Run a CMake script before INSTALL target

I would like to run a CMake script before the INSTALL target (optionally just before building the code).

I have tried using the install([SCRIPT] <file> [...]) functionality, but that runs during install, which is too late.

The idea is to set the patch part of the CPACK_PACKAGE_VERSION to the current Git SHA value, but I want to fetch the latest value just before building the install. (I already have a working CMake script to fetch the latest Git SHA). Currently my script requires the use of CMake generate just before triggering the INSTALL to be sure that the Git SHA is updated correctly. Which could lead to inconsistencies if you have pulled in new code since you generated build files.

I recommend generating the git information as part of the build rather than configure or installation.

I’ve done it before here, but you can probably simplify it for your use case (e.g., not dumping the diff out). Note that it is tied to a configure command which lists a non-existent file in the OUTPUT list so that CMake always runs it, so you’ll never have a “do nothing” build with this strategy.

The basic strategy is to make an add_custom_command which generates a header (or in your case, a CMake script to include) with the information you need. Just list some/no/exist/path in the OUTPUT so it always gets rerun since it is never up-to-date.

Thank you for you suggestion!

The problem is that the CPack variables in CPackConfig.cmake are only written during the generation stage of CMake. So even if I create a (header) file containing the updated SHA value from the Git repository during the build state, I cannot find a way of forwarding these values to CPack.

You can include() files from CPackConfig.cmake. Just include a CMake script that the git-info retrieval script can write out.

Well, just including a script file inside CPackConfig.cmake do not solve the issue, since I need to modify already existing variables inside the CPackConfig.

But I used your original example to parse the CPackConfig.cmake file, then do regex replace for the variables I needed to change and then write out the modified file to a new file. And finally replacing the old CPackConfig.cmake file with the new one. And this works. A bit hacky solution though…