Debian Codegraph @

pkg/color/color.go

raw
1 package color
2
3 import (
4 "fmt"
5 "io"
6 "os"
7 "slices"
8 "strconv"
9 "strings"
10
11 "github.com/mattn/go-colorable"
12 "golang.org/x/term"
13 )
14
15 // Config holds configuration settings for color output.
16 type Config struct {
17 // NoColor controls whether color output is disabled.
18 // When true, all color formatting is stripped from output.
19 NoColor bool
20
21 // Output is the default io.Writer used by print functions for colorized output.
22 Output io.Writer
23
24 // Error is the default io.Writer used for error output with color support.
25 Error io.Writer
26 }
27
28 // Color represents a color with ANSI SGR parameters.
29 type Color struct {
30 params []Attribute
31 noColor *bool // Instance-level override
32 config *Config // Reference to config (can be shared)
33 }
34
35 // stdoutFd is the file descriptor for stdout, safely converted.
36 var stdoutFd = int(os.Stdout.Fd())
37
38 // mapResetAttributes maps color attributes to their corresponding reset
39 // attributes for proper cleanup of terminal formatting.
40 var mapResetAttributes = map[Attribute]Attribute{
41 Bold: ResetBold,
42 Faint: ResetBold,
43 Italic: ResetItalic,
44 Underline: ResetUnderline,
45 BlinkSlow: ResetBlinking,
46 BlinkRapid: ResetBlinking,
47 ReverseVideo: ResetReversed,
48 Concealed: ResetConcealed,
49 CrossedOut: ResetCrossedOut,
50 }
51
52 // noColorFromEnv returns whether colors should be disabled based on environment.
53 func noColorFromEnv() bool {
54 return os.Getenv("NO_COLOR") != "" ||
55 os.Getenv("TERM") == "dumb" ||
56 !term.IsTerminal(stdoutFd)
57 }
58
59 // DefaultConfig returns a Config with sensible defaults.
60 // The NoColor setting is detected from the environment:
61 // - If NO_COLOR environment variable is set, colors are disabled
62 // - If TERM environment variable is "dumb", colors are disabled
63 // - If stdout is not a terminal, colors are disabled
64 //
65 // Output and Error are set to colorable writers that support ANSI escape codes
66 // on Windows.
67 func DefaultConfig() *Config {
68 return &Config{
69 NoColor: noColorFromEnv(),
70 Output: colorable.NewColorableStdout(),
71 Error: colorable.NewColorableStderr(),
72 }
73 }
74
75 // New returns a newly created color object using the default configuration.
76 func New(value ...Attribute) *Color {
77 return NewWithConfig(DefaultConfig(), value...)
78 }
79
80 // NewWithConfig returns a newly created color object with the specified configuration.
81 //
82 // Example:
83 //
84 // cfg := &color.Config{
85 // NoColor: true,
86 // Output: os.Stdout,
87 // Error: os.Stderr,
88 // }
89 // c := color.NewWithConfig(cfg, color.FgRed)
90 // c.Println("This is red text")
91 func NewWithConfig(cfg *Config, value ...Attribute) *Color {
92 c := &Color{
93 params: make([]Attribute, 0, len(value)),
94 noColor: nil, // Will use config.NoColor by default
95 config: cfg,
96 }
97
98 if cfg.NoColor {
99 c.noColor = boolPtr(true)
100 }
101
102 c.Add(value...)
103
104 return c
105 }
106
107 // Add is used to chain SGR parameters.
108 // Use as many as parameters to combine and create custom color objects.
109 // Example: Add(color.FgRed, color.Underline).
110 func (c *Color) Add(value ...Attribute) *Color {
111 c.params = append(c.params, value...)
112
113 return c
114 }
115
116 // AddBgRGB is used to chain background RGB SGR parameters.
117 // Use as many as parameters to combine and create custom color objects.
118 // Example: .Add(34, 0, 12).Add(255, 128, 0).
119 func (c *Color) AddBgRGB(r, green, blue int) *Color {
120 c.params = append(
121 c.params,
122 background,
123 rgbColorFormatSpecifier,
124 Attribute(r),
125 Attribute(green),
126 Attribute(blue),
127 )
128
129 return c
130 }
131
132 // AddRGB is used to chain foreground RGB SGR parameters.
133 // Use as many as parameters to combine and create custom color objects.
134 // Example: .Add(34, 0, 12).Add(255, 128, 0).
135 func (c *Color) AddRGB(r, green, blue int) *Color {
136 c.params = append(
137 c.params,
138 foreground,
139 rgbColorFormatSpecifier,
140 Attribute(r),
141 Attribute(green),
142 Attribute(blue),
143 )
144
145 return c
146 }
147
148 // DisableColor disables the color output.
149 // Useful to not change any existing code and still being able to output.
150 // Can be used for flags like "--no-color".
151 // To enable back use EnableColor() method.
152 func (c *Color) DisableColor() {
153 c.noColor = boolPtr(true)
154 }
155
156 // EnableColor enables the color output.
157 // Use it in conjunction with DisableColor().
158 // Otherwise, this method has no side effects.
159 func (c *Color) EnableColor() {
160 c.noColor = boolPtr(false)
161 }
162
163 // Equals returns a boolean value indicating whether two colors are equal.
164 func (c *Color) Equals(colorToCompare *Color) bool {
165 if c == nil && colorToCompare == nil {
166 return true
167 }
168
169 if c == nil || colorToCompare == nil {
170 return false
171 }
172
173 if len(c.params) != len(colorToCompare.params) {
174 return false
175 }
176
177 for _, attr := range c.params {
178 if !colorToCompare.attrExists(attr) {
179 return false
180 }
181 }
182
183 return true
184 }
185
186 // Fprint formats using the default formats for its operands and writes to w.
187 // Spaces are added between operands when neither is a string.
188 // It returns the number of bytes written and any write error encountered.
189 // On Windows, users should wrap w with colorable.NewColorable() if w is of
190 // type *os.File.
191 //
192 //nolint:wrapcheck // fmt.Fprintln errors are passed through as-is for API compatibility
193 func (c *Color) Fprint(writer io.Writer, args ...any) (int, error) {
194 if c.isNoColorSet() {
195 return fmt.Fprint(writer, args...)
196 }
197
198 c.SetWriter(writer)
199 defer c.UnsetWriter(writer)
200
201 return fmt.Fprint(writer, args...)
202 }
203
204 // FprintFunc returns a new function that prints the passed arguments as
205 // colorized with color.Fprint().
206 func (c *Color) FprintFunc() func(w io.Writer, a ...any) {
207 return func(w io.Writer, a ...any) {
208 _, _ = c.Fprint(w, a...)
209 }
210 }
211
212 // Fprintf formats according to a format specifier and writes to w.
213 // It returns the number of bytes written and any write error encountered.
214 // On Windows, users should wrap w with colorable.NewColorable() if w is of
215 // type *os.File.
216 //
217 //nolint:wrapcheck // fmt.Fprintln errors are passed through as-is for API compatibility
218 func (c *Color) Fprintf(writer io.Writer, format string, args ...any) (int, error) {
219 if c.isNoColorSet() {
220 return fmt.Fprintf(writer, format, args...)
221 }
222
223 c.SetWriter(writer)
224 defer c.UnsetWriter(writer)
225
226 return fmt.Fprintf(writer, format, args...)
227 }
228
229 // FprintfFunc returns a new function that prints the passed arguments as
230 // colorized with color.Fprintf().
231 func (c *Color) FprintfFunc() func(w io.Writer, format string, a ...any) {
232 return func(w io.Writer, format string, a ...any) {
233 _, _ = c.Fprintf(w, format, a...)
234 }
235 }
236
237 // Fprintln formats using the default formats for its operands and writes to w.
238 // Spaces are always added between operands and a newline is appended.
239 // On Windows, users should wrap w with colorable.NewColorable() if w is of
240 // type *os.File.
241 //
242 //nolint:wrapcheck // fmt.Fprintln errors are passed through as-is for API compatibility
243 func (c *Color) Fprintln(writer io.Writer, args ...any) (int, error) {
244 if c.isNoColorSet() {
245 return fmt.Fprintln(writer, args...)
246 }
247
248 return fmt.Fprintln(writer, c.format()+sprintln(args...)+c.unformat())
249 }
250
251 // FprintlnFunc returns a new function that prints the passed arguments as
252 // colorized with color.Fprintln().
253 func (c *Color) FprintlnFunc() func(w io.Writer, a ...any) {
254 return func(w io.Writer, a ...any) {
255 _, _ = c.Fprintln(w, a...)
256 }
257 }
258
259 // Print formats using the default formats for its operands and writes to
260 // standard output. Spaces are added between operands when neither is a
261 // string. It returns the number of bytes written and any write error
262 // encountered. This is the standard fmt.Print() method wrapped with the given
263 // color.
264 //
265 //nolint:wrapcheck // fmt.Fprintln errors are passed through as-is for API compatibility
266 func (c *Color) Print(args ...any) (int, error) {
267 if c.isNoColorSet() {
268 return fmt.Fprint(c.config.Output, args...)
269 }
270
271 c.Set()
272 defer c.Unset()
273
274 return fmt.Fprint(c.config.Output, args...)
275 }
276
277 // PrintFunc returns a new function that prints the passed arguments as
278 // colorized with color.Print().
279 func (c *Color) PrintFunc() func(a ...any) {
280 return func(a ...any) {
281 _, _ = c.Print(a...)
282 }
283 }
284
285 // Printf formats according to a format specifier and writes to standard output.
286 // It returns the number of bytes written and any write error encountered.
287 // This is the standard fmt.Printf() method wrapped with the given color.
288 //
289 //nolint:wrapcheck // fmt.Fprintln errors are passed through as-is for API compatibility
290 func (c *Color) Printf(format string, args ...any) (int, error) {
291 if c.isNoColorSet() {
292 return fmt.Fprintf(c.config.Output, format, args...)
293 }
294
295 c.Set()
296 defer c.Unset()
297
298 return fmt.Fprintf(c.config.Output, format, args...)
299 }
300
301 // PrintfFunc returns a new function that prints the passed arguments as
302 // colorized with color.Printf().
303 func (c *Color) PrintfFunc() func(format string, a ...any) {
304 return func(format string, a ...any) {
305 _, _ = c.Printf(format, a...)
306 }
307 }
308
309 // Println formats using the default formats for its operands and writes to
310 // standard output. Spaces are always added between operands and a newline is
311 // appended. It returns the number of bytes written and any write error
312 // encountered. This is the standard fmt.Print() method wrapped with the given
313 // color.
314 //
315 //nolint:wrapcheck // fmt.Fprintln errors are passed through as-is for API compatibility
316 func (c *Color) Println(args ...any) (int, error) {
317 if c.isNoColorSet() {
318 return fmt.Fprintln(c.config.Output, args...)
319 }
320
321 return fmt.Fprintln(c.config.Output, c.format()+sprintln(args...)+c.unformat())
322 }
323
324 // PrintlnFunc returns a new function that prints the passed arguments as
325 // colorized with color.Println().
326 func (c *Color) PrintlnFunc() func(a ...any) {
327 return func(a ...any) {
328 _, _ = c.Println(a...)
329 }
330 }
331
332 // Set sets the SGR sequence.
333 func (c *Color) Set() *Color {
334 if c.isNoColorSet() || c.config.NoColor {
335 return c
336 }
337
338 _, _ = fmt.Fprint(c.config.Output, c.format())
339
340 return c
341 }
342
343 // SetWriter is used to set the SGR sequence with the given io.Writer.
344 // This is a low-level function, and users should use the higher-level
345 // functions, such as color.Fprint, color.Print, etc.
346 func (c *Color) SetWriter(w io.Writer) *Color {
347 if c.isNoColorSet() || c.config.NoColor {
348 return c
349 }
350
351 _, _ = fmt.Fprint(w, c.format())
352
353 return c
354 }
355
356 // Sprint is just like Print, but returns a string instead of printing it.
357 func (c *Color) Sprint(a ...any) string {
358 return c.wrap(fmt.Sprint(a...))
359 }
360
361 // SprintFunc returns a new function that returns colorized strings for the
362 // given arguments with fmt.Sprint().
363 // Useful to put into or mix into other string.
364 // Windows users should use this in conjunction with color.Output
365 // Example:
366 //
367 // put := New(FgYellow).SprintFunc()
368 // fmt.Fprintf(color.Output, "This is a %s", put("warning"))
369 func (c *Color) SprintFunc() func(a ...any) string {
370 return func(a ...any) string {
371 return c.wrap(fmt.Sprint(a...))
372 }
373 }
374
375 // Sprintf is just like Printf, but returns a string instead of printing it.
376 func (c *Color) Sprintf(format string, a ...any) string {
377 return c.wrap(fmt.Sprintf(format, a...))
378 }
379
380 // SprintfFunc returns a new function that returns colorized strings for the
381 // given arguments with fmt.Sprintf().
382 // Useful to put into or mix into other string.
383 // Windows users should use this in conjunction with color.Output.
384 //
385 // Note: The returned function is memoized for performance.
386 func (c *Color) SprintfFunc() func(format string, args ...any) string {
387 if c.isNoColorSet() {
388 return fmt.Sprintf
389 }
390
391 return func(format string, args ...any) string {
392 return c.wrap(fmt.Sprintf(format, args...))
393 }
394 }
395
396 // Sprintln is just like Println, but returns a string instead of printing it.
397 func (c *Color) Sprintln(a ...any) string {
398 return c.wrap(sprintln(a...)) + "\n"
399 }
400
401 // SprintlnFunc returns a new function that returns colorized strings for the
402 // given arguments with fmt.Sprintln().
403 // Useful to put into or mix into other string.
404 // Windows users should use this in conjunction with color.Output.
405 //
406 // Note: The returned function is memoized for performance.
407 func (c *Color) SprintlnFunc() func(a ...any) string {
408 if c.isNoColorSet() {
409 return func(a ...any) string { return sprintln(a...) + "\n" }
410 }
411
412 return func(a ...any) string {
413 return c.wrap(sprintln(a...)) + "\n"
414 }
415 }
416
417 // Unset resets the color output to default.
418 // It clears the escape attributes and restores normal terminal formatting.
419 // This should be called after Set() to clean up the terminal state.
420 func (c *Color) Unset() {
421 if c.isNoColorSet() || c.config.NoColor {
422 return
423 }
424
425 c.config.unset()
426 }
427
428 // UnsetWriter resets all escape attributes and clears the output with the give
429 // io.Writer. Usually should be called after SetWriter().
430 func (c *Color) UnsetWriter(w io.Writer) {
431 if c.isNoColorSet() || c.config.NoColor {
432 return
433 }
434
435 _, _ = fmt.Fprintf(w, "%s[%dm", escape, Reset)
436 }
437
438 func (c *Color) attrExists(a Attribute) bool {
439 return slices.Contains(c.params, a)
440 }
441
442 func (c *Color) format() string {
443 return fmt.Sprintf("%s[%sm", escape, c.sequence())
444 }
445
446 func (c *Color) isNoColorSet() bool {
447 // check first if we have user set action
448 if c.noColor != nil {
449 return *c.noColor
450 }
451
452 // if not return the config option
453 return c.config.NoColor
454 }
455
456 // sequence returns a formatted SGR sequence to be plugged into a "\x1b[...m".
457 // An example output might be: "1;36" -> bold cyan.
458 func (c *Color) sequence() string {
459 if len(c.params) == 0 {
460 return ""
461 }
462
463 var b strings.Builder
464 b.Grow(len(c.params) * builderGrowthFactor) // Pre-allocate for typical cases
465
466 for i, v := range c.params {
467 if i > 0 {
468 b.WriteByte(';')
469 }
470
471 b.WriteString(strconv.Itoa(int(v)))
472 }
473
474 return b.String()
475 }
476
477 // unformat returns the ANSI escape sequence to reset the color formatting.
478 // For each parameter in the color, it uses the specific reset attribute
479 // if available, or the generic Reset attribute otherwise.
480 func (c *Color) unformat() string {
481 if len(c.params) == 0 {
482 return ""
483 }
484
485 var b strings.Builder
486 b.Grow(len(c.params) * builderGrowthFactor)
487 b.WriteString(escape)
488 b.WriteByte('[')
489
490 for i, attr := range c.params {
491 if i > 0 {
492 b.WriteByte(';')
493 }
494
495 // Default to generic reset
496 resetAttr := Reset
497
498 // Use specific reset if available
499 if specificReset, ok := mapResetAttributes[attr]; ok {
500 resetAttr = specificReset
501 }
502
503 b.WriteString(strconv.Itoa(int(resetAttr)))
504 }
505
506 b.WriteByte('m')
507
508 return b.String()
509 }
510
511 // wrap wraps the s string with the colors attributes.
512 // The string is ready to be printed.
513 func (c *Color) wrap(s string) string {
514 if c.isNoColorSet() || c.config.NoColor {
515 return s
516 }
517
518 return c.format() + s + c.unformat()
519 }
520
521 // unset resets all escape attributes and clears the output.
522 func (c *Config) unset() {
523 if c.NoColor {
524 return
525 }
526
527 _, _ = fmt.Fprintf(c.Output, "%s[%dm", escape, Reset)
528 }
529
530 // BgRGB returns a new background color in 24-bit RGB.
531 func BgRGB(r, g, b int) *Color {
532 return New(
533 background,
534 rgbColorFormatSpecifier,
535 Attribute(r),
536 Attribute(g),
537 Attribute(b),
538 )
539 }
540
541 // RGB returns a new foreground color in 24-bit RGB.
542 func RGB(r, g, b int) *Color {
543 return New(
544 foreground,
545 rgbColorFormatSpecifier,
546 Attribute(r),
547 Attribute(g),
548 Attribute(b),
549 )
550 }