Skip to content

Commit

Permalink
Merge(): do not change default values on merging
Browse files Browse the repository at this point in the history
  • Loading branch information
gobwas committed Sep 30, 2020
1 parent ed5a7ec commit 35e0775
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 8 deletions.
15 changes: 10 additions & 5 deletions flagutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -252,7 +252,7 @@ repeat:
reflect.Map:
return `{}`
}
return "?"
return ""
}

// defValueStd returns default value as it does std lib.
Expand Down Expand Up @@ -430,8 +430,10 @@ var MergeUsage = func(name string, usage0, usage1 string) string {
//
// If name of the flag defined in the subset already present in a superset,
// flag values are merged. That is, flag will remain in the superset, but
// setting it will lead both parameters to be filled with same values.
// setting its value will make both parameters filled with received value.
// Description of each flag (if differ) is joined with MergeSeparator.
// Default values (and initial values of where flag.Value points to) are kept
// untouched and may differ if no value is set during parsing phase.
func Merge(super *flag.FlagSet, setup func(*flag.FlagSet)) {
fs := flag.NewFlagSet("", flag.ContinueOnError)
setup(fs)
Expand All @@ -452,9 +454,12 @@ func merge(dst, src *flag.Flag) {
dst.Name, src.Name,
))
}
src.Value.Set(dst.Value.String())
// NOTE: we don't change dst.DefValue since it remains unchanged as well as
// in flag package.
if dst.DefValue != src.DefValue {
// Clear default values to be printed in usage to empty string since
// they are differ.
dst.DefValue = ""
src.DefValue = ""
}
dst.Value = valuePair{dst.Value, src.Value}
dst.Usage = mergeUsage(dst.Name, dst.Usage, src.Usage)
}
Expand Down
6 changes: 3 additions & 3 deletions flagutil_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ func ExampleMerge() {

// Output:
// 42
// 42
// 84
// 34
// 34
// some flag usage here / another flag usage here
Expand Down Expand Up @@ -227,8 +227,8 @@ func TestMerge(t *testing.T) {
Merge(fs, func(fs *flag.FlagSet) {
fs.StringVar(&s2, "foo", "baq", "subset2 usage")
})
if s0 != s1 || s1 != s2 {
t.Fatalf("strings are not equal: %q vs %q vs %q", s0, s1, s2)
if s0 == s1 || s1 == s2 {
t.Fatalf("strings are equal: %q vs %q vs %q", s0, s1, s2)
}
if err := fs.Set("foo", "42"); err != nil {
t.Fatal(err)
Expand Down

0 comments on commit 35e0775

Please sign in to comment.