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/
This commit is contained in:
Mislav Marohnić 2020-09-04 21:32:58 +02:00
parent abf83c02c0
commit ca2f2b18ca
3 changed files with 15 additions and 3 deletions

View file

@ -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.
`),
},
}

View file

@ -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

View file

@ -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
}