Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix:(issue_1263) FlagNames should return names set via env as well #1537

Merged
merged 1 commit into from Oct 22, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
24 changes: 22 additions & 2 deletions context.go
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
Comment on lines +104 to +105
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To ensure (more?) consistent behavior

Suggested change
return unames
sort.Strings(unames)
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
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add sort.Strings here, too?

}
Expand Down
4 changes: 4 additions & 0 deletions flag_test.go
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
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