A simpler solution is probably just to use CMake's built-in capability for emitting coloured output, i.e. these commands
Different colors
cmake -E cmake_echo_color --normal hello
cmake -E cmake_echo_color --black hello
cmake -E cmake_echo_color --red hello
cmake -E cmake_echo_color --green hello
cmake -E cmake_echo_color --yellow hello
cmake -E cmake_echo_color --blue hello
cmake -E cmake_echo_color --magenta hello
cmake -E cmake_echo_color --cyan hello
cmake -E cmake_echo_color --white hello
Bold text
cmake -E cmake_echo_color --red --bold hello
No new line
cmake -E cmake_echo_color --red --no-newline hello
From CMake you can use the execute_process()
command to invoke ${CMAKE_COMMAND}
. You could write a convenient function for doing this.
UPDATE: Using cmake_echo_color
with execute_process()
As pointed out by @sjm324 running
execute_process(COMMAND ${CMAKE_COMMAND} -E cmake_echo_color --red --bold hello)
does not work. Looking at the implementation https://github.com/Kitware/CMake/blob/10371cd6dcfc1bf601fa3e715734dbe66199e2e4/Source/kwsys/Terminal.c#L160
my guess is that standard output is not attached to the terminal and thus when CMake internally calls isatty()
this fails.
I have two hacks that workaround this but really if you care about this you should contact the CMake devs for a less fragile solution
HACK 1: Set CLICOLOR_FORCE=1
environment variable.
execute_process(COMMAND
${CMAKE_COMMAND} -E env CLICOLOR_FORCE=1
${CMAKE_COMMAND} -E cmake_echo_color --red --bold hello
)
This isn't a great idea. If you log the output of your build to a file
it will have escape sequences in it because you're forcing them to be
emitted always.
HACK 2: Set OUTPUT_FILE to be the TTY
Don't do this. HACK 1 is likely more portable.
execute_process(COMMAND
/usr/bin/tty
OUTPUT_VARIABLE TTY_NAME
OUTPUT_STRIP_TRAILING_WHITESPACE)
execute_process(COMMAND
${CMAKE_COMMAND} -E cmake_echo_color --red --bold hello
OUTPUT_FILE ${TTY_NAME})