Bash completion V2 with completion descriptions (#1146)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Bash completion v2 This v2 version of bash completion is based on Go completions. It also supports descriptions like the other shells. Signed-off-by: Marc Khouzam <marc.khouzam@montreal.ca> * Only consider matching completions for formatting Signed-off-by: Marc Khouzam <marc.khouzam@montreal.ca> * Use bash compV2 for the default completion command Signed-off-by: Marc Khouzam <marc.khouzam@montreal.ca> * Update comments that still referred to bash completion
authored by Marc Khouzam · committed by GitHub · parent d0f318d · Browse files · 6 files·+346 added−17 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Signed-off-by: Marc Khouzam <marc.khouzam@montreal.ca>
Diff stats
6 files+346 added−17 removed
- other:+346 added−17 removed
Provenance
- Commit
b361960- Tree
959dacd- Author
Marc Khouzam <marc.khouzam@montreal.ca>- Committer
GitHub <noreply@github.com>- Parent
d0f318d
6 files changed+346 added−17 removed
modified:bash_completions.md+2 added
4 unmodified lines56789101112131479 unmodified lines4 unmodified lines## Bash legacy dynamic completions
For backward compatibility, Cobra still supports its legacy dynamic completion solution (described below). Unlike the `ValidArgsFunction` solution, the legacy solution will only work for Bash shell-completion and not for other shells. This legacy solution can be used along-side `ValidArgsFunction` and `RegisterFlagCompletionFunc()`, as long as both solutions are not used for the same command. This provides a path to gradually migrate from the legacy solution to the new solution.
**Note**: Cobra's default `completion` command uses bash completion V2. If you are currently using Cobra's legacy dynamic completion solution, you should not use the default `completion` command but continue using your own.
The legacy solution allows you to inject bash functions into the bash completion script. Those bash functions are responsible for providing the completion choices for your own completions.
Some code that works in kubernetes:
79 unmodified linesadded:bash_completionsV2.go+302 added
1+package cobra2+3+import (4+ "bytes"5+ "fmt"6+ "io"7+ "os"8+)9+10+func (c *Command) genBashCompletion(w io.Writer, includeDesc bool) error {11+ buf := new(bytes.Buffer)12+ genBashComp(buf, c.Name(), includeDesc)13+ _, err := buf.WriteTo(w)14+ return err15+}16+17+func genBashComp(buf io.StringWriter, name string, includeDesc bool) {18+ compCmd := ShellCompRequestCmd19+ if !includeDesc {20+ compCmd = ShellCompNoDescRequestCmd21+ }22+23+ WriteStringAndCheck(buf, fmt.Sprintf(`# bash completion V2 for %-36[1]s -*- shell-script -*-24+25+__%[1]s_debug()26+{27+ if [[ -n ${BASH_COMP_DEBUG_FILE:-} ]]; then28+ echo "$*" >> "${BASH_COMP_DEBUG_FILE}"29+ fi30+}31+32+# Macs have bash3 for which the bash-completion package doesn't include33+# _init_completion. This is a minimal version of that function.34+__%[1]s_init_completion()35+{36+ COMPREPLY=()37+ _get_comp_words_by_ref "$@" cur prev words cword38+}39+40+# This function calls the %[1]s program to obtain the completion41+# results and the directive. It fills the 'out' and 'directive' vars.42+__%[1]s_get_completion_results() {43+ local requestComp lastParam lastChar args44+45+ # Prepare the command to request completions for the program.46+ # Calling ${words[0]} instead of directly %[1]s allows to handle aliases47+ args=("${words[@]:1}")48+ requestComp="${words[0]} %[2]s ${args[*]}"49+50+ lastParam=${words[$((${#words[@]}-1))]}51+ lastChar=${lastParam:$((${#lastParam}-1)):1}52+ __%[1]s_debug "lastParam ${lastParam}, lastChar ${lastChar}"53+54+ if [ -z "${cur}" ] && [ "${lastChar}" != "=" ]; then55+ # If the last parameter is complete (there is a space following it)56+ # We add an extra empty parameter so we can indicate this to the go method.57+ __%[1]s_debug "Adding extra empty parameter"58+ requestComp="${requestComp} ''"59+ fi60+61+ # When completing a flag with an = (e.g., %[1]s -n=<TAB>)62+ # bash focuses on the part after the =, so we need to remove63+ # the flag part from $cur64+ if [[ "${cur}" == -*=* ]]; then65+ cur="${cur#*=}"66+ fi67+68+ __%[1]s_debug "Calling ${requestComp}"69+ # Use eval to handle any environment variables and such70+ out=$(eval "${requestComp}" 2>/dev/null)71+72+ # Extract the directive integer at the very end of the output following a colon (:)73+ directive=${out##*:}74+ # Remove the directive75+ out=${out%%:*}76+ if [ "${directive}" = "${out}" ]; then77+ # There is not directive specified78+ directive=079+ fi80+ __%[1]s_debug "The completion directive is: ${directive}"81+ __%[1]s_debug "The completions are: ${out[*]}"82+}83+84+__%[1]s_process_completion_results() {85+ local shellCompDirectiveError=%[3]d86+ local shellCompDirectiveNoSpace=%[4]d87+ local shellCompDirectiveNoFileComp=%[5]d88+ local shellCompDirectiveFilterFileExt=%[6]d89+ local shellCompDirectiveFilterDirs=%[7]d90+91+ if [ $((directive & shellCompDirectiveError)) -ne 0 ]; then92+ # Error code. No completion.93+ __%[1]s_debug "Received error from custom completion go code"94+ return95+ else96+ if [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ]; then97+ if [[ $(type -t compopt) = "builtin" ]]; then98+ __%[1]s_debug "Activating no space"99+ compopt -o nospace100+ else101+ __%[1]s_debug "No space directive not supported in this version of bash"102+ fi103+ fi104+ if [ $((directive & shellCompDirectiveNoFileComp)) -ne 0 ]; then105+ if [[ $(type -t compopt) = "builtin" ]]; then106+ __%[1]s_debug "Activating no file completion"107+ compopt +o default108+ else109+ __%[1]s_debug "No file completion directive not supported in this version of bash"110+ fi111+ fi112+ fi113+114+ if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then115+ # File extension filtering116+ local fullFilter filter filteringCmd117+118+ # Do not use quotes around the $out variable or else newline119+ # characters will be kept.120+ for filter in ${out[*]}; do121+ fullFilter+="$filter|"122+ done123+124+ filteringCmd="_filedir $fullFilter"125+ __%[1]s_debug "File filtering command: $filteringCmd"126+ $filteringCmd127+ elif [ $((directive & shellCompDirectiveFilterDirs)) -ne 0 ]; then128+ # File completion for directories only129+130+ # Use printf to strip any trailing newline131+ local subdir132+ subdir=$(printf "%%s" "${out[0]}")133+ if [ -n "$subdir" ]; then134+ __%[1]s_debug "Listing directories in $subdir"135+ pushd "$subdir" >/dev/null 2>&1 && _filedir -d && popd >/dev/null 2>&1 || return136+ else137+ __%[1]s_debug "Listing directories in ."138+ _filedir -d139+ fi140+ else141+ __%[1]s_handle_standard_completion_case142+ fi143+144+ __%[1]s_handle_special_char "$cur" :145+ __%[1]s_handle_special_char "$cur" =146+}147+148+__%[1]s_handle_standard_completion_case() {149+ local tab comp150+ tab=$(printf '\t')151+152+ local longest=0153+ # Look for the longest completion so that we can format things nicely154+ while IFS='' read -r comp; do155+ # Strip any description before checking the length156+ comp=${comp%%%%$tab*}157+ # Only consider the completions that match158+ comp=$(compgen -W "$comp" -- "$cur")159+ if ((${#comp}>longest)); then160+ longest=${#comp}161+ fi162+ done < <(printf "%%s\n" "${out[@]}")163+164+ local completions=()165+ while IFS='' read -r comp; do166+ if [ -z "$comp" ]; then167+ continue168+ fi169+170+ __%[1]s_debug "Original comp: $comp"171+ comp="$(__%[1]s_format_comp_descriptions "$comp" "$longest")"172+ __%[1]s_debug "Final comp: $comp"173+ completions+=("$comp")174+ done < <(printf "%%s\n" "${out[@]}")175+176+ while IFS='' read -r comp; do177+ COMPREPLY+=("$comp")178+ done < <(compgen -W "${completions[*]}" -- "$cur")179+180+ # If there is a single completion left, remove the description text181+ if [ ${#COMPREPLY[*]} -eq 1 ]; then182+ __%[1]s_debug "COMPREPLY[0]: ${COMPREPLY[0]}"183+ comp="${COMPREPLY[0]%%%% *}"184+ __%[1]s_debug "Removed description from single completion, which is now: ${comp}"185+ COMPREPLY=()186+ COMPREPLY+=("$comp")187+ fi188+}189+190+__%[1]s_handle_special_char()191+{192+ local comp="$1"193+ local char=$2194+ if [[ "$comp" == *${char}* && "$COMP_WORDBREAKS" == *${char}* ]]; then195+ local word=${comp%%"${comp##*${char}}"}196+ local idx=${#COMPREPLY[*]}197+ while [[ $((--idx)) -ge 0 ]]; do198+ COMPREPLY[$idx]=${COMPREPLY[$idx]#"$word"}199+ done200+ fi201+}202+203+__%[1]s_format_comp_descriptions()204+{205+ local tab206+ tab=$(printf '\t')207+ local comp="$1"208+ local longest=$2209+210+ # Properly format the description string which follows a tab character if there is one211+ if [[ "$comp" == *$tab* ]]; then212+ desc=${comp#*$tab}213+ comp=${comp%%%%$tab*}214+215+ # $COLUMNS stores the current shell width.216+ # Remove an extra 4 because we add 2 spaces and 2 parentheses.217+ maxdesclength=$(( COLUMNS - longest - 4 ))218+219+ # Make sure we can fit a description of at least 8 characters220+ # if we are to align the descriptions.221+ if [[ $maxdesclength -gt 8 ]]; then222+ # Add the proper number of spaces to align the descriptions223+ for ((i = ${#comp} ; i < longest ; i++)); do224+ comp+=" "225+ done226+ else227+ # Don't pad the descriptions so we can fit more text after the completion228+ maxdesclength=$(( COLUMNS - ${#comp} - 4 ))229+ fi230+231+ # If there is enough space for any description text,232+ # truncate the descriptions that are too long for the shell width233+ if [ $maxdesclength -gt 0 ]; then234+ if [ ${#desc} -gt $maxdesclength ]; then235+ desc=${desc:0:$(( maxdesclength - 1 ))}236+ desc+="…"237+ fi238+ comp+=" ($desc)"239+ fi240+ fi241+242+ # Must use printf to escape all special characters243+ printf "%%q" "${comp}"244+}245+246+__start_%[1]s()247+{248+ local cur prev words cword split249+250+ COMPREPLY=()251+252+ # Call _init_completion from the bash-completion package253+ # to prepare the arguments properly254+ if declare -F _init_completion >/dev/null 2>&1; then255+ _init_completion -n "=:" || return256+ else257+ __%[1]s_init_completion -n "=:" || return258+ fi259+260+ __%[1]s_debug261+ __%[1]s_debug "========= starting completion logic =========="262+ __%[1]s_debug "cur is ${cur}, words[*] is ${words[*]}, #words[@] is ${#words[@]}, cword is $cword"263+264+ # The user could have moved the cursor backwards on the command-line.265+ # We need to trigger completion from the $cword location, so we need266+ # to truncate the command-line ($words) up to the $cword location.267+ words=("${words[@]:0:$cword+1}")268+ __%[1]s_debug "Truncated words[*]: ${words[*]},"269+270+ local out directive271+ __%[1]s_get_completion_results272+ __%[1]s_process_completion_results273+}274+275+if [[ $(type -t compopt) = "builtin" ]]; then276+ complete -o default -F __start_%[1]s %[1]s277+else278+ complete -o default -o nospace -F __start_%[1]s %[1]s279+fi280+281+# ex: ts=4 sw=4 et filetype=sh282+`, name, compCmd,283+ ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp,284+ ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs))285+}286+287+// GenBashCompletionFileV2 generates Bash completion version 2.288+func (c *Command) GenBashCompletionFileV2(filename string, includeDesc bool) error {289+ outFile, err := os.Create(filename)290+ if err != nil {291+ return err292+ }293+ defer outFile.Close()294+295+ return c.GenBashCompletionV2(outFile, includeDesc)296+}297+298+// GenBashCompletionV2 generates Bash completion file version 2299+// and writes it to the passed writer.300+func (c *Command) GenBashCompletionV2(w io.Writer, includeDesc bool) error {301+ return c.genBashCompletion(w, includeDesc)302+}modified:command.go+6 added-5 removed
61 unmodified lines62 63 // Example is examples of how to use the command.64 Example string65 66- // ValidArgs is list of all valid non-flag arguments that are accepted in bash completions66+ // ValidArgs is list of all valid non-flag arguments that are accepted in shell completions67 ValidArgs []string68- // ValidArgsFunction is an optional function that provides valid non-flag arguments for bash completion.68+ // ValidArgsFunction is an optional function that provides valid non-flag arguments for shell completion.69 // It is a dynamic version of using ValidArgs.70 // Only one of ValidArgs and ValidArgsFunction can be used for a command.71 ValidArgsFunction func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)72 73 // Expected arguments74 Args PositionalArgs75 76 // ArgAliases is List of aliases for ValidArgs.77- // These are not suggested to the user in the bash completion,77+ // These are not suggested to the user in the shell completion,78 // but accepted if entered manually.79 ArgAliases []string80 81- // BashCompletionFunction is custom functions used by the bash autocompletion generator.81+ // BashCompletionFunction is custom bash functions used by the legacy bash autocompletion generator.82+ // For portability with other shells, it is recommended to instead use ValidArgsFunction83 BashCompletionFunction string84 85 // Deprecated defines, if this command is deprecated and should print this string when used.86 Deprecated string851 unmodified lines938 if c.args == nil && filepath.Base(os.Args[0]) != "cobra.test" {939 args = os.Args[1:]940 }941 941- // initialize the hidden command to be used for bash completion942+ // initialize the hidden command to be used for shell completion943 c.initCompleteCmd(args)944 945 var flags []string946 if c.TraverseChildren {734 unmodified linesmodified:completions_test.go+2 added-10 removed
2095 unmodified lines2096 // Remove completion command for the next test2097 removeCompCmd(rootCmd)2098 2099 var compCmd *Command2100- // Test that the --no-descriptions flag is present for the relevant shells only2100+ // Test that the --no-descriptions flag is present on all shells2101 assertNoErr(t, rootCmd.Execute())2102- for _, shell := range []string{"fish", "powershell", "zsh"} {2102+ for _, shell := range []string{"bash", "fish", "powershell", "zsh"} {2103 if compCmd, _, err = rootCmd.Find([]string{compCmdName, shell}); err != nil {2104 t.Errorf("Unexpected error: %v", err)2105 }2106 if flag := compCmd.Flags().Lookup(compCmdNoDescFlagName); flag == nil {2107 t.Errorf("Missing --%s flag for %s shell", compCmdNoDescFlagName, shell)2108 }2109 }2110- for _, shell := range []string{"bash"} {2111- if compCmd, _, err = rootCmd.Find([]string{compCmdName, shell}); err != nil {2112- t.Errorf("Unexpected error: %v", err)2113- }2114- if flag := compCmd.Flags().Lookup(compCmdNoDescFlagName); flag != nil {2115- t.Errorf("Unexpected --%s flag for %s shell", compCmdNoDescFlagName, shell)2116- }2117- }2110 // Remove completion command for the next test2111 removeCompCmd(rootCmd)2112 2113 // Test that the '--no-descriptions' flag can be disabled175 unmodified linesmodified:completions.go+4 added-2 removed
32 unmodified lines33 ShellCompDirectiveNoSpace34 35 // ShellCompDirectiveNoFileComp indicates that the shell should not provide36 // file completion even when no completion is provided.37- // This currently does not work for zsh or bash < 437 ShellCompDirectiveNoFileComp38 39 // ShellCompDirectiveFilterFileExt indicates that the provided completions40 // should be used as file extension filters.549 unmodified lines590 Args: NoArgs,591 DisableFlagsInUseLine: true,592 ValidArgsFunction: NoFileCompletions,593 RunE: func(cmd *Command, args []string) error {595- return cmd.Root().GenBashCompletion(out)594+ return cmd.Root().GenBashCompletionV2(out, !noDesc)595 },596 }597+ if haveNoDescFlag {598+ bash.Flags().BoolVar(&noDesc, compCmdNoDescFlagName, compCmdNoDescFlagDefault, compCmdNoDescFlagDesc)599+ }600 601 zsh := &Command{602 Use: "zsh",603 Short: fmt.Sprintf(shortDesc, "zsh"),140 unmodified linesmodified:shell_completions.md+30 added
398 unmodified lines399 400 For backward compatibility, Cobra still supports its bash legacy dynamic completion solution.401 Please refer to [Bash Completions](bash_completions.md) for details.402 403+### Bash completion V2404+405+Cobra provides two versions for bash completion. The original bash completion (which started it all!) can be used by calling406+`GenBashCompletion()` or `GenBashCompletionFile()`.407+408+A new V2 bash completion version is also available. This version can be used by calling `GenBashCompletionV2()` or409+`GenBashCompletionFileV2()`. The V2 version does **not** support the legacy dynamic completion (see [Bash Completions]410+(bash_completions.md)) but instead works only with the Go dynamic completion solution described in this Readme.411+Unless your program already uses the legacy dynamic completion solution, it is recommended that you use the bash412+completion V2 solution which provides the following extra features:413+- Supports completion descriptions (like the other shells)414+- Small completion script of less than 300 lines (v1 generates scripts of thousands of lines; `kubectl` for example has a bash v1 completion script of over 13K lines)415+- Streamlined user experience thanks to a completion behavior aligned with the other shells 416+417+`Bash` completion V2 supports descriptions for completions. When calling `GenBashCompletionV2()` or `GenBashCompletionFileV2()`418+you must provide these functions with a parameter indicating if the completions should be annotated with a description; Cobra419+will provide the description automatically based on usage information. You can choose to make this option configurable by420+your users.421+422+```423+# With descriptions424+$ helm s[tab][tab]425+search (search for a keyword in charts) status (display the status of the named release)426+show (show information of a chart)427+428+# Without descriptions429+$ helm s[tab][tab]430+search show status431+```432+**Note**: Cobra's default `completion` command uses bash completion V2. If for some reason you need to use bash completion V1, you will need to implement your own `completion` command. 433 ## Zsh completions434 435 Cobra supports native zsh completion generated from the root `cobra.Command`.436 The generated completion script should be put somewhere in your `$fpath` and be named106 unmodified lines