Skip to content

Commit

Permalink
Add RemoveFlag() function
Browse files Browse the repository at this point in the history
This adds the ability to remove a Flag from a FlagSet, e.g. `flagSet.RemoveFlag("my-flag")`

My end-goal is to allow cobra commands to opt-out of PersistentFlags() that they inherit. Please LMK if I'm on the wrong track here.

(plus a few formatting changes)

Merge spf13#358
  • Loading branch information
tiegz authored and hoshsadiq committed Apr 9, 2023
1 parent fc0e889 commit a6f7e06
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
9 changes: 9 additions & 0 deletions flag.go
Original file line number Diff line number Diff line change
Expand Up @@ -904,6 +904,15 @@ func (fs *FlagSet) AddFlag(flag *Flag) {
fs.shorthands[flag.Shorthand] = flag
}

// RemoveFlag will remove the flag from the FlagSet
func (fs *FlagSet) RemoveFlag(name string) {
normalizedFlagName := fs.normalizeFlagName(name)
_, exists := fs.formal[normalizedFlagName]
if exists {
delete(fs.formal, normalizedFlagName)
}
}

// AddFlagSet adds one FlagSet to another. If a flag is already present in f
// the flag from newSet will be ignored.
func (fs *FlagSet) AddFlagSet(newSet *FlagSet) {
Expand Down
31 changes: 31 additions & 0 deletions flag_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,37 @@ func TestAddFlagSet(t *testing.T) {
}
}

func TestAddFlag(t *testing.T) {
fs := zflag.NewFlagSet("adding-flags", zflag.ContinueOnError)
fs.AddFlag(&zflag.Flag{
Name: "a-flag",
Shorthand: 'a',
Usage: "the usage",
})

if len(zflag.GetFlagFormalField(fs)) != 1 {
t.Errorf("Unexpected result adding a Flag to a FlagSet %v", fs)
}
}

func TestRemoveFlag(t *testing.T) {
fs := zflag.NewFlagSet("removing-flags", zflag.ContinueOnError)
fs.String("string1", "a", "enter a string1")
fs.String("string2", "b", "enter a string2")

fs.RemoveFlag("string1")

formal := zflag.GetFlagFormalField(fs)
if len(formal) != 1 {
t.Errorf("Flagset %v should only have 1 formal flag now, but has %d.", fs, len(formal))
}
fs.VisitAll(func(f *zflag.Flag) {
if f.Name == "string1" {
t.Errorf("Flag string1 was not removed from %v formal flags.", fs)
}
})
}

func TestAnnotation(t *testing.T) {
f := zflag.NewFlagSet("shorthand", zflag.ContinueOnError)

Expand Down

0 comments on commit a6f7e06

Please sign in to comment.