Skip to content
Myr

Fix generated bash completion for Bash 3 (OSX) (#520)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* Make preamble functions unique to command Prior to this commit the functions in the preamble had names that didn't vary based on the command for which the bash completion was generated. This meant that if you had two bash completions with differences in the preamble functions then only the last loaded function would be available. This commit prefixes all of these functions with the name of the command so that multiple cobra generated completion files won't clash. Signed-off-by: John McCabe <john@johnmccabe.net> * Fix function names in writeFlagHandler The references to the `__handle_filename_extension_flag` and `__handle_subdirs_in_dir_flag` functions in `writeFlagHandler` hadn't been updated correctly in the previous commits. Signed-off-by: John McCabe <john@johnmccabe.net> * Pass cmd into writeFlagHandler This commit passes the cmd pointer into the writeFlagHandler so that the `__handle_filename_extension_flag` and `__handle_subdirs_in_dir_flag` functions can have the `cmd.Name()` prefixed. * Update Bash completion tests Prefixes the tested `__handle_filename_extension_flag` and `__handle_subdirs_in_dir_flag` functions with the command name.

authored by John McCabe · committed by Eric Paris · parent 9395926 · Browse files · 2 files+52 added−51 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+52 added−51 removed

  • other:+52 added−51 removed

2 files+52 added−51 removed

modified:bash_completions_test.go+3 added-2 removed
1package cobra23import (4 "bytes"5 "fmt"6 "os"7 "os/exec"8 "strings"9 "testing"
136 unmodified lines
146 check(t, output, `flags_completion+=("_filedir")`)147 // check for filename extension flags148 check(t, output, `must_have_one_noun+=("three")`)149 // check for filename extension flags149 check(t, output, `flags_completion+=("__handle_filename_extension_flag json|yaml|yml")`)150 check(t, output, fmt.Sprintf(`flags_completion+=("__%s_handle_filename_extension_flag json|yaml|yml")`, rootCmd.Name()))151 // check for custom flags152 check(t, output, `flags_completion+=("__complete_custom")`)153 // check for subdirs_in_dir flags153 check(t, output, `flags_completion+=("__handle_subdirs_in_dir_flag themes")`)154 check(t, output, fmt.Sprintf(`flags_completion+=("__%s_handle_subdirs_in_dir_flag themes")`, rootCmd.Name()))155156 checkOmit(t, output, deprecatedCmd.Name())157158 // If available, run shellcheck against the script.
39 unmodified lines
modified:bash_completions.go+49 added-49 removed
19 unmodified lines
20)2122func writePreamble(buf *bytes.Buffer, name string) {23 buf.WriteString(fmt.Sprintf("# bash completion for %-36s -*- shell-script -*-\n", name))24 buf.WriteString(`25__debug()24 buf.WriteString(fmt.Sprintf(`25__%[1]s_debug()26{27 if [[ -n ${BASH_COMP_DEBUG_FILE} ]]; then28 echo "$*" >> "${BASH_COMP_DEBUG_FILE}"29 fi30}3132# Homebrew on Macs have version 1.3 of bash-completion which doesn't include33# _init_completion. This is a very minimal version of that function.34__my_init_completion()34__%[1]s_init_completion()35{36 COMPREPLY=()37 _get_comp_words_by_ref "$@" cur prev words cword38}3940__index_of_word()40__%[1]s_index_of_word()41{42 local w word=$143 shift44 index=0
3 unmodified lines
48 done49 index=-150}5152__contains_word()52__%[1]s_contains_word()53{54 local w word=$1; shift55 for w in "$@"; do56 [[ $w = "$word" ]] && return57 done58 return 159}6061__handle_reply()61__%[1]s_handle_reply()62{63 __debug "${FUNCNAME[0]}"63 __%[1]s_debug "${FUNCNAME[0]}"64 case $cur in65 -*)66 if [[ $(type -t compopt) = "builtin" ]]; then67 compopt -o nospace
16 unmodified lines
84 fi8586 local index flag87 flag="${cur%%=*}"88 __index_of_word "${flag}" "${flags_with_completion[@]}"88 __%[1]s_index_of_word "${flag}" "${flags_with_completion[@]}"89 COMPREPLY=()90 if [[ ${index} -ge 0 ]]; then91 PREFIX=""92 cur="${cur#*=}"
9 unmodified lines
102 esac103104 # check if we are handling a flag with special work handling105 local index106 __index_of_word "${prev}" "${flags_with_completion[@]}"106 __%[1]s_index_of_word "${prev}" "${flags_with_completion[@]}"107 if [[ ${index} -ge 0 ]]; then108 ${flags_completion[${index}]}109 return110 fi
27 unmodified lines
138 fi139}140141# The arguments should be in the form "ext1|ext2|extn"142__handle_filename_extension_flag()142__%[1]s_handle_filename_extension_flag()143{144 local ext="$1"145 _filedir "@(${ext})"146}147148__handle_subdirs_in_dir_flag()148__%[1]s_handle_subdirs_in_dir_flag()149{150 local dir="$1"151 pushd "${dir}" >/dev/null 2>&1 && _filedir -d && popd >/dev/null 2>&1152}153154__handle_flag()154__%[1]s_handle_flag()155{156 __debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}"156 __%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}"157158 # if a command required a flag, and we found it, unset must_have_one_flag()159 local flagname=${words[c]}160 local flagvalue
2 unmodified lines
163 flagvalue=${flagname#*=} # take in as flagvalue after the =164 flagname=${flagname%%=*} # strip everything after the =165 flagname="${flagname}=" # but put the = back166 fi167 __debug "${FUNCNAME[0]}: looking for ${flagname}"168 if __contains_word "${flagname}" "${must_have_one_flag[@]}"; then167 __%[1]s_debug "${FUNCNAME[0]}: looking for ${flagname}"168 if __%[1]s_contains_word "${flagname}" "${must_have_one_flag[@]}"; then169 must_have_one_flag=()170 fi171172 # if you set a flag which only applies to this command, don't show subcommands173 if __contains_word "${flagname}" "${local_nonpersistent_flags[@]}"; then173 if __%[1]s_contains_word "${flagname}" "${local_nonpersistent_flags[@]}"; then174 commands=()175 fi176177 # keep flag value with flagname as flaghash
8 unmodified lines
186 fi187 fi188189 # skip the argument to a two word flag190 if __contains_word "${words[c]}" "${two_word_flags[@]}"; then190 if __%[1]s_contains_word "${words[c]}" "${two_word_flags[@]}"; then191 c=$((c+1))192 # if we are looking for a flags value, don't show commands193 if [[ $c -eq $cword ]]; then194 commands=()
3 unmodified lines
198 c=$((c+1))199200}201202__handle_noun()202__%[1]s_handle_noun()203{204 __debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}"204 __%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}"205206 if __contains_word "${words[c]}" "${must_have_one_noun[@]}"; then206 if __%[1]s_contains_word "${words[c]}" "${must_have_one_noun[@]}"; then207 must_have_one_noun=()208 elif __contains_word "${words[c]}" "${noun_aliases[@]}"; then208 elif __%[1]s_contains_word "${words[c]}" "${noun_aliases[@]}"; then209 must_have_one_noun=()210 fi211212 nouns+=("${words[c]}")213 c=$((c+1))214}215216__handle_command()216__%[1]s_handle_command()217{218 __debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}"218 __%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}"219220 local next_command221 if [[ -n ${last_command} ]]; then222 next_command="_${last_command}_${words[c]//:/__}"
4 unmodified lines
227 next_command="_${words[c]//:/__}"228 fi229 fi230 c=$((c+1))231 __debug "${FUNCNAME[0]}: looking for ${next_command}"231 __%[1]s_debug "${FUNCNAME[0]}: looking for ${next_command}"232 declare -F "$next_command" >/dev/null && $next_command233}234235__handle_word()235__%[1]s_handle_word()236{237 if [[ $c -ge $cword ]]; then238 __handle_reply238 __%[1]s_handle_reply239 return240 fi241 __debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}"241 __%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}"242 if [[ "${words[c]}" == -* ]]; then243 __handle_flag244 elif __contains_word "${words[c]}" "${commands[@]}"; then245 __handle_command246 elif [[ $c -eq 0 ]] && __contains_word "$(basename "${words[c]}")" "${commands[@]}"; then247 __handle_command243 __%[1]s_handle_flag244 elif __%[1]s_contains_word "${words[c]}" "${commands[@]}"; then245 __%[1]s_handle_command246 elif [[ $c -eq 0 ]] && __%[1]s_contains_word "$(basename "${words[c]}")" "${commands[@]}"; then247 __%[1]s_handle_command248 else249 __handle_noun249 __%[1]s_handle_noun250 fi251 __handle_word251 __%[1]s_handle_word252}253254`)254`, name))255}256257func writePostscript(buf *bytes.Buffer, name string) {258 name = strings.Replace(name, ":", "__", -1)
3 unmodified lines
262 declare -A flaghash 2>/dev/null || :263 if declare -F _init_completion >/dev/null 2>&1; then264 _init_completion -s || return265 else266 __my_init_completion -n "=" || return266 __%[1]s_init_completion -n "=" || return267 fi268269 local c=0270 local flags=()271 local two_word_flags=()272 local local_nonpersistent_flags=()273 local flags_with_completion=()274 local flags_completion=()275 local commands=("%s")275 local commands=("%[1]s")276 local must_have_one_flag=()277 local must_have_one_noun=()278 local last_command279 local nouns=()280281 __handle_word281 __%[1]s_handle_word282}283284`, name))285 buf.WriteString(fmt.Sprintf(`if [[ $(type -t compopt) = "builtin" ]]; then
16 unmodified lines
302 }303 buf.WriteString("\n")304}305306func writeFlagHandler(buf *bytes.Buffer, name string, annotations map[string][]string) {306func writeFlagHandler(buf *bytes.Buffer, name string, annotations map[string][]string, cmd *Command) {307 for key, value := range annotations {308 switch key {309 case BashCompFilenameExt:310 buf.WriteString(fmt.Sprintf(" flags_with_completion+=(%q)\n", name))311312 var ext string313 if len(value) > 0 {314 ext = "__handle_filename_extension_flag " + strings.Join(value, "|")314 ext = fmt.Sprintf("__%s_handle_filename_extension_flag ", cmd.Name()) + strings.Join(value, "|")315 } else {316 ext = "_filedir"317 }318 buf.WriteString(fmt.Sprintf(" flags_completion+=(%q)\n", ext))
9 unmodified lines
328 buf.WriteString(fmt.Sprintf(" flags_with_completion+=(%q)\n", name))329330 var ext string331 if len(value) == 1 {332 ext = "__handle_subdirs_in_dir_flag " + value[0]332 ext = fmt.Sprintf("__%s_handle_subdirs_in_dir_flag ", cmd.Name()) + value[0]333 } else {334 ext = "_filedir -d"335 }336 buf.WriteString(fmt.Sprintf(" flags_completion+=(%q)\n", ext))337 }338 }339}340341func writeShortFlag(buf *bytes.Buffer, flag *pflag.Flag) {341func writeShortFlag(buf *bytes.Buffer, flag *pflag.Flag, cmd *Command) {342 name := flag.Shorthand343 format := " "344 if len(flag.NoOptDefVal) == 0 {345 format += "two_word_"346 }347 format += "flags+=(\"-%s\")\n"348 buf.WriteString(fmt.Sprintf(format, name))349 writeFlagHandler(buf, "-"+name, flag.Annotations)349 writeFlagHandler(buf, "-"+name, flag.Annotations, cmd)350}351352func writeFlag(buf *bytes.Buffer, flag *pflag.Flag) {352func writeFlag(buf *bytes.Buffer, flag *pflag.Flag, cmd *Command) {353 name := flag.Name354 format := " flags+=(\"--%s"355 if len(flag.NoOptDefVal) == 0 {356 format += "="357 }358 format += "\")\n"359 buf.WriteString(fmt.Sprintf(format, name))360 writeFlagHandler(buf, "--"+name, flag.Annotations)360 writeFlagHandler(buf, "--"+name, flag.Annotations, cmd)361}362363func writeLocalNonPersistentFlag(buf *bytes.Buffer, flag *pflag.Flag) {364 name := flag.Name
17 unmodified lines
382 cmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {383 if nonCompletableFlag(flag) {384 return385 }386 writeFlag(buf, flag)386 writeFlag(buf, flag, cmd)387 if len(flag.Shorthand) > 0 {388 writeShortFlag(buf, flag)388 writeShortFlag(buf, flag, cmd)389 }390 if localNonPersistentFlags.Lookup(flag.Name) != nil {391 writeLocalNonPersistentFlag(buf, flag)392 }
1 unmodified line
394 cmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) {395 if nonCompletableFlag(flag) {396 return397 }398 writeFlag(buf, flag)398 writeFlag(buf, flag, cmd)399 if len(flag.Shorthand) > 0 {400 writeShortFlag(buf, flag)400 writeShortFlag(buf, flag, cmd)401 }402 })403404 buf.WriteString("\n")
139 unmodified lines