Create new buffer if not present yet (#549)

Fixes a nil dereference when TraverseChildren is used
with multiple subcommands.
This commit is contained in:
Thomas Cyron 2017-10-12 20:25:33 +02:00 committed by Albert Nigmatzianov
parent 7cd9cc6d44
commit 7b2c5ac9fc
2 changed files with 29 additions and 0 deletions

View File

@ -1360,6 +1360,9 @@ func (c *Command) ParseFlags(args []string) error {
return nil return nil
} }
if c.flagErrorBuf == nil {
c.flagErrorBuf = new(bytes.Buffer)
}
beforeErrorBufLen := c.flagErrorBuf.Len() beforeErrorBufLen := c.flagErrorBuf.Len()
c.mergePersistentFlags() c.mergePersistentFlags()
err := c.Flags().Parse(args) err := c.Flags().Parse(args)

View File

@ -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) { func TestRequiredFlags(t *testing.T) {
c := &Command{Use: "c", Run: func(*Command, []string) {}} c := &Command{Use: "c", Run: func(*Command, []string) {}}
output := new(bytes.Buffer) output := new(bytes.Buffer)