Allow override of defaults for slice arguments

This commit fixes a bug where if a multiple value argument (slice) has default
values, the submitted values will be appended to the default. Not
overriding them as expected.
This commit is contained in:
Fredrik Wallgren 2016-02-29 22:05:26 +01:00
parent aaae1550b7
commit 1488562b1e
No known key found for this signature in database
GPG Key ID: F47F4EC105BDC53E
2 changed files with 18 additions and 0 deletions

View File

@ -322,6 +322,11 @@ func setSlice(dest reflect.Value, values []string) error {
elem = elem.Elem()
}
// Truncate the dest slice in case default values exist
if !dest.IsNil() {
dest.SetLen(0)
}
for _, s := range values {
v := reflect.New(elem)
if err := setScalar(v.Elem(), s); err != nil {

View File

@ -250,6 +250,19 @@ func TestMultipleWithEq(t *testing.T) {
assert.Equal(t, []string{"x"}, args.Bar)
}
func TestMultipleWithDefault(t *testing.T) {
var args struct {
Foo []int
Bar []string
}
args.Foo = []int{42}
args.Bar = []string{"foo"}
err := parse("--foo 1 2 3 --bar x y z", &args)
require.NoError(t, err)
assert.Equal(t, []int{1, 2, 3}, args.Foo)
assert.Equal(t, []string{"x", "y", "z"}, args.Bar)
}
func TestExemptField(t *testing.T) {
var args struct {
Foo string