Skip to content

Commit

Permalink
Merge pull request #58 from ethanmoffat/master
Browse files Browse the repository at this point in the history
Fix bug with bool flags on subcommands
  • Loading branch information
integrii authored Jan 14, 2020
2 parents 3376827 + 51e8461 commit 6407017
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 1 deletion.
13 changes: 12 additions & 1 deletion flag.go
Original file line number Diff line number Diff line change
Expand Up @@ -407,10 +407,21 @@ func parseFlagToName(arg string) string {
return arg
}

// collectAllNestedFlags recurses through the command tree to get all
// flags specified on a subcommand and its descending subcommands
func collectAllNestedFlags(sc *Subcommand) []*Flag {
fullList := sc.Flags
for _, sc := range sc.Subcommands {
fullList = append(fullList, sc.Flags...)
fullList = append(fullList, collectAllNestedFlags(sc)...)
}
return fullList
}

// flagIsBool determines if the flag is a bool within the specified parser
// and subcommand's context
func flagIsBool(sc *Subcommand, p *Parser, key string) bool {
for _, f := range append(sc.Flags, p.Flags...) {
for _, f := range append(collectAllNestedFlags(sc), p.Flags...) {
if f.HasName(key) {
_, isBool := f.AssignmentVar.(*bool)
_, isBoolSlice := f.AssignmentVar.(*[]bool)
Expand Down
36 changes: 36 additions & 0 deletions subcommand_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -768,3 +768,39 @@ func TestSCInputParsing(t *testing.T) {
}
}
}

// TestSCBoolFlag tests bool flags on subcommands
func TestSCBoolFlag(t *testing.T) {
p := flaggy.NewParser("TestSubcommandBoolParse")
newSC := flaggy.NewSubcommand("testSubcommand")

var boolFlag bool
newSC.Bool(&boolFlag, "f", "flag", "test bool flag on subcommand")

p.AttachSubcommand(newSC, 1)

os.Args = []string{"binaryName", "testSubcommand", "--flag"}
err := p.Parse()
if err != nil {
t.Fatal("Error parsing args: " + err.Error())
}
}

// TestNestedSCBoolFlag tests bool flags on nested subcommands
func TestNestedSCBoolFlag(t *testing.T) {
p := flaggy.NewParser("TestSubcommandBoolParse")
newSC := flaggy.NewSubcommand("mainSubcommand")
subSC := flaggy.NewSubcommand("subSubCommand")

var boolFlag bool
subSC.Bool(&boolFlag, "f", "flag", "test bool flag on subcommand")

newSC.AttachSubcommand(subSC, 1)
p.AttachSubcommand(newSC, 1)

os.Args = []string{"binaryName", "mainSubcommand", "subSubCommand", "--flag"}
err := p.Parse()
if err != nil {
t.Fatal("Error parsing args: " + err.Error())
}
}

0 comments on commit 6407017

Please sign in to comment.