From ba1052d4cbce7aac421a96de820558f75199ccbc Mon Sep 17 00:00:00 2001 From: Daisuke Taniwaki Date: Mon, 11 Mar 2019 21:55:09 +0900 Subject: [PATCH] Fix two word flags (#807) --- bash_completions.go | 7 ++++++- bash_completions_test.go | 10 ++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/bash_completions.go b/bash_completions.go index 30e7427..c3c1e50 100644 --- a/bash_completions.go +++ b/bash_completions.go @@ -199,7 +199,8 @@ __%[1]s_handle_flag() fi # skip the argument to a two word flag - if __%[1]s_contains_word "${words[c]}" "${two_word_flags[@]}"; then + if [[ ${words[c]} != *"="* ]] && __%[1]s_contains_word "${words[c]}" "${two_word_flags[@]}"; then + __%[1]s_debug "${FUNCNAME[0]}: found a flag ${words[c]}, skip the next argument" c=$((c+1)) # if we are looking for a flags value, don't show commands if [[ $c -eq $cword ]]; then @@ -379,6 +380,10 @@ func writeFlag(buf *bytes.Buffer, flag *pflag.Flag, cmd *Command) { } format += "\")\n" buf.WriteString(fmt.Sprintf(format, name)) + if len(flag.NoOptDefVal) == 0 { + format = " two_word_flags+=(\"--%s\")\n" + buf.WriteString(fmt.Sprintf(format, name)) + } writeFlagHandler(buf, "--"+name, flag.Annotations, cmd) } diff --git a/bash_completions_test.go b/bash_completions_test.go index dd0fa52..eefa3de 100644 --- a/bash_completions_test.go +++ b/bash_completions_test.go @@ -95,6 +95,10 @@ func TestBashCompletions(t *testing.T) { rootCmd.Flags().String("theme", "", "theme to use (located in /themes/THEMENAME/)") rootCmd.Flags().SetAnnotation("theme", BashCompSubdirsInDir, []string{"themes"}) + // For two word flags check + rootCmd.Flags().StringP("two", "t", "", "this is two word flags") + rootCmd.Flags().BoolP("two-w-default", "T", false, "this is not two word flags") + echoCmd := &Command{ Use: "echo [string to echo]", Aliases: []string{"say"}, @@ -183,6 +187,12 @@ func TestBashCompletions(t *testing.T) { // check for subdirs_in_dir flags in a subcommand checkRegex(t, output, fmt.Sprintf(`_root_echo\(\)\n{[^}]*flags_completion\+=\("__%s_handle_subdirs_in_dir_flag config"\)`, rootCmd.Name())) + // check two word flags + check(t, output, `two_word_flags+=("--two")`) + check(t, output, `two_word_flags+=("-t")`) + checkOmit(t, output, `two_word_flags+=("--two-w-default")`) + checkOmit(t, output, `two_word_flags+=("-T")`) + checkOmit(t, output, deprecatedCmd.Name()) // If available, run shellcheck against the script.