spraff
spraff

Reputation: 33405

CMake do something when command fails

I use CMake. A custom build step saves error output when it fails.

FIND_PROGRAM (BASH bash HINTS /bin)

SET (BASH_CMD "my-script input.file >output.file 2>error.file")

ADD_CUSTOM_COMMAND (
   OUTPUT output.file
   COMMAND ${CMAKE_COMMAND} -E env ${BASH} -c "${BASH_CMD}"
   ...)

This works. If my-script fails for the given input.file then the stderr is saved in error.file, however when I run make and the target fails to build, the normal output does not make the location of error.file obvious. (The actual path of this file is generated in a tangly way.)

I don't want the noisy stderr to show in the terminal during make. I would like to do something like

MESSAGE ("input.file failed, see error.file")

(ideally coloured red or something) to be executed when the command for output.file failed.

Can I express this behaviour in CMakeLists.txt recipes?

Upvotes: 1

Views: 1968

Answers (1)

fabian
fabian

Reputation: 82461

Not sure about the highlighting, but you could create a cmake script file executing the command via execute_process, check it's error code and print a custom message in case there's an issue. The following example runs on windows, not on linux, but this should be sufficient for demonstration.

Some command that fails: script.bat

echo "some long message" 1>&2
exit 1

CMake script: execute_script_bat.cmake

execute_process(COMMAND script.bat RESULT_VARIBALE _EXIT_CODE ERROR_FILE error.log)

if (NOT _EXIT_CODE EQUAL 0)
    message(FATAL_ERROR "command failed; output see ${CMAKE_SOURCE_DIR}/error.log")
endif()

CMakeLists.txt

add_custom_command(
   OUTPUT output.file
   COMMAND "${CMAKE_COMMAND}" -P "${CMAKE_CURRENT_SOURCE_DIR}/execute_script_bat.cmake")

Additional info can be passed by adding -D "SOME_VARIABLE=some value" arguments after "${CMAKE_COMMAND}"

Upvotes: 1

Related Questions