From 2e3d1bd2e1fad797cf2f2fae20cc504998eb93f9 Mon Sep 17 00:00:00 2001 From: Jesse van den Kieboom Date: Wed, 14 Oct 2015 23:05:37 +0200 Subject: [PATCH] Lookup options in all parent commands --- command_private.go | 13 +++++--- command_test.go | 80 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 88 insertions(+), 5 deletions(-) diff --git a/command_private.go b/command_private.go index 3ae7247..c0d6ce3 100644 --- a/command_private.go +++ b/command_private.go @@ -156,18 +156,21 @@ func (c *Command) makeLookup() lookup { parent := c.parent + var parents []*Command + for parent != nil { if cmd, ok := parent.(*Command); ok { - cmd.fillLookup(&ret, true) - } - - if grp, ok := parent.(*Group); ok { - parent = grp + parents = append(parents, cmd) + parent = cmd.parent } else { parent = nil } } + for i := len(parents) - 1; i >= 0; i-- { + parents[i].fillLookup(&ret, true) + } + c.fillLookup(&ret, false) return ret } diff --git a/command_test.go b/command_test.go index 1d904ae..e64ac45 100644 --- a/command_test.go +++ b/command_test.go @@ -106,6 +106,34 @@ func TestCommandFlagOrder2(t *testing.T) { } } +func TestCommandFlagOrderSub(t *testing.T) { + var opts = struct { + Value bool `short:"v"` + + Command struct { + G bool `short:"g"` + + SubCommand struct { + B bool `short:"b"` + } `command:"sub"` + } `command:"cmd"` + }{} + + assertParseSuccess(t, &opts, "cmd", "sub", "-v", "-g", "-b") + + if !opts.Value { + t.Errorf("Expected Value to be true") + } + + if !opts.Command.G { + t.Errorf("Expected Command.G to be true") + } + + if !opts.Command.SubCommand.B { + t.Errorf("Expected Command.SubCommand.B to be true") + } +} + func TestCommandFlagOverride1(t *testing.T) { var opts = struct { Value bool `short:"v"` @@ -146,6 +174,58 @@ func TestCommandFlagOverride2(t *testing.T) { } } +func TestCommandFlagOverrideSub(t *testing.T) { + var opts = struct { + Value bool `short:"v"` + + Command struct { + Value bool `short:"v"` + + SubCommand struct { + Value bool `short:"v"` + } `command:"sub"` + } `command:"cmd"` + }{} + + assertParseSuccess(t, &opts, "cmd", "sub", "-v") + + if opts.Value { + t.Errorf("Expected Value to be false") + } + + if opts.Command.Value { + t.Errorf("Expected Command.Value to be false") + } + + if !opts.Command.SubCommand.Value { + t.Errorf("Expected Command.Value to be true") + } +} + +func TestCommandFlagOverrideSub2(t *testing.T) { + var opts = struct { + Value bool `short:"v"` + + Command struct { + Value bool `short:"v"` + + SubCommand struct { + G bool `short:"g"` + } `command:"sub"` + } `command:"cmd"` + }{} + + assertParseSuccess(t, &opts, "cmd", "sub", "-v") + + if opts.Value { + t.Errorf("Expected Value to be false") + } + + if !opts.Command.Value { + t.Errorf("Expected Command.Value to be true") + } +} + func TestCommandEstimate(t *testing.T) { var opts = struct { Value bool `short:"v"`