diff --git a/cmake/app/boilerplate.cmake b/cmake/app/boilerplate.cmake index 7b14aa6e543..b76430e3d8b 100644 --- a/cmake/app/boilerplate.cmake +++ b/cmake/app/boilerplate.cmake @@ -190,7 +190,9 @@ endif() add_custom_target( pristine - COMMAND ${CMAKE_COMMAND} -P ${ZEPHYR_BASE}/cmake/pristine.cmake + COMMAND ${CMAKE_COMMAND} -DBINARY_DIR=${APPLICATION_BINARY_DIR} + -DSOURCE_DIR=${APPLICATION_SOURCE_DIR} + -P ${ZEPHYR_BASE}/cmake/pristine.cmake # Equivalent to rm -rf build/* ) diff --git a/cmake/pristine.cmake b/cmake/pristine.cmake index 4e56c05ea6c..aeefd270811 100644 --- a/cmake/pristine.cmake +++ b/cmake/pristine.cmake @@ -1,15 +1,38 @@ # SPDX-License-Identifier: Apache-2.0 -# NB: This could be dangerous to execute, it is assuming the user is -# checking that the build is out-of-source with code like this: -# -# if(${CMAKE_CURRENT_SOURCE_DIR} STREQUAL ${CMAKE_CURRENT_BINARY_DIR}) -# message(FATAL_ERROR "Source directory equals build directory.\ -# In-source builds are not supported.\ -# Please specify a build directory, e.g. cmake -Bbuild -H.") -# endif() +# NB: This could be dangerous to execute. -file(GLOB build_dir_contents ${CMAKE_BINARY_DIR}/*) +macro(print_usage) + message(" +usage: cmake -DBINARY_DIR= -DSOURCE_DIR= + -P ${CMAKE_SCRIPT_MODE_FILE} + +mandatory arguments: + -DBINARY_DIR=: Absolute path to the build directory to pristine + -DSOURCE_DIR=: Absolute path to the source directory used when + creating +") + # Making the usage itself a fatal error messes up the formatting when printing. + message(FATAL_ERROR "") +endmacro() + +if(NOT DEFINED BINARY_DIR OR NOT DEFINED SOURCE_DIR) + print_usage() +endif() + +if(NOT IS_ABSOLUTE ${BINARY_DIR} OR NOT IS_ABSOLUTE ${SOURCE_DIR}) + print_usage() +endif() + +get_filename_component(BINARY_DIR ${BINARY_DIR} REALPATH) +get_filename_component(SOURCE_DIR ${SOURCE_DIR} REALPATH) + +string(FIND ${SOURCE_DIR} ${BINARY_DIR} INDEX) +if(NOT INDEX EQUAL -1) + message(FATAL_ERROR "Refusing to run pristine in in-source build folder.") +endif() + +file(GLOB build_dir_contents ${BINARY_DIR}/*) foreach(file ${build_dir_contents}) if (EXISTS ${file}) file(REMOVE_RECURSE ${file}) diff --git a/scripts/west_commands/build.py b/scripts/west_commands/build.py index 29264ee211c..2b2e3083bf6 100644 --- a/scripts/west_commands/build.py +++ b/scripts/west_commands/build.py @@ -421,7 +421,13 @@ class Build(Forceable): 'Zephyr build system') cache = CMakeCache.from_build_dir(self.build_dir) - cmake_args = ['-P', cache['ZEPHYR_BASE'] + '/cmake/pristine.cmake'] + + app_src_dir = cache.get('APPLICATION_SOURCE_DIR') + app_bin_dir = cache.get('APPLICATION_BINARY_DIR') + + cmake_args = [f'-DBINARY_DIR={app_bin_dir}', + f'-DSOURCE_DIR={app_src_dir}', + '-P', cache['ZEPHYR_BASE'] + '/cmake/pristine.cmake'] run_cmake(cmake_args, cwd=self.build_dir, dry_run=self.args.dry_run) def _run_build(self, target):