From e8bd799c1c06ecd2aebd7a5ec67173a34ddf0f0d Mon Sep 17 00:00:00 2001 From: Eric Paris Date: Sun, 16 Aug 2015 22:14:43 -0700 Subject: [PATCH] Display pflag.CommandLine flags as if they were declared on the parent ```go package main import ( "github.com/spf13/cobra" "github.com/spf13/pflag" ) func main() { cmd := &cobra.Command{ Use: "min", Short: "minimal command", Run: func(_ *cobra.Command, _ []string) {}, } pflag.String("oncmdline", "oncmdline", "oncmdline") cmd.Execute() } ``` Is a minimal cobra program. When --help is displayed without this patch you only get: But with the patch --oncmdline is shows under flags. --- cobra_test.go | 8 ++++++++ command.go | 8 +++++++- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/cobra_test.go b/cobra_test.go index 7cb4917d..4fc3b88b 100644 --- a/cobra_test.go +++ b/cobra_test.go @@ -963,3 +963,11 @@ func TestGlobalNormFuncPropagation(t *testing.T) { t.Error("cmdPrint and cmdEchoSub should had the normalization function of rootCmd") } } + +func TestFlagOnPflagCommandLine(t *testing.T) { + flagName := "flagOnCommandLine" + pflag.CommandLine.String(flagName, "", "about my flag") + r := fullSetupTest("--help") + + checkResultContains(t, r, flagName) +} diff --git a/command.go b/command.go index 74565c2b..cbbc3264 100644 --- a/command.go +++ b/command.go @@ -158,7 +158,6 @@ func (c *Command) SetHelpTemplate(s string) { func (c *Command) SetGlobalNormalizationFunc(n func(f *flag.FlagSet, name string) flag.NormalizedName) { c.Flags().SetNormalizeFunc(n) c.PersistentFlags().SetNormalizeFunc(n) - c.LocalFlags().SetNormalizeFunc(n) c.globNormFunc = n for _, command := range c.commands { @@ -873,6 +872,13 @@ func (c *Command) LocalFlags() *flag.FlagSet { c.lflags.VisitAll(func(f *flag.Flag) { local.AddFlag(f) }) + if !c.HasParent() { + flag.CommandLine.VisitAll(func(f *flag.Flag) { + if local.Lookup(f.Name) == nil { + local.AddFlag(f) + } + }) + } return local }