feat(completion): support no space format of short flags https://github.com/spf13/cobra/issues/1629

This commit is contained in:
Denis Gukov 2022-06-13 22:26:13 +05:00
parent 87ea1807f7
commit d90b117809
2 changed files with 27 additions and 1 deletions

View file

@ -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))
}

View file

@ -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",