cobra: unable to redefine ‘h’ shorthand

January 15, 2022 0 By addshore

Cobra is both a library for creating powerful modern CLI applications as well as a program to generate applications and command files”

I’m currently using Cobra in the MediaWiki CLI project and recently came across an error while trying to auto-generate docs.

panic: unable to redefine 'h' shorthand in "login" flagset: it's already used for "hostname" flag

goroutine 1 [running]:
github.com/spf13/pflag.(*FlagSet).AddFlag(0xc0000b5d00, 0xc00053d680)
        /go/pkg/mod/github.com/spf13/pflag@v1.0.5/flag.go:874 +0x6f0Code language: PHP (php)

I’m not actually trying to redefine this flag, but it looks like by default cobra always uses the -h flag for a help command, if you don’t define a help flag that doesn’t have the shorthand.

Cobra does this in the command execute method, meaning you can set your own help command, and the default will not be set.

func (c *Command) execute(a []string) (err error) {
	// initialize help and version flag at the last point possible to allow for user
	// overriding
	c.InitDefaultHelpFlag()Code language: JavaScript (javascript)

https://github.com/spf13/cobra/blob/de187e874d1ca382320088f8f6d76333408e5c2e/command.go#L778-L780

This InitDefaultHelpFlag method looks for any existing flags on a command called help and will only set its default if one does not already exist.

func (c *Command) InitDefaultHelpFlag() {
	c.mergePersistentFlags()
	if c.Flags().Lookup("help") == nil {
		usage := "help for "
		if c.Name() == "" {
			usage += "this command"
		} else {
			usage += c.Name()
		}
		c.Flags().BoolP("help", "h", false, usage)
	}
}Code language: JavaScript (javascript)

https://github.com/spf13/cobra/blob/de187e874d1ca382320088f8f6d76333408e5c2e/command.go#L1028-L1042

In order to override this default help command in your commands, all you need to do is set a flag called help, without the shorthand.

// Remove the -h help shorthand, as gitlab auth login uses it for hostname
rootCmd.PersistentFlags().BoolP("help", "", false, "help for this command")Code language: JavaScript (javascript)

Your help flag will no longer have the shorthand, and you’ll no longer get such conflicts.