-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcolor.go
110 lines (96 loc) · 1.66 KB
/
color.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package color
import (
_fmt "fmt"
"os"
"strings"
"sync"
)
var isDisabled bool
var pool *sync.Pool
func init() {
_, ok := os.LookupEnv("ANSI_COLORS_DISABLED")
isDisabled = ok
pool = &sync.Pool{New: func() interface{} { return strings.Builder{} }}
}
// Format defines format type.
type Format int
const reset Format = iota
// Attributes
const (
Bold Format = iota + 1
Dark
_
Underline
Blink
_
Reverse
Concealed
)
// Colors
const (
Gray Format = iota + 30
Red
Green
Yellow
Blue
Magenta
Cyan
White
)
// Highlights
const (
OnGray Format = iota + 40
OnRed
OnGreen
OnYellow
OnBlue
OnMagenta
OnCyan
OnWhite
)
const tokenFmt = "\x1b[%dm"
func token(fmt Format) string {
return _fmt.Sprintf(tokenFmt, fmt)
}
// Colored applies a series of formats to the string and returns the result.
func Colored(s string, fmts ...Format) string {
// short path
if isDisabled || len(fmts) == 0 {
return s
}
// process the formats
var (
attrs []Format
color Format
highlight Format
)
for _, fmt := range fmts {
switch fmt {
case Bold, Dark, Underline, Blink, Reverse, Concealed:
attrs = append(attrs, fmt)
case Gray, Red, Green, Yellow, Blue, Magenta, Cyan, White:
color = fmt
case OnGray, OnRed, OnGreen, OnYellow, OnBlue, OnMagenta, OnCyan, OnWhite:
highlight = fmt
}
}
// build the string
b := pool.Get().(strings.Builder)
defer func() {
b.Reset()
pool.Put(b)
}()
for i := len(attrs) - 1; i >= 0; i-- {
b.WriteString(token(attrs[i]))
}
if highlight != 0 {
b.WriteString(token(highlight))
}
if color != 0 {
b.WriteString(token(color))
}
b.WriteString(s)
b.WriteString(token(reset))
// ok
return b.String()
}