Skip to content

Commit 33bb83f

Browse files
committed
MINOR: improve color detection for CI and LOG_COLOR
Update the noColor function to better manage ANSI color output across various environments: - Allow explicitly disabling colors by setting LOG_COLOR to 0, false, or never. Previously, LOG_COLOR could only force colors on. - Automatically enable colors in GitLab CI and GitHub Actions. These platforms natively support ANSI colored logs, but default to no TTY, which previously stripped the colors.
1 parent bead010 commit 33bb83f

2 files changed

Lines changed: 21 additions & 5 deletions

File tree

logging.go

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,14 +27,20 @@ func newLogHandler(w io.Writer) slog.Handler {
2727
})
2828
}
2929

30-
// noColor: NO_COLOR always wins, LOG_COLOR forces on, else require a TTY.
30+
// noColor: NO_COLOR always wins, LOG_COLOR forces on or off,
31+
// GitLab/GitHub CI logs render ANSI, else require a TTY.
3132
func noColor() bool {
3233
if os.Getenv("NO_COLOR") != "" {
3334
return true
3435
}
3536
switch strings.ToLower(os.Getenv("LOG_COLOR")) {
3637
case "1", "true", "always":
3738
return false
39+
case "0", "false", "never":
40+
return true
41+
}
42+
if os.Getenv("GITLAB_CI") != "" || os.Getenv("GITHUB_ACTIONS") != "" {
43+
return false
3844
}
3945
return !term.IsTerminal(int(os.Stderr.Fd()))
4046
}

logging_test.go

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -46,17 +46,27 @@ func TestNoColorPrecedence(t *testing.T) {
4646
name string
4747
noColor string
4848
logColor string
49+
gitlab string
50+
github string
4951
want bool
5052
}{
51-
{"NO_COLOR wins over LOG_COLOR", "1", "always", true},
52-
{"LOG_COLOR forces color", "", "1", false},
53-
{"LOG_COLOR true forces color", "", "true", false},
54-
{"default without TTY", "", "", true}, // test stderr is not a terminal
53+
{"NO_COLOR wins over LOG_COLOR", "1", "always", "", "", true},
54+
{"NO_COLOR wins over CI", "1", "", "true", "true", true},
55+
{"LOG_COLOR forces color", "", "1", "", "", false},
56+
{"LOG_COLOR true forces color", "", "true", "", "", false},
57+
{"LOG_COLOR 0 forces off in CI", "", "0", "true", "", true},
58+
{"LOG_COLOR false forces off", "", "false", "", "true", true},
59+
{"LOG_COLOR never forces off", "", "never", "true", "", true},
60+
{"GitLab CI colors on", "", "", "true", "", false},
61+
{"GitHub Actions colors on", "", "", "", "true", false},
62+
{"default without TTY", "", "", "", "", true}, // test stderr is not a terminal
5563
}
5664
for _, tt := range tests {
5765
t.Run(tt.name, func(t *testing.T) {
5866
t.Setenv("NO_COLOR", tt.noColor)
5967
t.Setenv("LOG_COLOR", tt.logColor)
68+
t.Setenv("GITLAB_CI", tt.gitlab)
69+
t.Setenv("GITHUB_ACTIONS", tt.github)
6070
if got := noColor(); got != tt.want {
6171
t.Errorf("noColor() = %v, want %v", got, tt.want)
6272
}

0 commit comments

Comments
 (0)