Skip to content

Commit

Permalink
support NO_COLOR
Browse files Browse the repository at this point in the history
  • Loading branch information
BenTheElder committed Apr 17, 2020
1 parent 909e6f7 commit 2131b8c
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 4 deletions.
17 changes: 15 additions & 2 deletions pkg/internal/env/term.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,16 +45,29 @@ func IsTerminal(w io.Writer) bool {
// IsSmartTerminal returns true if the writer w is a terminal AND
// we think that the terminal is smart enough to use VT escape codes etc.
func IsSmartTerminal(w io.Writer) bool {
return isSmartTerminal(w, runtime.GOOS, os.Getenv)
return isSmartTerminal(w, runtime.GOOS, os.LookupEnv)
}

func isSmartTerminal(w io.Writer, GOOS string, getenv func(string) string) bool {
func isSmartTerminal(w io.Writer, GOOS string, lookupEnv func(string) (string, bool)) bool {
// Not smart if it's not a tty
if !IsTerminal(w) {
return false
}

// getenv helper for when we only care about the value
getenv := func(e string) string {
v, _ := lookupEnv(e)
return v
}

// Explicit request for no ANSI escape codes
// https://no-color.org/
if _, set := lookupEnv("NO_COLOR"); set {
return false
}

// Explicitly dumb terminals are not smart
// https://en.wikipedia.org/wiki/Computer_terminal#Dumb_terminals
if getenv("TERM") == "dumb" {
return false
}
Expand Down
14 changes: 12 additions & 2 deletions pkg/internal/env/term_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,15 @@ func TestIsSmartTerminal(t *testing.T) {
IsSmart: false,
Writer: &testFakeTTY{},
},
{
Name: "tty, NO_COLOR=",
FakeEnv: map[string]string{
"NO_COLOR": "",
},
GOOS: "linux",
IsSmart: false,
Writer: &testFakeTTY{},
},
{
Name: "tty, Travis CI",
FakeEnv: map[string]string{
Expand All @@ -112,8 +121,9 @@ func TestIsSmartTerminal(t *testing.T) {
for _, tc := range cases {
tc := tc // capture tc
t.Run(tc.Name, func(t *testing.T) {
res := isSmartTerminal(tc.Writer, tc.GOOS, func(s string) string {
return tc.FakeEnv[s]
res := isSmartTerminal(tc.Writer, tc.GOOS, func(s string) (string, bool) {
k, set := tc.FakeEnv[s]
return k, set
})
assert.BoolEqual(t, tc.IsSmart, res)
})
Expand Down

0 comments on commit 2131b8c

Please sign in to comment.