Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed usage of NOMAD_CLI_NO_COLOR env variable. #11168

Merged
merged 2 commits into from
Sep 18, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
}
})
}
}