Help Flag Shorthand & Usage Customization

This patch allows users to the value used for the help flag's
shorthand character so that when there's a global "host" flag, it can
use the "h" for its shorthand and the help flag can use "?".
Additionally, the ability to format the help flag's usage value would
also be nice for applications with different casing standards for help
output.

Users should simply set cobra.HelpFlagShorthand (defaults to "h") to the
desired shorthand value while using cobra.HelpFlagUsageFormatString to
specify a format string for the flag's usage value. The format string
accept a single substitution, the command's name.
This commit is contained in:
akutz 2015-08-23 14:11:53 -05:00
parent e4993076d8
commit 1169e1f351
2 changed files with 12 additions and 1 deletions

View file

@ -34,6 +34,15 @@ var EnablePrefixMatching bool = false
// enables an information splash screen on Windows if the CLI is started from explorer.exe.
var EnableWindowsMouseTrap bool = true
// HelpFlagShorthand is the character used to for the help flag's shorthand notation. The
// default value is "h".
var HelpFlagShorthand string = "h"
// HelpFlagUsageFormatString is the format string used with fmt.Sprintf to produce the
// usage value for the help flag. The name of a given command is substituted in the
// formatted result.
var HelpFlagUsageFormatString string = "help for %s"
var MousetrapHelpText string = `This is a command line tool
You need to open cmd.exe and run it from there.

View file

@ -859,7 +859,9 @@ func (c *Command) Flags() *flag.FlagSet {
c.flagErrorBuf = new(bytes.Buffer)
}
c.flags.SetOutput(c.flagErrorBuf)
c.PersistentFlags().BoolVarP(&c.helpFlagVal, "help", "h", false, "help for "+c.Name())
c.PersistentFlags().BoolVarP(&c.helpFlagVal, "help",
HelpFlagShorthand, false,
fmt.Sprintf(HelpFlagUsageFormatString, c.Name()))
}
return c.flags
}