Cppcheck
color.cpp
Go to the documentation of this file.
1 /*
2  * Cppcheck - A tool for static C/C++ code analysis
3  * Copyright (C) 2007-2024 Cppcheck team.
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
17  */
18 
19 #include "color.h"
20 
21 #ifndef _WIN32
22 #include <unistd.h>
23 #include <cstddef>
24 #include <sstream>
25 #include <iostream>
26 #endif
27 
28 bool gDisableColors = false;
29 
30 #ifndef _WIN32
31 static bool isStreamATty(const std::ostream & os)
32 {
33  static const bool stdout_tty = isatty(STDOUT_FILENO);
34  static const bool stderr_tty = isatty(STDERR_FILENO);
35  if (&os == &std::cout)
36  return stdout_tty;
37  if (&os == &std::cerr)
38  return stderr_tty;
39  return (stdout_tty && stderr_tty);
40 }
41 #endif
42 
43 std::ostream& operator<<(std::ostream & os, Color c)
44 {
45 #ifndef _WIN32
46  if (!gDisableColors && isStreamATty(os))
47  return os << "\033[" << static_cast<std::size_t>(c) << "m";
48 #else
49  (void)c;
50 #endif
51  return os;
52 }
53 
54 std::string toString(Color c)
55 {
56 #ifndef _WIN32
57  std::stringstream ss;
58  ss << c;
59  return ss.str();
60 #else
61  (void)c;
62  return "";
63 #endif
64 }
65 
std::ostream & operator<<(std::ostream &os, Color c)
Definition: color.cpp:43
bool gDisableColors
Definition: color.cpp:28
static bool isStreamATty(const std::ostream &os)
Definition: color.cpp:31
std::string toString(Color c)
Definition: color.cpp:54
Color
Definition: color.h:27