Browse Source

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.
Fredrik Wallgren 10 years ago
parent
commit
1488562b1e
No known key found for this signature in database GPG Key ID: F47F4EC105BDC53E
2 changed files with 18 additions and 0 deletions
  1. +5
    -0
      parse.go
  2. +13
    -0
      parse_test.go

+ 5
- 0
parse.go 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 {


+ 13
- 0
parse_test.go 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


Loading…
Cancel
Save