Skip to content

Commit ba1052d

Browse files
dtaniwakieparis
authored andcommitted
Fix two word flags (#807)
1 parent 7547e83 commit ba1052d

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-1
lines changed

bash_completions.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -199,7 +199,8 @@ __%[1]s_handle_flag()
199199
fi
200200
201201
# skip the argument to a two word flag
202-
if __%[1]s_contains_word "${words[c]}" "${two_word_flags[@]}"; then
202+
if [[ ${words[c]} != *"="* ]] && __%[1]s_contains_word "${words[c]}" "${two_word_flags[@]}"; then
203+
__%[1]s_debug "${FUNCNAME[0]}: found a flag ${words[c]}, skip the next argument"
203204
c=$((c+1))
204205
# if we are looking for a flags value, don't show commands
205206
if [[ $c -eq $cword ]]; then
@@ -379,6 +380,10 @@ func writeFlag(buf *bytes.Buffer, flag *pflag.Flag, cmd *Command) {
379380
}
380381
format += "\")\n"
381382
buf.WriteString(fmt.Sprintf(format, name))
383+
if len(flag.NoOptDefVal) == 0 {
384+
format = " two_word_flags+=(\"--%s\")\n"
385+
buf.WriteString(fmt.Sprintf(format, name))
386+
}
382387
writeFlagHandler(buf, "--"+name, flag.Annotations, cmd)
383388
}
384389

bash_completions_test.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,10 @@ func TestBashCompletions(t *testing.T) {
9595
rootCmd.Flags().String("theme", "", "theme to use (located in /themes/THEMENAME/)")
9696
rootCmd.Flags().SetAnnotation("theme", BashCompSubdirsInDir, []string{"themes"})
9797

98+
// For two word flags check
99+
rootCmd.Flags().StringP("two", "t", "", "this is two word flags")
100+
rootCmd.Flags().BoolP("two-w-default", "T", false, "this is not two word flags")
101+
98102
echoCmd := &Command{
99103
Use: "echo [string to echo]",
100104
Aliases: []string{"say"},
@@ -183,6 +187,12 @@ func TestBashCompletions(t *testing.T) {
183187
// check for subdirs_in_dir flags in a subcommand
184188
checkRegex(t, output, fmt.Sprintf(`_root_echo\(\)\n{[^}]*flags_completion\+=\("__%s_handle_subdirs_in_dir_flag config"\)`, rootCmd.Name()))
185189

190+
// check two word flags
191+
check(t, output, `two_word_flags+=("--two")`)
192+
check(t, output, `two_word_flags+=("-t")`)
193+
checkOmit(t, output, `two_word_flags+=("--two-w-default")`)
194+
checkOmit(t, output, `two_word_flags+=("-T")`)
195+
186196
checkOmit(t, output, deprecatedCmd.Name())
187197

188198
// If available, run shellcheck against the script.

0 commit comments

Comments
 (0)