1 /*
2  * Copyright (C) 2018 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <stdarg.h>
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <unistd.h>
21 
22 #include <gtest/gtest.h>
23 
24 #include "Color.h"
25 
26 namespace android {
27 namespace gtest_extras {
28 
ShouldUseColor()29 static bool ShouldUseColor() {
30   const auto& gtest_color = ::testing::GTEST_FLAG(color);
31   if (gtest_color == "yes" || gtest_color == "true" || gtest_color == "t") {
32     return true;
33   }
34   if (gtest_color != "auto") {
35     return false;
36   }
37 
38   bool stdout_is_tty = isatty(STDOUT_FILENO) != 0;
39   if (!stdout_is_tty) {
40     return false;
41   }
42 
43   std::string color_term;
44   const char* const color_term_env = getenv("COLORTERM");
45   if (color_term_env != nullptr) {
46     color_term = color_term_env;
47   }
48   std::string term;
49   const char* const term_env = getenv("TERM");
50   if (term_env != nullptr) {
51     term = term_env;
52   }
53   return !color_term.empty() || term == "xterm" || term == "xterm-color" ||
54          term == "xterm-256color" || term == "screen" || term == "screen-256color" ||
55          term == "tmux" || term == "tmux-256color" || term == "rxvt-unicode" ||
56          term == "rxvt-unicode-256color" || term == "linux" || term == "cygwing";
57 }
58 
ColoredPrintf(const char * color,const char * fmt,...)59 void ColoredPrintf(const char* color, const char* fmt, ...) {
60   static const bool use_color = ShouldUseColor();
61 
62   va_list args;
63   va_start(args, fmt);
64 
65   if (!use_color) {
66     vprintf(fmt, args);
67   } else {
68     printf("%s", color);
69     vprintf(fmt, args);
70     printf("%s", COLOR_RESET);
71   }
72 
73   va_end(args);
74 }
75 
76 }  // namespace gtest_extras
77 }  // namespace android
78