Skip to content

Commit e201e9c

Browse files
committed
text: support NO_COLOR/FORCE_COLOR env directives
1 parent be73dfa commit e201e9c

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

text/color.go

+11-1
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,14 @@ package text
22

33
import (
44
"fmt"
5+
"os"
56
"sort"
67
"strconv"
78
"strings"
89
"sync"
910
)
1011

11-
var colorsEnabled = areANSICodesSupported()
12+
var colorsEnabled = areColorsOnInTheEnv() && areANSICodesSupported()
1213

1314
// DisableColors (forcefully) disables color coding globally.
1415
func DisableColors() {
@@ -20,6 +21,15 @@ func EnableColors() {
2021
colorsEnabled = true
2122
}
2223

24+
// areColorsOnInTheEnv returns true is colors are not disable using
25+
// well known environment variables.
26+
func areColorsOnInTheEnv() bool {
27+
if os.Getenv("FORCE_COLOR") == "1" {
28+
return true
29+
}
30+
return os.Getenv("NO_COLOR") == "" || os.Getenv("NO_COLOR") == "0"
31+
}
32+
2333
// The logic here is inspired from github.com/fatih/color; the following is
2434
// the bare minimum logic required to print Colored to the console.
2535
// The differences:

text/color_test.go

+19
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package text
22

33
import (
44
"fmt"
5+
"os"
56
"testing"
67

78
"github.com/stretchr/testify/assert"
@@ -24,6 +25,24 @@ func TestColor_EnableAndDisable(t *testing.T) {
2425
assert.Equal(t, "\x1b[31mtest\x1b[0m", FgRed.Sprint("test"))
2526
}
2627

28+
func TestColor_areColorsOnInTheEnv(t *testing.T) {
29+
_ = os.Setenv("FORCE_COLOR", "0")
30+
_ = os.Setenv("NO_COLOR", "0")
31+
assert.True(t, areColorsOnInTheEnv())
32+
33+
_ = os.Setenv("FORCE_COLOR", "0")
34+
_ = os.Setenv("NO_COLOR", "1")
35+
assert.False(t, areColorsOnInTheEnv())
36+
37+
_ = os.Setenv("FORCE_COLOR", "1")
38+
_ = os.Setenv("NO_COLOR", "0")
39+
assert.True(t, areColorsOnInTheEnv())
40+
41+
_ = os.Setenv("FORCE_COLOR", "1")
42+
_ = os.Setenv("NO_COLOR", "1")
43+
assert.True(t, areColorsOnInTheEnv())
44+
}
45+
2746
func ExampleColor_EscapeSeq() {
2847
fmt.Printf("Black Background: %#v\n", BgBlack.EscapeSeq())
2948
fmt.Printf("Black Foreground: %#v\n", FgBlack.EscapeSeq())

0 commit comments

Comments
 (0)