diff --git a/text/color.go b/text/color.go index f42dfb3..4154111 100644 --- a/text/color.go +++ b/text/color.go @@ -2,13 +2,14 @@ package text import ( "fmt" + "os" "sort" "strconv" "strings" "sync" ) -var colorsEnabled = areANSICodesSupported() +var colorsEnabled = areColorsOnInTheEnv() && areANSICodesSupported() // DisableColors (forcefully) disables color coding globally. func DisableColors() { @@ -20,6 +21,15 @@ func EnableColors() { colorsEnabled = true } +// areColorsOnInTheEnv returns true is colors are not disable using +// well known environment variables. +func areColorsOnInTheEnv() bool { + if os.Getenv("FORCE_COLOR") == "1" { + return true + } + return os.Getenv("NO_COLOR") == "" || os.Getenv("NO_COLOR") == "0" +} + // The logic here is inspired from github.com/fatih/color; the following is // the bare minimum logic required to print Colored to the console. // The differences: diff --git a/text/color_test.go b/text/color_test.go index d31cac0..447169c 100644 --- a/text/color_test.go +++ b/text/color_test.go @@ -2,6 +2,7 @@ package text import ( "fmt" + "os" "testing" "github.com/stretchr/testify/assert" @@ -24,6 +25,24 @@ func TestColor_EnableAndDisable(t *testing.T) { assert.Equal(t, "\x1b[31mtest\x1b[0m", FgRed.Sprint("test")) } +func TestColor_areColorsOnInTheEnv(t *testing.T) { + _ = os.Setenv("FORCE_COLOR", "0") + _ = os.Setenv("NO_COLOR", "0") + assert.True(t, areColorsOnInTheEnv()) + + _ = os.Setenv("FORCE_COLOR", "0") + _ = os.Setenv("NO_COLOR", "1") + assert.False(t, areColorsOnInTheEnv()) + + _ = os.Setenv("FORCE_COLOR", "1") + _ = os.Setenv("NO_COLOR", "0") + assert.True(t, areColorsOnInTheEnv()) + + _ = os.Setenv("FORCE_COLOR", "1") + _ = os.Setenv("NO_COLOR", "1") + assert.True(t, areColorsOnInTheEnv()) +} + func ExampleColor_EscapeSeq() { fmt.Printf("Black Background: %#v\n", BgBlack.EscapeSeq()) fmt.Printf("Black Foreground: %#v\n", FgBlack.EscapeSeq())