Skip to content

Commit cc86e8b

Browse files
authored
fix(cmake): better --fresh support (#5668)
Signed-off-by: Henry Schreiner <[email protected]>
1 parent 6bf25d1 commit cc86e8b

File tree

1 file changed

+19
-16
lines changed

1 file changed

+19
-16
lines changed

CMakeLists.txt

Lines changed: 19 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -130,28 +130,23 @@ if(PYBIND11_MASTER_PROJECT)
130130
set(Python_EXECUTABLE "${PYTHON_EXECUTABLE}")
131131
endif()
132132

133-
if(NOT DEFINED Python3_EXECUTABLE
134-
AND NOT DEFINED Python_EXECUTABLE
135-
AND NOT DEFINED Python_ROOT_DIR
136-
AND NOT DEFINED ENV{VIRTUALENV}
137-
AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/.venv")
138-
message(STATUS "Autodetecting Python in virtual environment")
139-
set(Python_ROOT_DIR "${CMAKE_CURRENT_SOURCE_DIR}/.venv")
140-
endif()
141-
142133
# This is a shortcut that is primarily for the venv cmake preset,
143134
# but can be used to quickly setup tests manually, too
144135
set(PYBIND11_CREATE_WITH_UV
145136
""
146-
CACHE STRING "Create a virtualenv in Python_ROOT_DIR with uv if it doesn't exist")
137+
CACHE STRING "Create a virtualenv if it doesn't exist")
147138

148139
if(NOT PYBIND11_CREATE_WITH_UV STREQUAL "")
149-
if(NOT DEFINED Python_ROOT_DIR)
150-
message(FATAL_ERROR "Python_ROOT_DIR must be defined to use PYBIND11_CREATE_WITH_UV")
151-
endif()
140+
set(Python_ROOT_DIR "${CMAKE_CURRENT_BINARY_DIR}/.venv")
152141
if(EXISTS "${Python_ROOT_DIR}")
153-
message(STATUS "Using existing venv at ${Python_ROOT_DIR}, remove to recreate")
154-
else()
142+
if(EXISTS "${CMAKE_BINARY_DIR}/CMakeCache.txt")
143+
message(STATUS "Using existing venv at ${Python_ROOT_DIR}, remove or --fresh to recreate")
144+
else()
145+
# --fresh used to remove the cache
146+
file(REMOVE_RECURSE "${CMAKE_CURRENT_BINARY_DIR}/.venv")
147+
endif()
148+
endif()
149+
if(NOT EXISTS "${Python_ROOT_DIR}")
155150
find_program(UV uv REQUIRED)
156151
# CMake 3.19+ would be able to use COMMAND_ERROR_IS_FATAL
157152
message(
@@ -172,8 +167,16 @@ if(PYBIND11_MASTER_PROJECT)
172167
message(FATAL_ERROR "uv pip install failed with '${_pip_result}'")
173168
endif()
174169
endif()
170+
else()
171+
if(NOT DEFINED Python3_EXECUTABLE
172+
AND NOT DEFINED Python_EXECUTABLE
173+
AND NOT DEFINED Python_ROOT_DIR
174+
AND NOT DEFINED ENV{VIRTUALENV}
175+
AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/.venv")
176+
message(STATUS "Autodetecting Python in virtual environment")
177+
set(Python_ROOT_DIR "${CMAKE_CURRENT_SOURCE_DIR}/.venv")
178+
endif()
175179
endif()
176-
177180
endif()
178181

179182
# NB: when adding a header don't forget to also add it to setup.py

0 commit comments

Comments
 (0)