Skip to content

Commit

Permalink
Merge pull request #712 from windler/fix_args_reorder
Browse files Browse the repository at this point in the history
Fix args reordering when bool flags are present
  • Loading branch information
jszwedko committed Feb 11, 2018
2 parents 803d066 + 3a87b13 commit a1c7408
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
33 changes: 33 additions & 0 deletions app_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -329,6 +329,39 @@ func TestApp_CommandWithArgBeforeFlags(t *testing.T) {
expect(t, firstArg, "my-arg")
}

func TestApp_CommandWithArgBeforeBoolFlags(t *testing.T) {
var parsedOption, parsedSecondOption, firstArg string
var parsedBool, parsedSecondBool bool

app := NewApp()
command := Command{
Name: "cmd",
Flags: []Flag{
StringFlag{Name: "option", Value: "", Usage: "some option"},
StringFlag{Name: "secondOption", Value: "", Usage: "another option"},
BoolFlag{Name: "boolflag", Usage: "some bool"},
BoolFlag{Name: "b", Usage: "another bool"},
},
Action: func(c *Context) error {
parsedOption = c.String("option")
parsedSecondOption = c.String("secondOption")
parsedBool = c.Bool("boolflag")
parsedSecondBool = c.Bool("b")
firstArg = c.Args().First()
return nil
},
}
app.Commands = []Command{command}

app.Run([]string{"", "cmd", "my-arg", "--boolflag", "--option", "my-option", "-b", "--secondOption", "fancy-option"})

expect(t, parsedOption, "my-option")
expect(t, parsedSecondOption, "fancy-option")
expect(t, parsedBool, true)
expect(t, parsedSecondBool, true)
expect(t, firstArg, "my-arg")
}

func TestApp_RunAsSubcommandParseFlags(t *testing.T) {
var context *Context

Expand Down
3 changes: 2 additions & 1 deletion command.go
Original file line number Diff line number Diff line change
Expand Up @@ -213,11 +213,12 @@ func reorderArgs(args []string) []string {
break
}

if readFlagValue {
if readFlagValue && !strings.HasPrefix(arg, "-") && !strings.HasPrefix(arg, "--") {
readFlagValue = false
flags = append(flags, arg)
continue
}
readFlagValue = false

if arg != "-" && strings.HasPrefix(arg, "-") {
flags = append(flags, arg)
Expand Down

0 comments on commit a1c7408

Please sign in to comment.