diff --git a/context.go b/context.go index 315c2fb596..dbf50e495f 100644 --- a/context.go +++ b/context.go @@ -82,7 +82,27 @@ 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 @@ -90,7 +110,7 @@ func (cCtx *Context) LocalFlagNames() []string { 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 } diff --git a/docs/v2/examples/flags.md b/docs/v2/examples/flags.md index 44c643a397..873c6ff7e7 100644 --- a/docs/v2/examples/flags.md +++ b/docs/v2/examples/flags.md @@ -51,7 +51,8 @@ func main() { ``` You can also set a destination variable for a flag, to which the content will be -scanned. +scanned. Note that if the `Value` is set for the flag, it will be shown as default, +and destination will be set to this value before parsing flag on the command line.