Skip to content
This repository has been archived by the owner on Apr 19, 2024. It is now read-only.

Output plain template when NO_COLOR environment variable is set #475

Merged
merged 2 commits into from
Dec 8, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
15 changes: 14 additions & 1 deletion core/template.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package core

import (
"bytes"
"os"
"sync"
"text/template"

Expand All @@ -23,6 +24,17 @@ var TemplateFuncsNoColor = map[string]interface{}{
},
}

// envColorDisabled returns if output colors are forbid by environment variables
func envColorDisabled() bool {
return os.Getenv("NO_COLOR") != "" || os.Getenv("CLICOLOR") == "0"
}

// envColorForced returns if output colors are forced from environment variables
func envColorForced() bool {
val, ok := os.LookupEnv("CLICOLOR_FORCE")
return ok && val != "0"
Comment on lines +34 to +35
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Happy to change this to match the reference if that's preferred, but wanted to share a way to check if the environment variable is present then check for a != 0 value instead of checking that the variable isn't the empty value.

}

// RunTemplate returns two formatted strings given a template and
// the data it requires. The first string returned is generated for
// user-facing output and may or may not contain ANSI escape codes
Expand Down Expand Up @@ -74,7 +86,8 @@ func GetTemplatePair(tmpl string) ([2]*template.Template, error) {

templatePair[1] = templateNoColor

if DisableColor {
envColorHide := envColorDisabled() && !envColorForced()
if DisableColor || envColorHide {
templatePair[0] = templatePair[1]
} else {
templateWithColor, err := template.New("prompt").Funcs(TemplateFuncsWithColor).Parse(tmpl)
Expand Down