From e0e7ef766bf91748c5c55258e3773edaea7ed5f4 Mon Sep 17 00:00:00 2001 From: Eric Paris Date: Sat, 15 Aug 2015 16:05:51 -0400 Subject: New AddFlagSet function on FlagSet This function allows one to create a different FlagSets and then easily merge them together. --- flag.go | 13 +++++++++++++ flag_test.go | 17 +++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/flag.go b/flag.go index c99ccf3..603c81a 100644 --- a/flag.go +++ b/flag.go @@ -524,6 +524,19 @@ func (f *FlagSet) AddFlag(flag *Flag) { f.shorthands[c] = flag } +// AddFlagSet adds one FlagSet to another. If a flag is already present in f +// the flag from newSet will be ignored +func (f *FlagSet) AddFlagSet(newSet *FlagSet) { + if newSet == nil { + return + } + newSet.VisitAll(func(flag *Flag) { + if f.Lookup(flag.Name) == nil { + f.AddFlag(flag) + } + }) +} + // Var defines a flag with the specified name and usage string. The type and // value of the flag are represented by the first argument, of type Value, which // typically holds a user-defined implementation of Value. For instance, the diff --git a/flag_test.go b/flag_test.go index 9ff1934..5114f28 100644 --- a/flag_test.go +++ b/flag_test.go @@ -110,6 +110,23 @@ func TestUsage(t *testing.T) { } } +func TestAddFlagSet(t *testing.T) { + oldSet := NewFlagSet("old", ContinueOnError) + newSet := NewFlagSet("new", ContinueOnError) + + oldSet.String("flag1", "flag1", "flag1") + oldSet.String("flag2", "flag2", "flag2") + + newSet.String("flag2", "flag2", "flag2") + newSet.String("flag3", "flag3", "flag3") + + oldSet.AddFlagSet(newSet) + + if len(oldSet.formal) != 3 { + t.Errorf("Unexpected result adding a FlagSet to a FlagSet %v", oldSet) + } +} + func TestAnnotation(t *testing.T) { f := NewFlagSet("shorthand", ContinueOnError) -- cgit v1.2.3