Skip to content

Commit

Permalink
text: support NO_COLOR/FORCE_COLOR env directives; fixes #352 (#360)
Browse files Browse the repository at this point in the history
  • Loading branch information
jedib0t authored Mar 1, 2025
1 parent be73dfa commit 5a8fa5f
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
12 changes: 11 additions & 1 deletion text/color.go
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand All @@ -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:
Expand Down
19 changes: 19 additions & 0 deletions text/color_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package text

import (
"fmt"
"os"
"testing"

"github.com/stretchr/testify/assert"
Expand All @@ -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())
Expand Down

0 comments on commit 5a8fa5f

Please # to comment.