CPack error copying files

I have set up a .cmake file I intend to use as a template/framework. It is included at the beginning of the top level CMakeLists.txt. The actual project contains more than this (and targets not named example), but this is the relevant part.

cmake_minimum_required(VERSION 4.4)

project(Example)

include(example_template.cmake)

add_executable(example example.cpp)

set(CPACK_PACKAGE_VENDOR "Example")
set(CPACK_PACKAGE_EXECUTABLES "example" "An example")
add_packages()

example_template.cmake contains:

include_guard(DIRECTORY)

function(add_packages)
    # Logic for getting executables from directory targets goes here.
    #...

    install(TARGETS ${executables} RUNTIME DESTINATION bin)
    set(CPACK_POST_BUILD_SCRIPTS "${CMAKE_CURRENT_SOURCE_DIR}/scripts/CopyArtifacts.cmake")
    include(CPack)

endfunction()

Then lastly, scripts/CopyArtifacts.cmake contains:

list(GET CPACK_BUILD_SOURCE_DIRS 0 SOURCE_DIR)
file(GLOB packageFiles RELATIVE "${CPACK_PACKAGE_DIRECTORIES}" "${CPACK_PACKAGE_FILE_NAME}*")
execute_process(
    COMMAND ${CMAKE_COMMAND} -E make_directory "${SOURCE_DIR}/.artifacts"
    COMMAND ${CMAKE_COMMAND} -E copy "${packageFiles}" "${SOURCE_DIR}/.artifacts"
)

This used to work fine when the content of add_packages was not a function but directly inside of CMakeLists.txt. Though to make it less cluttered, I did this. And now only the first time running cmake --build .build --target package an error occurs with output:

  Error copying file "" to "<path to project>/.artifacts": Invalid argument

I output the value of SOURCE_DIR and packageFiles via message. And the value of SOURCE_DIR is fine. But the value of packageFiles is empty the first time.

It seems that CPACK_POST_BUILD_SCRIPTS is not running after the packaging is done. Is this a bug in CPack, or am I missing something else?

About the use of CPACK_BUILD_SOURCE_DIRS on non RPM package formats. This was approved in the CMake GitLab: https://gitlab.kitware.com/cmake/cmake/-/work_items/21520#note_1710398

I assume the problem is because of CPACK_POST_BUILD_SCRIPTS and add_custom_command POST_BUILD commands not having a dependency between them?

But I assumed that CPACK_POST_BUILD_SCRIPTS would refer to post-CPack scripts, not literally post building targets. Doesn’t the package target depend on the all build target? So shouldn’t that run and complete first? Including post build steps.