From 3fdd06b013ce167aeeb0d71ebe736d63c2ef7a1e Mon Sep 17 00:00:00 2001
From: Kevin Kofler <kevin.kofler@chello.at>
Date: Wed, 5 Nov 2014 23:49:41 +0100
Subject: [PATCH] CMakeColors.cmake: Use colors only if stderr is an
 interactive terminal.

In particular, do not write ugly escape sequences to log files.

Fixes #124.
---
 CMakeModules/CMakeColors.cmake | 39 +++++++++++++++++++---------------
 1 file changed, 22 insertions(+), 17 deletions(-)

diff --git a/CMakeModules/CMakeColors.cmake b/CMakeModules/CMakeColors.cmake
index 34e87fcbd3..4d899e2457 100644
--- a/CMakeModules/CMakeColors.cmake
+++ b/CMakeModules/CMakeColors.cmake
@@ -1,19 +1,24 @@
 if(NOT WIN32)
-  string(ASCII 27 Esc)
-  set(ColorReset  "${Esc}[m")
-  set(ColorBold   "${Esc}[1m")
-  set(Red         "${Esc}[31m")
-  set(Green       "${Esc}[32m")
-  set(Yellow      "${Esc}[33m")
-  set(Blue        "${Esc}[34m")
-  set(Magenta     "${Esc}[35m")
-  set(Cyan        "${Esc}[36m")
-  set(White       "${Esc}[37m")
-  set(BoldRed     "${Esc}[1;31m")
-  set(BoldGreen   "${Esc}[1;32m")
-  set(BoldYellow  "${Esc}[1;33m")
-  set(BoldBlue    "${Esc}[1;34m")
-  set(BoldMagenta "${Esc}[1;35m")
-  set(BoldCyan    "${Esc}[1;36m")
-  set(BoldWhite   "${Esc}[1;37m")
+  # [ -t 2 ] tests whether stderr is interactive.
+  # The negation '!' is because for POSIX shells, 0 is true and 1 is false.
+  execute_process(COMMAND [ ! -t 2 ] RESULT_VARIABLE IS_STDERR_INTERACTIVE)
+  if(IS_STDERR_INTERACTIVE)
+    string(ASCII 27 Esc)
+    set(ColorReset  "${Esc}[m")
+    set(ColorBold   "${Esc}[1m")
+    set(Red         "${Esc}[31m")
+    set(Green       "${Esc}[32m")
+    set(Yellow      "${Esc}[33m")
+    set(Blue        "${Esc}[34m")
+    set(Magenta     "${Esc}[35m")
+    set(Cyan        "${Esc}[36m")
+    set(White       "${Esc}[37m")
+    set(BoldRed     "${Esc}[1;31m")
+    set(BoldGreen   "${Esc}[1;32m")
+    set(BoldYellow  "${Esc}[1;33m")
+    set(BoldBlue    "${Esc}[1;34m")
+    set(BoldMagenta "${Esc}[1;35m")
+    set(BoldCyan    "${Esc}[1;36m")
+    set(BoldWhite   "${Esc}[1;37m")
+  endif(IS_STDERR_INTERACTIVE)
 endif()
-- 
GitLab