From 95a6a40798df11df014298af8a8250af515fa753 Mon Sep 17 00:00:00 2001 From: Eric Paris Date: Wed, 12 Aug 2015 10:54:26 -0400 Subject: Do not append to default values in {String,Int}Slice I added the ability to do: `-s=bob -s=john` and get `[]string{"bob", "john"}` But if a default value was set to say `[]string{"eric"}` the above operation was mistakenly resulting in: `[]string{"eric", "bob", "john"} which was obviously not what was intended. This is fixed by tracking if a value was parsed and overwriting the default on the first time -s is found, but we append the 2+ time. --- string_slice.go | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) (limited to 'string_slice.go') diff --git a/string_slice.go b/string_slice.go index 2037bd8..848bea8 100644 --- a/string_slice.go +++ b/string_slice.go @@ -1,27 +1,41 @@ package pflag import ( + "fmt" "strings" ) +var _ = fmt.Fprint + // -- stringSlice Value -type stringSliceValue []string +type stringSliceValue struct { + value *[]string + changed bool +} func newStringSliceValue(val []string, p *[]string) *stringSliceValue { - *p = val - return (*stringSliceValue)(p) + ssv := new(stringSliceValue) + ssv.value = p + *ssv.value = val + return ssv } func (s *stringSliceValue) Set(val string) error { v := strings.Split(val, ",") - *s = append(*s, v...) + if !s.changed { + *s.value = v + } else { + *s.value = append(*s.value, v...) + } + s.changed = true return nil } + func (s *stringSliceValue) Type() string { return "stringSlice" } -func (s *stringSliceValue) String() string { return "[" + strings.Join(*s, ",") + "]" } +func (s *stringSliceValue) String() string { return "[" + strings.Join(*s.value, ",") + "]" } func stringSliceConv(sval string) (interface{}, error) { sval = strings.Trim(sval, "[]") -- cgit v1.2.3