From 100a9b57ffab5c10239c7b1fc7186ab9cedce427 Mon Sep 17 00:00:00 2001 From: Andrii Zakurenyi Date: Fri, 13 May 2022 19:15:12 +0300 Subject: [PATCH] exclude blank args from subcommand parsing --- cli.go | 5 +++-- cli_test.go | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/cli.go b/cli.go index 9b05ff6..9520532 100644 --- a/cli.go +++ b/cli.go @@ -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 } diff --git a/cli_test.go b/cli_test.go index 6b6014e..aa3b13d 100644 --- a/cli_test.go +++ b/cli_test.go @@ -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{