Skip to content

Commit

Permalink
Fix:(issue_1263) FlagNames should return names set via env as well
Browse files Browse the repository at this point in the history
  • Loading branch information
dearchap committed Oct 16, 2022
1 parent 5ac0710 commit e302525
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 4 deletions.
24 changes: 22 additions & 2 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,15 +82,35 @@ func (cCtx *Context) IsSet(name string) bool {
func (cCtx *Context) LocalFlagNames() []string {
var names []string
cCtx.flagSet.Visit(makeFlagNameVisitor(&names))
return names
// Check the flags which have been set via env or file
if cCtx.Command != nil && cCtx.Command.Flags != nil {
for _, f := range cCtx.Command.Flags {
if f.IsSet() {
names = append(names, f.Names()...)
}
}
}

// Sort out the duplicates since flag could be set via multiple
// paths
m := map[string]struct{}{}
var unames []string
for _, name := range names {
if _, ok := m[name]; !ok {
m[name] = struct{}{}
unames = append(unames, name)
}
}

return unames
}

// FlagNames returns a slice of flag names used by the this context and all of
// its parent contexts.
func (cCtx *Context) FlagNames() []string {
var names []string
for _, pCtx := range cCtx.Lineage() {
pCtx.flagSet.Visit(makeFlagNameVisitor(&names))
names = append(names, pCtx.LocalFlagNames()...)
}
return names
}
Expand Down
4 changes: 4 additions & 0 deletions flag_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,10 @@ func TestFlagsFromEnv(t *testing.T) {
t.Errorf("Flag %s not set", f.Names()[0])
}

// check that flag names are returned when set via env as well
if !reflect.DeepEqual(ctx.FlagNames(), test.flag.Names()) {
t.Errorf("Not enough flag names %+v", ctx.FlagNames())
}
return nil
},
}
Expand Down
4 changes: 2 additions & 2 deletions sliceflag_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -156,8 +156,8 @@ func ExampleMultiStringFlag() {
//---
//Setting all flags via environment...
//
//Flag names: []
//Local flag names: []
//Flag names: ["flag-one" "1" "two" "2" "flag-three" "3" "flag-four" "4"]
//Local flag names: ["flag-one" "1" "two" "2" "flag-three" "3" "flag-four" "4"]
//Context values:
//"flag-one"=["v 9" "v 10"]
//"two"=["v 11" "v 12"]
Expand Down

0 comments on commit e302525

Please sign in to comment.