@@ -266,37 +266,42 @@ endfunction()
266266# Uses CMAKE_CURRENT_SOURCE_DIR/BINARY_DIR instead of the top-level CMAKE_SOURCE_DIR so Git
267267# hooks and .venv land in the submodule tree. Commits inside that submodule then run this
268268# hook; the parent's mb_pre_commit_setup() does not apply there.
269- function (mb_pre_commit_setup_subdirectory )
270- cmake_parse_arguments (
271- SUBPC
272- ""
273- "PRE_COMMIT_SWEEP_TARGET;PRE_COMMIT_INSTALL_EXAMPLE_CONFIG"
274- ""
275- ${ARGN}
269+ function (_mb_pre_commit_setup_subdirectory_impl )
270+ set (options)
271+ set (oneValueArgs
272+ CALLER_LIST_DIR
273+ CALLER_SOURCE_DIR
274+ CALLER_BINARY_DIR
275+ PRE_COMMIT_SWEEP_TARGET
276+ PRE_COMMIT_INSTALL_EXAMPLE_CONFIG
276277 )
278+ cmake_parse_arguments (SUBPC "${options} " "${oneValueArgs} " "" ${ARGN} )
279+
280+ if (
281+ NOT SUBPC_CALLER_LIST_DIR
282+ OR NOT SUBPC_CALLER_SOURCE_DIR
283+ OR NOT SUBPC_CALLER_BINARY_DIR
284+ )
285+ message (
286+ FATAL_ERROR
287+ "_mb_pre_commit_setup_subdirectory_impl: internal caller paths missing"
288+ )
289+ endif ()
277290
278291 if (NOT SUBPC_PRE_COMMIT_SWEEP_TARGET)
279- # CMAKE_PROJECT_NAME is always the top-level project(); nested add_subdirectory
280- # trees need PROJECT_NAME or the source dir leaf so targets do not collide.
281- if (PROJECT_NAME AND NOT PROJECT_NAME STREQUAL CMAKE_PROJECT_NAME )
282- set (_subpc_sweep_id "${PROJECT_NAME } " )
283- else ()
284- get_filename_component (
285- _subpc_sweep_id
286- "${CMAKE_CURRENT_SOURCE_DIR } "
287- NAME
288- )
289- endif ()
292+ # Do not use PROJECT_NAME or CMAKE_PROJECT_NAME: in a function they may not reflect
293+ # the caller's directory scope (PROJECT_NAME inherits the top-level project() name).
294+ get_filename_component (_subpc_sweep_id "${SUBPC_CALLER_LIST_DIR} " NAME )
290295 set (SUBPC_PRE_COMMIT_SWEEP_TARGET
291296 "mb-pre-commit-sweep-${_subpc_sweep_id} "
292297 )
293298 endif ()
294299
295300 set (_sub_setup_args
296301 PROJECT_SOURCE_DIR
297- "${CMAKE_CURRENT_SOURCE_DIR } "
302+ "${SUBPC_CALLER_SOURCE_DIR } "
298303 PROJECT_BINARY_DIR
299- "${CMAKE_CURRENT_BINARY_DIR } "
304+ "${SUBPC_CALLER_BINARY_DIR } "
300305 PRE_COMMIT_SWEEP_TARGET
301306 "${SUBPC_PRE_COMMIT_SWEEP_TARGET} "
302307 )
@@ -316,3 +321,17 @@ function(mb_pre_commit_setup_subdirectory)
316321
317322 mb_pre_commit_setup (${_sub_setup_args} )
318323endfunction ()
324+
325+ # Macro so CMAKE_CURRENT_* are read at the call site (the submodule CMakeLists.txt), not
326+ # inside a function scope where PROJECT_NAME can still be the top-level project() name.
327+ macro (mb_pre_commit_setup_subdirectory )
328+ _mb_pre_commit_setup_subdirectory_impl (
329+ CALLER_LIST_DIR
330+ "${CMAKE_CURRENT_LIST_DIR } "
331+ CALLER_SOURCE_DIR
332+ "${CMAKE_CURRENT_SOURCE_DIR } "
333+ CALLER_BINARY_DIR
334+ "${CMAKE_CURRENT_BINARY_DIR } "
335+ ${ARGN}
336+ )
337+ endmacro ()
0 commit comments