Skip to content

Commit

Permalink
Merge pull request #93 from kmoe/kmoe/subcommand-suffix-parsing
Browse files Browse the repository at this point in the history
Fix bug in which "fooasdf -o=foo" is incorrectly identified as the subcommand "foo"
  • Loading branch information
mitchellh committed Apr 21, 2022
2 parents 5454ffe + 4bb9ba2 commit 249ea46
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 4 deletions.
8 changes: 4 additions & 4 deletions cli.go
Expand Up @@ -680,12 +680,12 @@ func (c *CLI) processArgs() {
}

// Determine the argument we look to to end subcommands.
// We look at all arguments until one has a space. This
// disallows commands like: ./cli foo "bar baz". An argument
// with a space is always an argument.
// 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.
j := 0
for k, v := range c.Args[i:] {
if strings.ContainsRune(v, ' ') {
if strings.ContainsRune(v, ' ') || v[0] == '-' {
break
}

Expand Down
31 changes: 31 additions & 0 deletions cli_test.go
Expand Up @@ -171,6 +171,37 @@ func TestCLIRun_prefix(t *testing.T) {
}
}

func TestCLIRun_subcommandSuffix(t *testing.T) {
buf := new(bytes.Buffer)
command := new(MockCommand)
cli := &CLI{
Args: []string{"fooasdf", "-o=foo"},
Commands: map[string]CommandFactory{
"foo": func() (Command, error) {
return command, nil
},

"foo bar": func() (Command, error) {
return command, nil
},
},
ErrorWriter: buf,
}

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

if exitCode != 127 {
t.Fatalf("expected to get exit code 127, but got %d", exitCode)
}

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

func TestCLIRun_default(t *testing.T) {
commandBar := new(MockCommand)
commandBar.RunResult = 42
Expand Down

0 comments on commit 249ea46

Please sign in to comment.