From fa37277e6394c29db7bcc94062cb30cd7785a126 Mon Sep 17 00:00:00 2001 From: Ethan Zimbelman Date: Thu, 8 Dec 2022 07:41:06 -0800 Subject: [PATCH] Respect NO_COLOR, CLICOLOR, and CLICOLOR_FORCE environment (#475) --- core/template.go | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/core/template.go b/core/template.go index 77f25850..02da879d 100644 --- a/core/template.go +++ b/core/template.go @@ -2,6 +2,7 @@ package core import ( "bytes" + "os" "sync" "text/template" @@ -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" +} + // 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 @@ -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)