diff --git a/completions.go b/completions.go index 3de4e87a..d9137743 100644 --- a/completions.go +++ b/completions.go @@ -480,7 +480,7 @@ func getFlagNameCompletions(flag *pflag.Flag, toComplete string) []string { } flagName = "-" + flag.Shorthand - if len(flag.Shorthand) > 0 && strings.HasPrefix(flagName, toComplete) { + if len(flag.Shorthand) > 0 && (strings.HasPrefix(flagName, toComplete) || strings.HasPrefix(toComplete, flagName)) { completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage)) } diff --git a/completions_test.go b/completions_test.go index 28a3228e..59c36b7d 100644 --- a/completions_test.go +++ b/completions_test.go @@ -473,6 +473,32 @@ func TestValidArgsFuncAndCmdCompletionInGo(t *testing.T) { } } +func TestShorthandFlagCompletionInGoWithDesc(t *testing.T) { + rootCmd := &Command{ + Use: "root", + Run: emptyRun, + } + + rootCmd.Flags().StringP("first", "f", "", "first flag") + rootCmd.Flags().StringP("second", "d", "", "second flag") + + // Test that flag names are completed + output, err := executeCommand(rootCmd, ShellCompRequestCmd, "-ftest") + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + expected := strings.Join([]string{ + "-f\tfirst flag", + ":4", + "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n") + + if output != expected { + t.Errorf("expected: %q, got: %q", expected, output) + } + +} + func TestFlagNameCompletionInGo(t *testing.T) { rootCmd := &Command{ Use: "root",