Skip to content

Commit

Permalink
Support $NO_COLOR and $FORCE_COLOR (#48)
Browse files Browse the repository at this point in the history
  • Loading branch information
FollowTheProcess authored Jan 5, 2025
1 parent 7f41984 commit 0231350
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions internal/colour/colour.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
// Package colour implements basic text colouring for showing text diffs.
package colour

import (
"os"
"sync"
)

// ANSI codes for coloured output, they are all the same length so as not to throw off
// alignment of [text/tabwriter].
const (
Expand All @@ -10,6 +15,19 @@ const (
codeReset = "\x1b[000000m" // Reset all attributes
)

// getColourOnce is a [sync.OnceValues] function that returns the state of
// $NO_COLOR and $FORCE_COLOR, once and only once to avoid us calling
// os.Getenv on every call to a colour function.
var getColourOnce = sync.OnceValues(getColour)

// getColour returns whether $NO_COLOR and $FORCE_COLOR were set.
func getColour() (noColour bool, forceColour bool) {
no := os.Getenv("NO_COLOR") != ""
force := os.Getenv("FORCE_COLOR") != ""

return no, force
}

// Header returns a diff header styled string.
func Header(text string) string {
return sprint(codeHeader, text)
Expand All @@ -29,5 +47,16 @@ func Red(text string) string {
//
// It handles checking for NO_COLOR and FORCE_COLOR.
func sprint(code, text string) string {
noColor, forceColor := getColourOnce()

// $FORCE_COLOR overrides $NO_COLOR
if forceColor {
return code + text + codeReset
}

// $NO_COLOR is next
if noColor {
return text
}
return code + text + codeReset
}

0 comments on commit 0231350

Please sign in to comment.