| 1 |
package check |
| 2 |
|
| 3 |
import ( |
| 4 |
"os" |
| 5 |
"strings" |
| 6 |
) |
| 7 |
|
| 8 |
//nolint:gochecknoglobals // By design. |
| 9 |
var ( |
| 10 |
ansiGreen = "\033[32m" |
| 11 |
ansiYellow = "\033[33m" |
| 12 |
ansiRed = "\033[31m" |
| 13 |
ansiReset = "\033[0m" |
| 14 |
) |
| 15 |
|
| 16 |
func init() { //nolint:gochecknoinits // By design. |
| 17 |
if !wantColor(os.Getenv, isTerminal()) { |
| 18 |
ansiGreen, ansiYellow, ansiRed, ansiReset = "", "", "", "" |
| 19 |
} |
| 20 |
} |
| 21 |
|
| 22 |
func isTerminal() bool { |
| 23 |
fi, err := os.Stderr.Stat() |
| 24 |
return err == nil && fi.Mode()&os.ModeCharDevice != 0 |
| 25 |
} |
| 26 |
|
| 27 |
// wantColor reports whether coloured output should be enabled. |
| 28 |
// |
| 29 |
// Precedence (first match wins): |
| 30 |
// 1. NO_COLOR set (any non-empty value) → no colour. |
| 31 |
// 2. CLICOLOR_FORCE set and not "0" → colour. |
| 32 |
// 3. FORCE_COLOR set and not "0" → colour. |
| 33 |
// 4. GO_TEST_COLOR set (any non-empty) → colour (legacy; superseded by FORCE_COLOR). |
| 34 |
// 5. isTTY and TERM != "dumb" and TERM != "" → colour. |
| 35 |
// 6. Otherwise → no colour. |
| 36 |
func wantColor(getenv func(string) string, isTTY bool) bool { |
| 37 |
switch { |
| 38 |
case getenv("NO_COLOR") != "": |
| 39 |
return false |
| 40 |
case getenv("CLICOLOR_FORCE") != "" && getenv("CLICOLOR_FORCE") != "0": |
| 41 |
return true |
| 42 |
case getenv("FORCE_COLOR") != "" && getenv("FORCE_COLOR") != "0": |
| 43 |
return true |
| 44 |
case getenv("GO_TEST_COLOR") != "": |
| 45 |
return true |
| 46 |
default: |
| 47 |
term := getenv("TERM") |
| 48 |
return isTTY && term != "dumb" && term != "" |
| 49 |
} |
| 50 |
} |
| 51 |
|
| 52 |
func colouredDiff(diff string) string { |
| 53 |
lines := strings.SplitAfter(diff, "\n") |
| 54 |
for i := range lines { |
| 55 |
switch { |
| 56 |
case strings.HasPrefix(lines[i], "--- "): |
| 57 |
case strings.HasPrefix(lines[i], "+++ "): |
| 58 |
case strings.HasPrefix(lines[i], "-"): |
| 59 |
lines[i] = ansiGreen + lines[i] + ansiReset |
| 60 |
case strings.HasPrefix(lines[i], "+"): |
| 61 |
lines[i] = ansiRed + lines[i] + ansiReset |
| 62 |
} |
| 63 |
} |
| 64 |
return strings.Join(lines, "") |
| 65 |
} |