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:
parent
aaae1550b7
commit
1488562b1e
5
parse.go
5
parse.go
|
@ -322,6 +322,11 @@ func setSlice(dest reflect.Value, values []string) error {
|
||||||
elem = elem.Elem()
|
elem = elem.Elem()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Truncate the dest slice in case default values exist
|
||||||
|
if !dest.IsNil() {
|
||||||
|
dest.SetLen(0)
|
||||||
|
}
|
||||||
|
|
||||||
for _, s := range values {
|
for _, s := range values {
|
||||||
v := reflect.New(elem)
|
v := reflect.New(elem)
|
||||||
if err := setScalar(v.Elem(), s); err != nil {
|
if err := setScalar(v.Elem(), s); err != nil {
|
||||||
|
|
|
@ -250,6 +250,19 @@ func TestMultipleWithEq(t *testing.T) {
|
||||||
assert.Equal(t, []string{"x"}, args.Bar)
|
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) {
|
func TestExemptField(t *testing.T) {
|
||||||
var args struct {
|
var args struct {
|
||||||
Foo string
|
Foo string
|
||||||
|
|
Loading…
Reference in New Issue