Skip to content

Commit

Permalink
Merge pull request #94 from andrii-zakurenyi/fix-blank-nested
Browse files Browse the repository at this point in the history
Exclude blank args from subcommand parsing
  • Loading branch information
mitchellh committed May 13, 2022
2 parents 628e665 + 100a9b5 commit 25f4c7c
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
5 changes: 3 additions & 2 deletions cli.go
Expand Up @@ -682,10 +682,11 @@ func (c *CLI) processArgs() {
// Determine the argument we look to to end subcommands.
// We look at all arguments until one is a flag or has a space.
// This disallows commands like: ./cli foo "bar baz". An
// argument with a space is always an argument.
// argument with a space is always an argument. A blank
// argument is always an argument.
j := 0
for k, v := range c.Args[i:] {
if strings.ContainsRune(v, ' ') || v[0] == '-' {
if strings.ContainsRune(v, ' ') || v == "" || v[0] == '-' {
break
}

Expand Down
32 changes: 32 additions & 0 deletions cli_test.go
Expand Up @@ -427,6 +427,38 @@ func TestCLIRun_nestedNoArgs(t *testing.T) {
}
}

func TestCLIRun_nestedBlankArg(t *testing.T) {
command := new(MockCommand)
cli := &CLI{
Args: []string{"foo", "", "bar", "-baz"},
Commands: map[string]CommandFactory{
"foo": func() (Command, error) {
return command, nil
},
"foo bar": func() (Command, error) {
return new(MockCommand), nil
},
},
}

exitCode, err := cli.Run()
if err != nil {
t.Fatalf("err: %s", err)
}

if exitCode != command.RunResult {
t.Fatalf("bad: %d", exitCode)
}

if !command.RunCalled {
t.Fatalf("run should be called")
}

if !reflect.DeepEqual(command.RunArgs, []string{"", "bar", "-baz"}) {
t.Fatalf("bad args: %#v", command.RunArgs)
}
}

func TestCLIRun_nestedQuotedCommand(t *testing.T) {
command := new(MockCommand)
cli := &CLI{
Expand Down

0 comments on commit 25f4c7c

Please sign in to comment.