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.
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
Provenance
- Commit
fd32f09- Tree
370aa45- Author
John McCabe <johnmccabe@users.noreply.github.com>- Committer
Eric Paris <eparis@redhat.com>- Parent
9395926
2 files changed+52 added−51 removed
modified:bash_completions_test.go+3 added-2 removed
1 package cobra2 3 import (4 "bytes"5+ "fmt"6 "os"7 "os/exec"8 "strings"9 "testing"136 unmodified lines146 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()))155 156 checkOmit(t, output, deprecatedCmd.Name())157 158 // If available, run shellcheck against the script.39 unmodified linesmodified:bash_completions.go+49 added-49 removed
19 unmodified lines20 )21 22 func 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 }31 32 # 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 }39 40-__index_of_word()40+__%[1]s_index_of_word()41 {42 local w word=$143 shift44 index=03 unmodified lines48 done49 index=-150 }51 52-__contains_word()52+__%[1]s_contains_word()53 {54 local w word=$1; shift55 for w in "$@"; do56 [[ $w = "$word" ]] && return57 done58 return 159 }60 61-__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 nospace16 unmodified lines84 fi85 86 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 lines102 esac103 104 # 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 fi27 unmodified lines138 fi139 }140 141 # 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 }147 148-__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 }153 154-__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]}"157 158 # if a command required a flag, and we found it, unset must_have_one_flag()159 local flagname=${words[c]}160 local flagvalue2 unmodified lines163 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 fi171 172 # 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 fi176 177 # keep flag value with flagname as flaghash8 unmodified lines186 fi187 fi188 189 # 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 lines198 c=$((c+1))199 200 }201 202-__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]}"205 206- 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 fi211 212 nouns+=("${words[c]}")213 c=$((c+1))214 }215 216-__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]}"219 220 local next_command221 if [[ -n ${last_command} ]]; then222 next_command="_${last_command}_${words[c]//:/__}"4 unmodified lines227 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 }234 235-__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 }253 254-`)254+`, name))255 }256 257 func writePostscript(buf *bytes.Buffer, name string) {258 name = strings.Replace(name, ":", "__", -1)3 unmodified lines262 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 fi268 269 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=()280 281- __handle_word281+ __%[1]s_handle_word282 }283 284 `, name))285 buf.WriteString(fmt.Sprintf(`if [[ $(type -t compopt) = "builtin" ]]; then16 unmodified lines302 }303 buf.WriteString("\n")304 }305 306-func writeFlagHandler(buf *bytes.Buffer, name string, annotations map[string][]string) {306+func 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))311 312 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 lines328 buf.WriteString(fmt.Sprintf(" flags_with_completion+=(%q)\n", name))329 330 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 }340 341-func writeShortFlag(buf *bytes.Buffer, flag *pflag.Flag) {341+func 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 }351 352-func writeFlag(buf *bytes.Buffer, flag *pflag.Flag) {352+func 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 }362 363 func writeLocalNonPersistentFlag(buf *bytes.Buffer, flag *pflag.Flag) {364 name := flag.Name17 unmodified lines382 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 line394 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 })403 404 buf.WriteString("\n")139 unmodified lines