-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcolor.go
66 lines (56 loc) · 1.24 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
package fmtx
import (
"os"
"github.com/mattn/go-isatty"
)
var enableColor = true
var forceColor = false
var cacheEnableColor = 0
func SetEnableColor(enable bool) {
enableColor = enable
cacheEnableColor = 0
}
func SetForceColor(force bool) {
forceColor = force
cacheEnableColor = 0
}
// reset enable color cache
func ResetColorCache() {
cacheEnableColor = 0
}
func enableColorFromCache() bool {
if cacheEnableColor != 0 {
return cacheEnableColor == 1
}
if getEnableColor() {
cacheEnableColor = 1
return true
} else {
cacheEnableColor = 2
return false
}
}
func getEnableColor() bool {
envVal := os.Getenv("FORCE_COLOR")
envForceColor := envVal != "" && envVal != "0"
return (forceColor || envForceColor) || ((isatty.IsTerminal(os.Stdout.Fd()) || isatty.IsCygwinTerminal(os.Stdout.Fd())) && enableColor)
}
func Color(s string, start string, end string) string {
if !enableColorFromCache() {
return s
}
// buf := make([]byte, 0, len(start)+len(s)+len(end))
buf := []byte{}
if start != "" {
buf = append(buf, "\x1b["...)
buf = append(buf, start...)
buf = append(buf, 'm')
}
buf = append(buf, s...)
if end != "" {
buf = append(buf, "\x1b["...)
buf = append(buf, end...)
buf = append(buf, 'm')
}
return string(buf)
}