Skip to content

Commit

Permalink
Merge pull request #1865 from joshfrench/variadic-args
Browse files Browse the repository at this point in the history
Fix variadic args
  • Loading branch information
dearchap authored Feb 15, 2024
2 parents 204d34f + 46839fa commit 5336fa4
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 2 deletions.
5 changes: 3 additions & 2 deletions args.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ func (a *ArgumentBase[T, C, VC]) Parse(s []string) ([]string, error) {
}
values = append(values, value.Get().(T))
count++
if count >= a.Max {
if count >= a.Max && a.Max > -1 {
break
}
}
Expand All @@ -128,7 +128,7 @@ func (a *ArgumentBase[T, C, VC]) Parse(s []string) ([]string, error) {

if a.Values == nil {
a.Values = &values
} else {
} else if count > 0 {
*a.Values = values
}

Expand All @@ -139,6 +139,7 @@ func (a *ArgumentBase[T, C, VC]) Parse(s []string) ([]string, error) {
*a.Destination = t
}
}

return s[count:], nil
}

Expand Down
46 changes: 46 additions & 0 deletions args_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -174,3 +174,49 @@ func TestSingleOptionalArg(t *testing.T) {
require.NoError(t, cmd.Run(context.Background(), []string{"foo", "zbar"}))
require.Equal(t, "zbar", s1)
}

func TestUnboundedArgs(t *testing.T) {
arg := &StringArg{
Min: 0,
Max: -1,
}
tests := []struct {
name string
args []string
values []string
expected []string
}{
{
name: "cmd accepts no args",
args: []string{"foo"},
expected: nil,
},
{
name: "cmd uses given args",
args: []string{"foo", "bar", "baz"},
expected: []string{"bar", "baz"},
},
{
name: "cmd uses default values",
args: []string{"foo"},
values: []string{"zbar", "zbaz"},
expected: []string{"zbar", "zbaz"},
},
{
name: "given args override default values",
args: []string{"foo", "bar", "baz"},
values: []string{"zbar", "zbaz"},
expected: []string{"bar", "baz"},
},
}

cmd := buildMinimalTestCommand()
cmd.Arguments = []Argument{arg}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
arg.Values = &test.values
require.NoError(t, cmd.Run(context.Background(), test.args))
require.Equal(t, test.expected, *arg.Values)
})
}
}

0 comments on commit 5336fa4

Please sign in to comment.