Skip to content

Commit

Permalink
Merge pull request #1864 from joshfrench/single-optional-arg
Browse files Browse the repository at this point in the history
Missing arg can cause a panic
  • Loading branch information
dearchap authored Feb 12, 2024
2 parents 00e6067 + d765601 commit e1d1334
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
6 changes: 5 additions & 1 deletion args.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,11 @@ func (a *ArgumentBase[T, C, VC]) Parse(s []string) ([]string, error) {
}

if a.Max == 1 && a.Destination != nil {
*a.Destination = values[0]
if len(values) > 0 {
*a.Destination = values[0]
} else {
*a.Destination = t
}
}
return s[count:], nil
}
Expand Down
23 changes: 23 additions & 0 deletions args_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -151,3 +151,26 @@ func TestArgsUsage(t *testing.T) {
})
}
}

func TestSingleOptionalArg(t *testing.T) {
cmd := buildMinimalTestCommand()
var s1 string
arg := &StringArg{
Min: 0,
Max: 1,
Destination: &s1,
}
cmd.Arguments = []Argument{
arg,
}

require.NoError(t, cmd.Run(context.Background(), []string{"foo"}))
require.Equal(t, "", s1)

arg.Value = "bar"
require.NoError(t, cmd.Run(context.Background(), []string{"foo"}))
require.Equal(t, "bar", s1)

require.NoError(t, cmd.Run(context.Background(), []string{"foo", "zbar"}))
require.Equal(t, "zbar", s1)
}

0 comments on commit e1d1334

Please sign in to comment.