From 7805b8edf48a22c534bbda0b6d88abaad80670fc Mon Sep 17 00:00:00 2001 From: Florian Apolloner Date: Sat, 18 Sep 2021 02:37:05 +0200 Subject: [PATCH] Fixed usage of NOMAD_CLI_NO_COLOR env variable. (#11168) --- .changelog/11168.txt | 3 ++ command/meta.go | 5 +++- command/meta_test.go | 65 ++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 72 insertions(+), 1 deletion(-) create mode 100644 .changelog/11168.txt diff --git a/.changelog/11168.txt b/.changelog/11168.txt new file mode 100644 index 000000000..571f46698 --- /dev/null +++ b/.changelog/11168.txt @@ -0,0 +1,3 @@ +```release-note:bug +cli: Fixed a bug where the NOMAD_CLI_NO_COLOR environment variable was not always applied +``` diff --git a/command/meta.go b/command/meta.go index 0ea87313d..5f57adcb0 100644 --- a/command/meta.go +++ b/command/meta.go @@ -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, } } diff --git a/command/meta_test.go b/command/meta_test.go index c44a21be5..33f9bb59b 100644 --- a/command/meta_test.go +++ b/command/meta_test.go @@ -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) { @@ -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) + } + }) + } +}