Skip to content

Commit cf4d040

Browse files
apollo13schmichael
authored andcommitted
Fixed usage of NOMAD_CLI_NO_COLOR env variable. (#11168)
1 parent e8d0cd6 commit cf4d040

File tree

3 files changed

+72
-1
lines changed

3 files changed

+72
-1
lines changed

.changelog/11168.txt

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

command/meta.go

+4-1
Original file line numberDiff line numberDiff line change
@@ -154,9 +154,12 @@ func (m *Meta) allNamespaces() bool {
154154
}
155155

156156
func (m *Meta) Colorize() *colorstring.Colorize {
157+
_, coloredUi := m.Ui.(*cli.ColoredUi)
158+
noColor := m.noColor || !coloredUi || !terminal.IsTerminal(int(os.Stdout.Fd()))
159+
157160
return &colorstring.Colorize{
158161
Colors: colorstring.DefaultColors,
159-
Disable: m.noColor || !terminal.IsTerminal(int(os.Stdout.Fd())),
162+
Disable: noColor,
160163
Reset: true,
161164
}
162165
}

command/meta_test.go

+65
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,14 @@ package command
22

33
import (
44
"flag"
5+
"os"
56
"reflect"
67
"sort"
78
"testing"
9+
10+
"github.com/kr/pty"
11+
"github.com/mitchellh/cli"
12+
"github.com/stretchr/testify/assert"
813
)
914

1015
func TestMeta_FlagSet(t *testing.T) {
@@ -53,3 +58,63 @@ func TestMeta_FlagSet(t *testing.T) {
5358
}
5459
}
5560
}
61+
62+
func TestMeta_Colorize(t *testing.T) {
63+
type testCaseSetupFn func(*testing.T, *Meta)
64+
65+
cases := []struct {
66+
Name string
67+
SetupFn testCaseSetupFn
68+
ExpectColor bool
69+
}{
70+
{
71+
Name: "disable colors if UI is not colored",
72+
ExpectColor: false,
73+
},
74+
{
75+
Name: "colors if UI is colored",
76+
SetupFn: func(t *testing.T, m *Meta) {
77+
m.Ui = &cli.ColoredUi{}
78+
},
79+
ExpectColor: true,
80+
},
81+
{
82+
Name: "disable colors via CLI flag",
83+
SetupFn: func(t *testing.T, m *Meta) {
84+
m.Ui = &cli.ColoredUi{}
85+
86+
fs := m.FlagSet("colorize_test", FlagSetDefault)
87+
err := fs.Parse([]string{"-no-color"})
88+
assert.NoError(t, err)
89+
},
90+
ExpectColor: false,
91+
},
92+
}
93+
94+
for _, tc := range cases {
95+
t.Run(tc.Name, func(t *testing.T) {
96+
// Create fake test terminal.
97+
_, tty, err := pty.Open()
98+
if err != nil {
99+
t.Fatalf("%v", err)
100+
}
101+
defer tty.Close()
102+
103+
oldStdout := os.Stdout
104+
defer func() { os.Stdout = oldStdout }()
105+
os.Stdout = tty
106+
107+
// Run test case.
108+
m := &Meta{}
109+
if tc.SetupFn != nil {
110+
tc.SetupFn(t, m)
111+
}
112+
113+
if tc.ExpectColor {
114+
assert.False(t, m.Colorize().Disable)
115+
} else {
116+
assert.True(t, m.Colorize().Disable)
117+
}
118+
})
119+
}
120+
}

0 commit comments

Comments
 (0)