From ca2f2b18ca507db40c2b7a72f371be8e4fc98b32 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Fri, 4 Sep 2020 21:32:58 +0200 Subject: [PATCH] Add support for CLICOLOR "standard" The CLICOLOR_FORCE environment variable can now be used to force color output even when stdout is redirected. https://bixense.com/clicolors/ --- pkg/cmd/root/root.go | 7 ++++++- pkg/iostreams/iostreams.go | 5 ++++- utils/color.go | 6 +++++- 3 files changed, 15 insertions(+), 3 deletions(-) diff --git a/pkg/cmd/root/root.go b/pkg/cmd/root/root.go index 252636e52..fe2d23d8c 100644 --- a/pkg/cmd/root/root.go +++ b/pkg/cmd/root/root.go @@ -61,7 +61,12 @@ func NewCmdRoot(f *cmdutil.Factory, version, buildDate string) *cobra.Command { GLAMOUR_STYLE: the style to use for rendering Markdown. See https://github.com/charmbracelet/glamour#styles - NO_COLOR: avoid printing ANSI escape sequences for color output. + NO_COLOR: set to any value to avoid printing ANSI escape sequences for color output. + + CLICOLOR: set to "0" to disable printing ANSI colors in output. + + CLICOLOR_FORCE: set to a value other than "0" to keep ANSI colors in output + even when the output is piped. `), }, } diff --git a/pkg/iostreams/iostreams.go b/pkg/iostreams/iostreams.go index e9b9c2220..bbaaecda4 100644 --- a/pkg/iostreams/iostreams.go +++ b/pkg/iostreams/iostreams.go @@ -106,11 +106,14 @@ func System() *IOStreams { stdoutIsTTY := isTerminal(os.Stdout) stderrIsTTY := isTerminal(os.Stderr) + envNoColor := os.Getenv("NO_COLOR") != "" || os.Getenv("CLICOLOR") == "0" + envForceColor := os.Getenv("CLICOLOR_FORCE") != "" && os.Getenv("CLICOLOR_FORCE") != "0" + io := &IOStreams{ In: os.Stdin, Out: colorable.NewColorable(os.Stdout), ErrOut: colorable.NewColorable(os.Stderr), - colorEnabled: os.Getenv("NO_COLOR") == "" && stdoutIsTTY, + colorEnabled: envForceColor || (!envNoColor && stdoutIsTTY), } // prevent duplicate isTerminal queries now that we know the answer diff --git a/utils/color.go b/utils/color.go index 123e0927c..034dd54d7 100644 --- a/utils/color.go +++ b/utils/color.go @@ -39,7 +39,11 @@ func makeColorFunc(color string) func(string) string { } func isColorEnabled() bool { - if os.Getenv("NO_COLOR") != "" { + if os.Getenv("CLICOLOR_FORCE") != "" && os.Getenv("CLICOLOR_FORCE") != "0" { + return true + } + + if os.Getenv("NO_COLOR") != "" || os.Getenv("CLICOLOR") == "0" { return false }