Skip to content

Commit

Permalink
Boundary check for optional arg
Browse files Browse the repository at this point in the history
  • Loading branch information
joshfrench committed Feb 11, 2024
1 parent 00e6067 commit f7deded
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
2 changes: 1 addition & 1 deletion args.go
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ func (a *ArgumentBase[T, C, VC]) Parse(s []string) ([]string, error) {
*a.Values = values
}

if a.Max == 1 && a.Destination != nil {
if a.Max == 1 && a.Destination != nil && len(values) > 0 {
*a.Destination = values[0]
}
return s[count:], nil
Expand Down
20 changes: 20 additions & 0 deletions args_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -151,3 +151,23 @@ 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", "bar"}))
require.Equal(t, "bar", s1)
}

0 comments on commit f7deded

Please sign in to comment.