-
Notifications
You must be signed in to change notification settings - Fork 7
/
ansi.go
135 lines (120 loc) · 2.35 KB
/
ansi.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
package ansi
import (
"fmt"
"strings"
)
const (
black = iota
red
green
yellow
blue
magenta
cyan
white
normalIntensityFG = 30
highIntensityFG = 90
normalIntensityBG = 40
highIntensityBG = 100
start = "\033["
bold = "1;"
blink = "5;"
underline = "4;"
inverse = "7;"
Reset = "\033[0m"
)
var (
plain = false
colors = map[string]int{
"black": black,
"red": red,
"green": green,
"yellow": yellow,
"blue": blue,
"magenta": magenta,
"cyan": cyan,
"white": white,
}
)
// Gets the ANSI escape code for a color style.
func ColorCode(style string) string {
if plain || style == "" {
return ""
}
if style == "reset" {
return Reset
}
foreground_background := strings.Split(style, ":")
foreground := strings.Split(foreground_background[0], "+")
fg := colors[foreground[0]]
fgStyle := ""
if len(foreground) > 1 {
fgStyle = foreground[1]
}
bg, bgStyle := "", ""
if len(foreground_background) > 1 {
background := strings.Split(foreground_background[1], "+")
bg = background[0]
if len(background) > 1 {
bgStyle = background[1]
}
}
code := start
base := normalIntensityFG
if len(fgStyle) > 0 {
if strings.Contains(fgStyle, "b") {
code += bold
}
if strings.Contains(fgStyle, "B") {
code += blink
}
if strings.Contains(fgStyle, "u") {
code += underline
}
if strings.Contains(fgStyle, "i") {
code += inverse
}
if strings.Contains(fgStyle, "h") {
base = highIntensityFG
}
}
code += fmt.Sprintf("%d;", base+fg)
base = normalIntensityBG
if len(bg) > 0 {
if strings.Contains(bgStyle, "h") {
base = highIntensityBG
}
code += fmt.Sprintf("%d;", base+colors[bg])
}
// remove last ";"
return code[:len(code)-1] + "m"
}
// Surrounds `s` with ANSI color and reset code.
func Color(s, style string) string {
if plain || len(style) < 1 {
return s
}
return ColorCode(style) + s + Reset
}
// Creates a fast closure.
//
// Prefer ColorFunc over Color as it does not recompute ANSI codes.
func ColorFunc(style string) func(string) string {
if style == "" {
return func(s string) string {
return s
}
} else {
code := ColorCode(style)
return func(s string) string {
if plain || len(s) < 1 {
return s
}
return code + s + Reset
}
}
}
// Disables ANSI color codes. On by default.
func DisableColors(disable bool) {
plain = disable
}