From fe69f2e3a341cc3f84b5416441d1e6a25bc8fb8f Mon Sep 17 00:00:00 2001 From: Albert Nigmatzianov Date: Thu, 27 Apr 2017 10:55:15 +0200 Subject: [PATCH] Make initHelpFlag public Used for solving #424 --- command.go | 13 ++++++++----- command_test.go | 2 +- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/command.go b/command.go index 4bf1e24..ebc9ab2 100644 --- a/command.go +++ b/command.go @@ -571,18 +571,19 @@ func (c *Command) execute(a []string) (err error) { // initialize help flag as the last point possible to allow for user // overriding - c.initHelpFlag() + c.InitDefaultHelpFlag() err = c.ParseFlags(a) if err != nil { return c.FlagErrorFunc()(c, err) } - // If help is called, regardless of other flags, return we want help + + // If help is called, regardless of other flags, return we want help. // Also say we need help if the command isn't runnable. helpVal, err := c.Flags().GetBool("help") if err != nil { // should be impossible to get here as we always declare a help - // flag in initHelpFlag() + // flag in InitDefaultHelpFlag() c.Println("\"help\" flag declared as non-bool. Please correct your code") return err } @@ -722,7 +723,9 @@ func (c *Command) ExecuteC() (cmd *Command, err error) { return cmd, nil } -func (c *Command) initHelpFlag() { +// InitDefaultHelpFlag adds default help flag to c. +// It is called automatically by executing the c or by calling help and usage. +func (c *Command) InitDefaultHelpFlag() { c.mergePersistentFlags() if c.Flags().Lookup("help") == nil { usage := "help for " @@ -755,7 +758,7 @@ func (c *Command) initHelpCmd() { c.Printf("Unknown help topic %#q\n", args) c.Root().Usage() } else { - cmd.initHelpFlag() // make possible 'help' flag to be shown + cmd.InitDefaultHelpFlag() // make possible 'help' flag to be shown cmd.Help() } }, diff --git a/command_test.go b/command_test.go index 91d1fb1..24abd3e 100644 --- a/command_test.go +++ b/command_test.go @@ -146,7 +146,7 @@ func TestInitHelpFlagMergesFlags(t *testing.T) { cmd := Command{Use: "do"} baseCmd.AddCommand(&cmd) - cmd.initHelpFlag() + cmd.InitDefaultHelpFlag() actual := cmd.Flags().Lookup("help").Usage if actual != usage { t.Fatalf("Expected the help flag from the base command with usage '%s', but got the default with usage '%s'", usage, actual)