Skip to content

Commit

Permalink
Fixed usage of NOMAD_CLI_NO_COLOR env variable. (#11168)
Browse files Browse the repository at this point in the history
  • Loading branch information
apollo13 authored and schmichael committed Sep 20, 2021
1 parent 2a2317c commit 3d24464
Show file tree
Hide file tree
Showing 3 changed files with 72 additions and 1 deletion.
3 changes: 3 additions & 0 deletions .changelog/11168.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
```release-note:bug
cli: Fixed a bug where the NOMAD_CLI_NO_COLOR environment variable was not always applied
```
5 changes: 4 additions & 1 deletion command/meta.go
Original file line number Diff line number Diff line change
Expand Up @@ -154,9 +154,12 @@ func (m *Meta) allNamespaces() bool {
}

func (m *Meta) Colorize() *colorstring.Colorize {
_, coloredUi := m.Ui.(*cli.ColoredUi)
noColor := m.noColor || !coloredUi || !terminal.IsTerminal(int(os.Stdout.Fd()))

return &colorstring.Colorize{
Colors: colorstring.DefaultColors,
Disable: m.noColor || !terminal.IsTerminal(int(os.Stdout.Fd())),
Disable: noColor,
Reset: true,
}
}
Expand Down
65 changes: 65 additions & 0 deletions command/meta_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,14 @@ package command

import (
"flag"
"os"
"reflect"
"sort"
"testing"

"github.com/kr/pty"
"github.com/mitchellh/cli"
"github.com/stretchr/testify/assert"
)

func TestMeta_FlagSet(t *testing.T) {
Expand Down Expand Up @@ -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)
}
})
}
}

0 comments on commit 3d24464

Please sign in to comment.