diff --git a/command.go b/command.go index c05fed45a..59057b4fe 100644 --- a/command.go +++ b/command.go @@ -1226,6 +1226,9 @@ func (c *Command) InitDefaultHelpFlag() { } else { usage += name } + if f := c.Flags().ShorthandLookup("h"); f != nil { + panic(fmt.Sprintf("shorthand '-h' is reserved for the help flag, but is already used by flag '%s'", f.Name)) + } c.Flags().BoolP(helpFlagName, "h", false, usage) _ = c.Flags().SetAnnotation(helpFlagName, FlagSetByCobraAnnotation, []string{"true"}) } diff --git a/command_test.go b/command_test.go index a86e57f0a..74eb02130 100644 --- a/command_test.go +++ b/command_test.go @@ -938,6 +938,29 @@ func TestInitHelpFlagMergesFlags(t *testing.T) { } } +// related to https://github.com/spf13/cobra/issues/2359 +func TestInitDefaultHelpFlagPanicsWhenHShorthandAlreadyUsed(t *testing.T) { + cmd := &Command{Use: "root"} + + cmd.PersistentFlags().BoolP("ayuda", "h", false, "help") + + func() { + defer func() { + r := recover() + if r == nil { + t.Fatalf("expected InitDefaultHelpFlag to panic") + } + // Without Cobra's explicit guard, pflag will also panic on duplicate shorthands. + // Assert on the message to ensure we hit Cobra's clearer, intentional panic. + msg := fmt.Sprint(r) + if !strings.Contains(msg, "reserved for the help flag") { + t.Fatalf("expected reserved -h panic message, got: %v", r) + } + }() + cmd.InitDefaultHelpFlag() + }() +} + func TestHelpCommandExecuted(t *testing.T) { rootCmd := &Command{Use: "root", Long: "Long description", Run: emptyRun} rootCmd.AddCommand(&Command{Use: "child", Run: emptyRun})