Debian Codegraph @

internal/color/color.go

raw
1 // Copyright (c) 2019, 2020 Maxime Soulé
2 // All rights reserved.
3 //
4 // This source code is licensed under the BSD-style license found in the
5 // LICENSE file in the root directory of this source tree.
6
7 package color
8
9 import (
10 "fmt"
11 "os"
12 "strings"
13 "sync"
14
15 "github.com/maxatome/go-testdeep/internal/util"
16 )
17
18 const (
19 // EnvColor is the name of the environment variable allowing to
20 // enable/disable coloring feature.
21 EnvColor = "TESTDEEP_COLOR"
22 // EnvColorTestName is the name of the environment variable
23 // containing the color of test names in error reports.
24 EnvColorTestName = "TESTDEEP_COLOR_TEST_NAME"
25 // EnvColorTitle is the name of the environment variable
26 // containing the color of failure reason in error reports.
27 EnvColorTitle = "TESTDEEP_COLOR_TITLE"
28 // EnvColorOK is the name of the environment variable
29 // containing the color of "expected" in error reports.
30 EnvColorOK = "TESTDEEP_COLOR_OK"
31 // EnvColorBad is the name of the environment variable
32 // containing the color of "got" in error reports.
33 EnvColorBad = "TESTDEEP_COLOR_BAD"
34 )
35
36 var (
37 // TestNameOn contains the ANSI color escape sequence to turn test
38 // name color on.
39 TestNameOn string
40 // TestNameOff contains the ANSI color escape sequence to turn test
41 // name color off.
42 TestNameOff string
43 // TitleOn contains the ANSI color escape sequence to turn title color on.
44 TitleOn string
45 // TitleOff contains the ANSI color escape sequence to turn title color off.
46 TitleOff string
47 // OKOn contains the ANSI color escape sequence to turn "expected" color on.
48 OKOn string
49 // OKOnBold contains the ANSI color escape sequence to turn
50 // "expected" color and bold on.
51 OKOnBold string
52 // OKOff contains the ANSI color escape sequence to turn "expected" color off.
53 OKOff string
54 // BadOn contains the ANSI color escape sequence to turn "got" color on.
55 BadOn string
56 // BadOnBold contains the ANSI color escape sequence to turn "got"
57 // color and bold on.
58 BadOnBold string
59 // BadOff contains the ANSI color escape sequence to turn "got" color off.
60 BadOff string
61 )
62
63 var initOnce sync.Once
64
65 // Init initializes all the colors from the environment. It can be
66 // called several times concurrently, but only the first call is
67 // effective.
68 func Init() {
69 initOnce.Do(func() {
70 _, TestNameOn, TestNameOff = FromEnv(EnvColorTestName, "yellow")
71 _, TitleOn, TitleOff = FromEnv(EnvColorTitle, "cyan")
72 OKOn, OKOnBold, OKOff = FromEnv(EnvColorOK, "green")
73 BadOn, BadOnBold, BadOff = FromEnv(EnvColorBad, "red")
74 })
75 }
76
77 // SaveState saves the "TESTDEEP_COLOR" environment variable
78 // value, sets it to "on" (if true passed as on) or "off" (if on not
79 // passed or set to false), resets the colors initialization and
80 // returns a function to be called in a defer statement. Only intended
81 // to be used in tests like:
82 //
83 // defer color.SaveState()()
84 //
85 // It is not thread-safe.
86 func SaveState(on ...bool) func() {
87 colorState, set := os.LookupEnv(EnvColor)
88 if len(on) == 0 || !on[0] {
89 os.Setenv(EnvColor, "off") //nolint: errcheck
90 } else {
91 os.Setenv(EnvColor, "on") //nolint: errcheck
92 }
93 initOnce = sync.Once{}
94 return func() {
95 if set {
96 os.Setenv(EnvColor, colorState) //nolint: errcheck
97 } else {
98 os.Unsetenv(EnvColor) //nolint: errcheck
99 }
100 initOnce = sync.Once{}
101 }
102 }
103
104 // On returns true if coloring feature is enabled.
105 func On() bool {
106 switch os.Getenv(EnvColor) {
107 case "on", "":
108 return true
109 default: // "off" or any other value
110 return false
111 }
112 }
113
114 var colors = map[string]byte{
115 "black": '0',
116 "red": '1',
117 "green": '2',
118 "yellow": '3',
119 "blue": '4',
120 "magenta": '5',
121 "cyan": '6',
122 "white": '7',
123 "gray": '7',
124 }
125
126 // FromEnv returns the light, bold and end ANSI sequences for the
127 // color contained in the environment variable env. defaultColor is
128 // used if the environment variable does exist or is empty.
129 //
130 // If coloring is disabled, returns "", "", "".
131 func FromEnv(env, defaultColor string) (string, string, string) {
132 var color string
133 if On() {
134 if curColor := os.Getenv(env); curColor != "" {
135 color = curColor
136 } else {
137 color = defaultColor
138 }
139 }
140
141 if color == "" {
142 return "", "", ""
143 }
144
145 names := strings.SplitN(color, ":", 2)
146
147 light := [...]byte{
148 // 0 1 2 4 4 5 6
149 '\x1b', '[', '0', ';', '3', 'y', 'm', // foreground
150 // 7 8 9 10 11
151 '\x1b', '[', '4', 'z', 'm', // background
152 }
153 bold := [...]byte{
154 // 0 1 2 4 4 5 6
155 '\x1b', '[', '1', ';', '3', 'y', 'm', // foreground
156 // 7 8 9 10 11
157 '\x1b', '[', '4', 'z', 'm', // background
158 }
159
160 var start, end int
161
162 // Foreground
163 if names[0] != "" {
164 c := colors[names[0]]
165 if c == 0 {
166 c = colors[defaultColor]
167 }
168
169 light[5] = c
170 bold[5] = c
171
172 end = 7
173 } else {
174 start = 7
175 }
176
177 // Background
178 if len(names) > 1 && names[1] != "" {
179 c := colors[names[1]]
180 if c != 0 {
181 light[10] = c
182 bold[10] = c
183
184 end = 12
185 }
186 }
187
188 return string(light[start:end]), string(bold[start:end]), "\x1b[0m"
189 }
190
191 // AppendTestNameOn enables test name color in b.
192 func AppendTestNameOn(b *strings.Builder) {
193 Init()
194 b.WriteString(TestNameOn)
195 }
196
197 // AppendTestNameOff disables test name color in b.
198 func AppendTestNameOff(b *strings.Builder) {
199 Init()
200 b.WriteString(TestNameOff)
201 }
202
203 // Bad returns a string surrounded by BAD color. If len(args) is > 0,
204 // s and args are given to fmt.Sprintf.
205 //
206 // Typically used in panic() when the user made a mistake.
207 func Bad(s string, args ...any) string {
208 Init()
209 if len(args) == 0 {
210 return BadOnBold + s + BadOff
211 }
212 return fmt.Sprintf(BadOnBold+s+BadOff, args...)
213 }
214
215 // BadUsage returns a string surrounded by BAD color to notice the
216 // user she/he passes a bad parameter to a function. Typically used in a
217 // panic().
218 func BadUsage(usage string, param any, pos int, kind bool) string {
219 return Bad("usage: %s, %s", usage, util.BadParam(param, pos, kind))
220 }
221
222 // TooManyParams returns a string surrounded by BAD color to notice
223 // the user she/he called a variadic function with too many
224 // parameters. Typically used in a panic().
225 func TooManyParams(usage string) string {
226 return Bad("usage: " + usage + ", too many parameters")
227 }
228
229 // UnBad returns s with bad color prefix & suffix removed.
230 func UnBad(s string) string {
231 return strings.TrimSuffix(strings.TrimPrefix(s, BadOnBold), BadOff)
232 }