From 7aeaa2cce6ae7e18d2a6ee597b60ee137e999bd9 Mon Sep 17 00:00:00 2001 From: Tamir Duberstein Date: Sun, 2 Apr 2017 10:14:34 -0400 Subject: [PATCH] Avoid storing pointer to nil (#411) * Fix shellcheck Before this change: In - line 204: declare -F $next_command >/dev/null && $next_command ^-- SC2086: Double quote to prevent globbing and word splitting. --- FAIL: TestBashCompletions (0.34s) bash_completions_test.go:138: shellcheck failed: exit status 1 * Avoid storing pointer to nil Before this change, the new test fails with: --- FAIL: TestSetOutput (0.00s) command_test.go:198: expected setting output to nil to revert back to stdout, got --- bash_completions.go | 2 +- command.go | 6 +++--- command_test.go | 8 ++++++++ 3 files changed, 12 insertions(+), 4 deletions(-) diff --git a/bash_completions.go b/bash_completions.go index 8820ba8f..59e90f9d 100644 --- a/bash_completions.go +++ b/bash_completions.go @@ -225,7 +225,7 @@ __handle_command() fi c=$((c+1)) __debug "${FUNCNAME[0]}: looking for ${next_command}" - declare -F $next_command >/dev/null && $next_command + declare -F "$next_command" >/dev/null && $next_command } __handle_word() diff --git a/command.go b/command.go index 664bf5aa..a5b47d0f 100644 --- a/command.go +++ b/command.go @@ -113,7 +113,7 @@ type Command struct { flagErrorBuf *bytes.Buffer args []string // actual args parsed from flags - output *io.Writer // out writer if set in SetOutput(w) + output io.Writer // out writer if set in SetOutput(w) usageFunc func(*Command) error // Usage can be defined by application usageTemplate string // Can be defined by Application flagErrorFunc func(*Command, error) error @@ -141,7 +141,7 @@ func (c *Command) SetArgs(a []string) { // SetOutput sets the destination for usage and error messages. // If output is nil, os.Stderr is used. func (c *Command) SetOutput(output io.Writer) { - c.output = &output + c.output = output } // SetUsageFunc sets usage function. Usage can be defined by application. @@ -199,7 +199,7 @@ func (c *Command) OutOrStderr() io.Writer { func (c *Command) getOut(def io.Writer) io.Writer { if c.output != nil { - return *c.output + return c.output } if c.HasParent() { return c.parent.getOut(def) diff --git a/command_test.go b/command_test.go index 7947f6c4..8b78ee34 100644 --- a/command_test.go +++ b/command_test.go @@ -191,6 +191,14 @@ func TestEnableCommandSortingIsDisabled(t *testing.T) { EnableCommandSorting = true } +func TestSetOutput(t *testing.T) { + cmd := &Command{} + cmd.SetOutput(nil) + if out := cmd.OutOrStdout(); out != os.Stdout { + t.Fatalf("expected setting output to nil to revert back to stdout, got %v", out) + } +} + func TestFlagErrorFunc(t *testing.T) { cmd := &Command{