|
2 | 2 | package colour |
3 | 3 |
|
4 | 4 | import ( |
5 | | - "os" |
6 | | - "sync" |
| 5 | + "github.com/fatih/color" |
7 | 6 | ) |
8 | 7 |
|
9 | | -// ANSI codes for coloured output, they are all the same length so as not to throw off |
10 | | -// alignment of [text/tabwriter]. |
11 | | -const ( |
12 | | - codeRed = "\x1b[0;0031m" // Red, used for diff lines starting with '-' |
13 | | - codeHeader = "\x1b[1;0036m" // Bold cyan, used for diff headers starting with '@@' |
14 | | - codeGreen = "\x1b[0;0032m" // Green, used for diff lines starting with '+' |
15 | | - codeReset = "\x1b[000000m" // Reset all attributes |
| 8 | +var ( |
| 9 | + red = color.New(color.FgRed) |
| 10 | + header = color.New(color.FgCyan, color.Bold) |
| 11 | + green = color.New(color.FgGreen) |
16 | 12 | ) |
17 | 13 |
|
18 | | -// getColourOnce is a [sync.OnceValues] function that returns the state of |
19 | | -// $NO_COLOR and $FORCE_COLOR, once and only once to avoid us calling |
20 | | -// os.Getenv on every call to a colour function. |
21 | | -var getColourOnce = sync.OnceValues(getColour) |
22 | | - |
23 | | -// getColour returns whether $NO_COLOR and $FORCE_COLOR were set. |
24 | | -func getColour() (noColour, forceColour bool) { |
25 | | - no := os.Getenv("NO_COLOR") != "" |
26 | | - force := os.Getenv("FORCE_COLOR") != "" |
27 | | - |
28 | | - return no, force |
29 | | -} |
30 | | - |
31 | 14 | // Header returns a diff header styled string. |
32 | 15 | func Header(text string) string { |
33 | | - return sprint(codeHeader, text) |
| 16 | + return header.Sprint(text) |
34 | 17 | } |
35 | 18 |
|
36 | 19 | // Green returns a green styled string. |
37 | 20 | func Green(text string) string { |
38 | | - return sprint(codeGreen, text) |
| 21 | + return green.Sprint(text) |
39 | 22 | } |
40 | 23 |
|
41 | 24 | // Red returns a red styled string. |
42 | 25 | func Red(text string) string { |
43 | | - return sprint(codeRed, text) |
44 | | -} |
45 | | - |
46 | | -// sprint returns a string with a given colour and the reset code. |
47 | | -// |
48 | | -// It handles checking for NO_COLOR and FORCE_COLOR. |
49 | | -func sprint(code, text string) string { |
50 | | - noColor, forceColor := getColourOnce() |
51 | | - |
52 | | - // $FORCE_COLOR overrides $NO_COLOR |
53 | | - if forceColor { |
54 | | - return code + text + codeReset |
55 | | - } |
56 | | - |
57 | | - // $NO_COLOR is next |
58 | | - if noColor { |
59 | | - return text |
60 | | - } |
61 | | - return code + text + codeReset |
| 26 | + return red.Sprint(text) |
62 | 27 | } |
0 commit comments