From 7b2c5ac9fc04fc5efafb60700713d4fa609b777b Mon Sep 17 00:00:00 2001 From: Thomas Cyron Date: Thu, 12 Oct 2017 20:25:33 +0200 Subject: [PATCH] Create new buffer if not present yet (#549) Fixes a nil dereference when TraverseChildren is used with multiple subcommands. --- command.go | 3 +++ command_test.go | 26 ++++++++++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/command.go b/command.go index 4d4b391..58e6ceb 100644 --- a/command.go +++ b/command.go @@ -1360,6 +1360,9 @@ func (c *Command) ParseFlags(args []string) error { return nil } + if c.flagErrorBuf == nil { + c.flagErrorBuf = new(bytes.Buffer) + } beforeErrorBufLen := c.flagErrorBuf.Len() c.mergePersistentFlags() err := c.Flags().Parse(args) diff --git a/command_test.go b/command_test.go index 4f798da..dda355f 100644 --- a/command_test.go +++ b/command_test.go @@ -439,6 +439,32 @@ func TestTraverseWithBadChildFlag(t *testing.T) { } } +func TestTraverseWithTwoSubcommands(t *testing.T) { + cmd := &Command{ + Use: "do", + TraverseChildren: true, + } + + sub := &Command{ + Use: "sub", + TraverseChildren: true, + } + cmd.AddCommand(sub) + + subsub := &Command{ + Use: "subsub", + } + sub.AddCommand(subsub) + + c, _, err := cmd.Traverse([]string{"sub", "subsub"}) + if err != nil { + t.Fatalf("Expected no error: %s", err) + } + if c.Name() != subsub.Name() { + t.Fatalf("wrong command %q expected %q", c.Name(), subsub.Name()) + } +} + func TestRequiredFlags(t *testing.T) { c := &Command{Use: "c", Run: func(*Command, []string) {}} output := new(bytes.Buffer)