Skip to content

text: support NO_COLOR/FORCE_COLOR env directives; fixes #352 #360

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 1, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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