From e83fc64bf4fbb574797eac99e3146857d4b47759 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?= Date: Sat, 8 Apr 2023 16:48:02 +0200 Subject: [PATCH] Colors: Do not output colors to a file --- lib/color.cpp | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/lib/color.cpp b/lib/color.cpp index 5fec2edec9e..33a5a175656 100644 --- a/lib/color.cpp +++ b/lib/color.cpp @@ -23,6 +23,7 @@ #endif #include #include // IWYU pragma: keep +#include bool gDisableColors = false; @@ -32,9 +33,16 @@ std::ostream& operator<<(std::ostream& os, const Color& /*c*/) #else std::ostream& operator<<(std::ostream & os, const Color& c) { - // TODO: handle piping into file as well as other pipes like stderr - static const bool s_is_tty = isatty(STDOUT_FILENO); - if (!gDisableColors && s_is_tty) + static const bool isatty_stdout = isatty(STDOUT_FILENO); + static const bool isatty_stderr = isatty(STDERR_FILENO); + bool stream_is_tty; + if (&os == &std::cout) + stream_is_tty = isatty_stdout; + else if (&os == &std::cerr) + stream_is_tty = isatty_stderr; + else + stream_is_tty = (isatty_stdout && isatty_stderr); + if (!gDisableColors && stream_is_tty) return os << "\033[" << static_cast(c) << "m"; #endif return os;