Fixed usage of NOMAD_CLI_NO_COLOR env variable. (#11168)

This commit is contained in:
Florian Apolloner 2021-09-18 02:37:05 +02:00 committed by GitHub
parent 571b0c1469
commit 7805b8edf4
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 72 additions and 1 deletions

3
.changelog/11168.txt Normal file
View file

@ -0,0 +1,3 @@
```release-note:bug
cli: Fixed a bug where the NOMAD_CLI_NO_COLOR environment variable was not always applied
```

View file

@ -154,9 +154,12 @@ func (m *Meta) allNamespaces() bool {
} }
func (m *Meta) Colorize() *colorstring.Colorize { func (m *Meta) Colorize() *colorstring.Colorize {
_, coloredUi := m.Ui.(*cli.ColoredUi)
noColor := m.noColor || !coloredUi || !terminal.IsTerminal(int(os.Stdout.Fd()))
return &colorstring.Colorize{ return &colorstring.Colorize{
Colors: colorstring.DefaultColors, Colors: colorstring.DefaultColors,
Disable: m.noColor || !terminal.IsTerminal(int(os.Stdout.Fd())), Disable: noColor,
Reset: true, Reset: true,
} }
} }

View file

@ -2,9 +2,14 @@ package command
import ( import (
"flag" "flag"
"os"
"reflect" "reflect"
"sort" "sort"
"testing" "testing"
"github.com/kr/pty"
"github.com/mitchellh/cli"
"github.com/stretchr/testify/assert"
) )
func TestMeta_FlagSet(t *testing.T) { func TestMeta_FlagSet(t *testing.T) {
@ -53,3 +58,63 @@ func TestMeta_FlagSet(t *testing.T) {
} }
} }
} }
func TestMeta_Colorize(t *testing.T) {
type testCaseSetupFn func(*testing.T, *Meta)
cases := []struct {
Name string
SetupFn testCaseSetupFn
ExpectColor bool
}{
{
Name: "disable colors if UI is not colored",
ExpectColor: false,
},
{
Name: "colors if UI is colored",
SetupFn: func(t *testing.T, m *Meta) {
m.Ui = &cli.ColoredUi{}
},
ExpectColor: true,
},
{
Name: "disable colors via CLI flag",
SetupFn: func(t *testing.T, m *Meta) {
m.Ui = &cli.ColoredUi{}
fs := m.FlagSet("colorize_test", FlagSetDefault)
err := fs.Parse([]string{"-no-color"})
assert.NoError(t, err)
},
ExpectColor: false,
},
}
for _, tc := range cases {
t.Run(tc.Name, func(t *testing.T) {
// Create fake test terminal.
_, tty, err := pty.Open()
if err != nil {
t.Fatalf("%v", err)
}
defer tty.Close()
oldStdout := os.Stdout
defer func() { os.Stdout = oldStdout }()
os.Stdout = tty
// Run test case.
m := &Meta{}
if tc.SetupFn != nil {
tc.SetupFn(t, m)
}
if tc.ExpectColor {
assert.False(t, m.Colorize().Disable)
} else {
assert.True(t, m.Colorize().Disable)
}
})
}
}