-
-
Notifications
You must be signed in to change notification settings - Fork 72
/
Copy pathtermenv.go
92 lines (76 loc) · 2.22 KB
/
termenv.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
package termenv
import (
"errors"
"os"
"github.com/mattn/go-isatty"
)
var (
ErrStatusReport = errors.New("unable to retrieve status report")
)
type Profile int
const (
CSI = "\x1b["
Ascii = Profile(iota)
ANSI
ANSI256
TrueColor
)
// ColorProfile returns the supported color profile:
// Ascii, ANSI, ANSI256, or TrueColor.
func ColorProfile() Profile {
if !isatty.IsTerminal(os.Stdout.Fd()) {
return Ascii
}
return colorProfile()
}
// ForegroundColor returns the terminal's default foreground color.
func ForegroundColor() Color {
if !isatty.IsTerminal(os.Stdout.Fd()) {
return NoColor{}
}
return foregroundColor()
}
// BackgroundColor returns the terminal's default background color.
func BackgroundColor() Color {
if !isatty.IsTerminal(os.Stdout.Fd()) {
return NoColor{}
}
return backgroundColor()
}
// HasDarkBackground returns whether terminal uses a dark-ish background.
func HasDarkBackground() bool {
c := ConvertToRGB(BackgroundColor())
_, _, l := c.Hsl()
return l < 0.5
}
// EnvNoColor returns true if the environment variables explicitly disable color output
// by setting NO_COLOR (https://no-color.org/)
// or CLICOLOR/CLICOLOR_FORCE (https://bixense.com/clicolors/)
// If NO_COLOR is set, this will return true, ignoring CLICOLOR/CLICOLOR_FORCE
// If CLICOLOR=="0", it will be true only if CLICOLOR_FORCE is also "0" or is unset.
func EnvNoColor() bool {
return os.Getenv("NO_COLOR") != "" || (os.Getenv("CLICOLOR") == "0" && !cliColorForced())
}
// EnvColorProfile returns the color profile based on environment variables set
// Supports NO_COLOR (https://no-color.org/)
// and CLICOLOR/CLICOLOR_FORCE (https://bixense.com/clicolors/)
// If none of these environment variables are set, this behaves the same as ColorProfile()
// It will return the Ascii color profile if EnvNoColor() returns true
// If the terminal does not support any colors, but CLICOLOR_FORCE is set and not "0"
// then the ANSI color profile will be returned.
func EnvColorProfile() Profile {
if EnvNoColor() {
return Ascii
}
p := ColorProfile()
if cliColorForced() && p == Ascii {
return ANSI
}
return p
}
func cliColorForced() bool {
if forced := os.Getenv("CLICOLOR_FORCE"); forced != "" {
return forced != "0"
}
return false
}