| Abhay Kumar | a61c522 | 2025-11-10 07:32:50 +0000 | [diff] [blame^] | 1 | // Copyright 2013-2023 The Cobra Authors |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | package cobra |
| 16 | |
| 17 | import ( |
| 18 | "bytes" |
| 19 | "fmt" |
| 20 | "io" |
| 21 | "os" |
| 22 | ) |
| 23 | |
| 24 | func (c *Command) genBashCompletion(w io.Writer, includeDesc bool) error { |
| 25 | buf := new(bytes.Buffer) |
| 26 | genBashComp(buf, c.Name(), includeDesc) |
| 27 | _, err := buf.WriteTo(w) |
| 28 | return err |
| 29 | } |
| 30 | |
| 31 | func genBashComp(buf io.StringWriter, name string, includeDesc bool) { |
| 32 | compCmd := ShellCompRequestCmd |
| 33 | if !includeDesc { |
| 34 | compCmd = ShellCompNoDescRequestCmd |
| 35 | } |
| 36 | |
| 37 | WriteStringAndCheck(buf, fmt.Sprintf(`# bash completion V2 for %-36[1]s -*- shell-script -*- |
| 38 | |
| 39 | __%[1]s_debug() |
| 40 | { |
| 41 | if [[ -n ${BASH_COMP_DEBUG_FILE-} ]]; then |
| 42 | echo "$*" >> "${BASH_COMP_DEBUG_FILE}" |
| 43 | fi |
| 44 | } |
| 45 | |
| 46 | # Macs have bash3 for which the bash-completion package doesn't include |
| 47 | # _init_completion. This is a minimal version of that function. |
| 48 | __%[1]s_init_completion() |
| 49 | { |
| 50 | COMPREPLY=() |
| 51 | _get_comp_words_by_ref "$@" cur prev words cword |
| 52 | } |
| 53 | |
| 54 | # This function calls the %[1]s program to obtain the completion |
| 55 | # results and the directive. It fills the 'out' and 'directive' vars. |
| 56 | __%[1]s_get_completion_results() { |
| 57 | local requestComp lastParam lastChar args |
| 58 | |
| 59 | # Prepare the command to request completions for the program. |
| 60 | # Calling ${words[0]} instead of directly %[1]s allows handling aliases |
| 61 | args=("${words[@]:1}") |
| 62 | requestComp="${words[0]} %[2]s ${args[*]}" |
| 63 | |
| 64 | lastParam=${words[$((${#words[@]}-1))]} |
| 65 | lastChar=${lastParam:$((${#lastParam}-1)):1} |
| 66 | __%[1]s_debug "lastParam ${lastParam}, lastChar ${lastChar}" |
| 67 | |
| 68 | if [[ -z ${cur} && ${lastChar} != = ]]; then |
| 69 | # If the last parameter is complete (there is a space following it) |
| 70 | # We add an extra empty parameter so we can indicate this to the go method. |
| 71 | __%[1]s_debug "Adding extra empty parameter" |
| 72 | requestComp="${requestComp} ''" |
| 73 | fi |
| 74 | |
| 75 | # When completing a flag with an = (e.g., %[1]s -n=<TAB>) |
| 76 | # bash focuses on the part after the =, so we need to remove |
| 77 | # the flag part from $cur |
| 78 | if [[ ${cur} == -*=* ]]; then |
| 79 | cur="${cur#*=}" |
| 80 | fi |
| 81 | |
| 82 | __%[1]s_debug "Calling ${requestComp}" |
| 83 | # Use eval to handle any environment variables and such |
| 84 | out=$(eval "${requestComp}" 2>/dev/null) |
| 85 | |
| 86 | # Extract the directive integer at the very end of the output following a colon (:) |
| 87 | directive=${out##*:} |
| 88 | # Remove the directive |
| 89 | out=${out%%:*} |
| 90 | if [[ ${directive} == "${out}" ]]; then |
| 91 | # There is not directive specified |
| 92 | directive=0 |
| 93 | fi |
| 94 | __%[1]s_debug "The completion directive is: ${directive}" |
| 95 | __%[1]s_debug "The completions are: ${out}" |
| 96 | } |
| 97 | |
| 98 | __%[1]s_process_completion_results() { |
| 99 | local shellCompDirectiveError=%[3]d |
| 100 | local shellCompDirectiveNoSpace=%[4]d |
| 101 | local shellCompDirectiveNoFileComp=%[5]d |
| 102 | local shellCompDirectiveFilterFileExt=%[6]d |
| 103 | local shellCompDirectiveFilterDirs=%[7]d |
| 104 | local shellCompDirectiveKeepOrder=%[8]d |
| 105 | |
| 106 | if (((directive & shellCompDirectiveError) != 0)); then |
| 107 | # Error code. No completion. |
| 108 | __%[1]s_debug "Received error from custom completion go code" |
| 109 | return |
| 110 | else |
| 111 | if (((directive & shellCompDirectiveNoSpace) != 0)); then |
| 112 | if [[ $(type -t compopt) == builtin ]]; then |
| 113 | __%[1]s_debug "Activating no space" |
| 114 | compopt -o nospace |
| 115 | else |
| 116 | __%[1]s_debug "No space directive not supported in this version of bash" |
| 117 | fi |
| 118 | fi |
| 119 | if (((directive & shellCompDirectiveKeepOrder) != 0)); then |
| 120 | if [[ $(type -t compopt) == builtin ]]; then |
| 121 | # no sort isn't supported for bash less than < 4.4 |
| 122 | if [[ ${BASH_VERSINFO[0]} -lt 4 || ( ${BASH_VERSINFO[0]} -eq 4 && ${BASH_VERSINFO[1]} -lt 4 ) ]]; then |
| 123 | __%[1]s_debug "No sort directive not supported in this version of bash" |
| 124 | else |
| 125 | __%[1]s_debug "Activating keep order" |
| 126 | compopt -o nosort |
| 127 | fi |
| 128 | else |
| 129 | __%[1]s_debug "No sort directive not supported in this version of bash" |
| 130 | fi |
| 131 | fi |
| 132 | if (((directive & shellCompDirectiveNoFileComp) != 0)); then |
| 133 | if [[ $(type -t compopt) == builtin ]]; then |
| 134 | __%[1]s_debug "Activating no file completion" |
| 135 | compopt +o default |
| 136 | else |
| 137 | __%[1]s_debug "No file completion directive not supported in this version of bash" |
| 138 | fi |
| 139 | fi |
| 140 | fi |
| 141 | |
| 142 | # Separate activeHelp from normal completions |
| 143 | local completions=() |
| 144 | local activeHelp=() |
| 145 | __%[1]s_extract_activeHelp |
| 146 | |
| 147 | if (((directive & shellCompDirectiveFilterFileExt) != 0)); then |
| 148 | # File extension filtering |
| 149 | local fullFilter="" filter filteringCmd |
| 150 | |
| 151 | # Do not use quotes around the $completions variable or else newline |
| 152 | # characters will be kept. |
| 153 | for filter in ${completions[*]}; do |
| 154 | fullFilter+="$filter|" |
| 155 | done |
| 156 | |
| 157 | filteringCmd="_filedir $fullFilter" |
| 158 | __%[1]s_debug "File filtering command: $filteringCmd" |
| 159 | $filteringCmd |
| 160 | elif (((directive & shellCompDirectiveFilterDirs) != 0)); then |
| 161 | # File completion for directories only |
| 162 | |
| 163 | local subdir |
| 164 | subdir=${completions[0]} |
| 165 | if [[ -n $subdir ]]; then |
| 166 | __%[1]s_debug "Listing directories in $subdir" |
| 167 | pushd "$subdir" >/dev/null 2>&1 && _filedir -d && popd >/dev/null 2>&1 || return |
| 168 | else |
| 169 | __%[1]s_debug "Listing directories in ." |
| 170 | _filedir -d |
| 171 | fi |
| 172 | else |
| 173 | __%[1]s_handle_completion_types |
| 174 | fi |
| 175 | |
| 176 | __%[1]s_handle_special_char "$cur" : |
| 177 | __%[1]s_handle_special_char "$cur" = |
| 178 | |
| 179 | # Print the activeHelp statements before we finish |
| 180 | __%[1]s_handle_activeHelp |
| 181 | } |
| 182 | |
| 183 | __%[1]s_handle_activeHelp() { |
| 184 | # Print the activeHelp statements |
| 185 | if ((${#activeHelp[*]} != 0)); then |
| 186 | if [ -z $COMP_TYPE ]; then |
| 187 | # Bash v3 does not set the COMP_TYPE variable. |
| 188 | printf "\n"; |
| 189 | printf "%%s\n" "${activeHelp[@]}" |
| 190 | printf "\n" |
| 191 | __%[1]s_reprint_commandLine |
| 192 | return |
| 193 | fi |
| 194 | |
| 195 | # Only print ActiveHelp on the second TAB press |
| 196 | if [ $COMP_TYPE -eq 63 ]; then |
| 197 | printf "\n" |
| 198 | printf "%%s\n" "${activeHelp[@]}" |
| 199 | |
| 200 | if ((${#COMPREPLY[*]} == 0)); then |
| 201 | # When there are no completion choices from the program, file completion |
| 202 | # may kick in if the program has not disabled it; in such a case, we want |
| 203 | # to know if any files will match what the user typed, so that we know if |
| 204 | # there will be completions presented, so that we know how to handle ActiveHelp. |
| 205 | # To find out, we actually trigger the file completion ourselves; |
| 206 | # the call to _filedir will fill COMPREPLY if files match. |
| 207 | if (((directive & shellCompDirectiveNoFileComp) == 0)); then |
| 208 | __%[1]s_debug "Listing files" |
| 209 | _filedir |
| 210 | fi |
| 211 | fi |
| 212 | |
| 213 | if ((${#COMPREPLY[*]} != 0)); then |
| 214 | # If there are completion choices to be shown, print a delimiter. |
| 215 | # Re-printing the command-line will automatically be done |
| 216 | # by the shell when it prints the completion choices. |
| 217 | printf -- "--" |
| 218 | else |
| 219 | # When there are no completion choices at all, we need |
| 220 | # to re-print the command-line since the shell will |
| 221 | # not be doing it itself. |
| 222 | __%[1]s_reprint_commandLine |
| 223 | fi |
| 224 | elif [ $COMP_TYPE -eq 37 ] || [ $COMP_TYPE -eq 42 ]; then |
| 225 | # For completion type: menu-complete/menu-complete-backward and insert-completions |
| 226 | # the completions are immediately inserted into the command-line, so we first |
| 227 | # print the activeHelp message and reprint the command-line since the shell won't. |
| 228 | printf "\n" |
| 229 | printf "%%s\n" "${activeHelp[@]}" |
| 230 | |
| 231 | __%[1]s_reprint_commandLine |
| 232 | fi |
| 233 | fi |
| 234 | } |
| 235 | |
| 236 | __%[1]s_reprint_commandLine() { |
| 237 | # The prompt format is only available from bash 4.4. |
| 238 | # We test if it is available before using it. |
| 239 | if (x=${PS1@P}) 2> /dev/null; then |
| 240 | printf "%%s" "${PS1@P}${COMP_LINE[@]}" |
| 241 | else |
| 242 | # Can't print the prompt. Just print the |
| 243 | # text the user had typed, it is workable enough. |
| 244 | printf "%%s" "${COMP_LINE[@]}" |
| 245 | fi |
| 246 | } |
| 247 | |
| 248 | # Separate activeHelp lines from real completions. |
| 249 | # Fills the $activeHelp and $completions arrays. |
| 250 | __%[1]s_extract_activeHelp() { |
| 251 | local activeHelpMarker="%[9]s" |
| 252 | local endIndex=${#activeHelpMarker} |
| 253 | |
| 254 | while IFS='' read -r comp; do |
| 255 | [[ -z $comp ]] && continue |
| 256 | |
| 257 | if [[ ${comp:0:endIndex} == $activeHelpMarker ]]; then |
| 258 | comp=${comp:endIndex} |
| 259 | __%[1]s_debug "ActiveHelp found: $comp" |
| 260 | if [[ -n $comp ]]; then |
| 261 | activeHelp+=("$comp") |
| 262 | fi |
| 263 | else |
| 264 | # Not an activeHelp line but a normal completion |
| 265 | completions+=("$comp") |
| 266 | fi |
| 267 | done <<<"${out}" |
| 268 | } |
| 269 | |
| 270 | __%[1]s_handle_completion_types() { |
| 271 | __%[1]s_debug "__%[1]s_handle_completion_types: COMP_TYPE is $COMP_TYPE" |
| 272 | |
| 273 | case $COMP_TYPE in |
| 274 | 37|42) |
| 275 | # Type: menu-complete/menu-complete-backward and insert-completions |
| 276 | # If the user requested inserting one completion at a time, or all |
| 277 | # completions at once on the command-line we must remove the descriptions. |
| 278 | # https://github.com/spf13/cobra/issues/1508 |
| 279 | |
| 280 | # If there are no completions, we don't need to do anything |
| 281 | (( ${#completions[@]} == 0 )) && return 0 |
| 282 | |
| 283 | local tab=$'\t' |
| 284 | |
| 285 | # Strip any description and escape the completion to handled special characters |
| 286 | IFS=$'\n' read -ra completions -d '' < <(printf "%%q\n" "${completions[@]%%%%$tab*}") |
| 287 | |
| 288 | # Only consider the completions that match |
| 289 | IFS=$'\n' read -ra COMPREPLY -d '' < <(IFS=$'\n'; compgen -W "${completions[*]}" -- "${cur}") |
| 290 | |
| 291 | # compgen looses the escaping so we need to escape all completions again since they will |
| 292 | # all be inserted on the command-line. |
| 293 | IFS=$'\n' read -ra COMPREPLY -d '' < <(printf "%%q\n" "${COMPREPLY[@]}") |
| 294 | ;; |
| 295 | |
| 296 | *) |
| 297 | # Type: complete (normal completion) |
| 298 | __%[1]s_handle_standard_completion_case |
| 299 | ;; |
| 300 | esac |
| 301 | } |
| 302 | |
| 303 | __%[1]s_handle_standard_completion_case() { |
| 304 | local tab=$'\t' |
| 305 | |
| 306 | # If there are no completions, we don't need to do anything |
| 307 | (( ${#completions[@]} == 0 )) && return 0 |
| 308 | |
| 309 | # Short circuit to optimize if we don't have descriptions |
| 310 | if [[ "${completions[*]}" != *$tab* ]]; then |
| 311 | # First, escape the completions to handle special characters |
| 312 | IFS=$'\n' read -ra completions -d '' < <(printf "%%q\n" "${completions[@]}") |
| 313 | # Only consider the completions that match what the user typed |
| 314 | IFS=$'\n' read -ra COMPREPLY -d '' < <(IFS=$'\n'; compgen -W "${completions[*]}" -- "${cur}") |
| 315 | |
| 316 | # compgen looses the escaping so, if there is only a single completion, we need to |
| 317 | # escape it again because it will be inserted on the command-line. If there are multiple |
| 318 | # completions, we don't want to escape them because they will be printed in a list |
| 319 | # and we don't want to show escape characters in that list. |
| 320 | if (( ${#COMPREPLY[@]} == 1 )); then |
| 321 | COMPREPLY[0]=$(printf "%%q" "${COMPREPLY[0]}") |
| 322 | fi |
| 323 | return 0 |
| 324 | fi |
| 325 | |
| 326 | local longest=0 |
| 327 | local compline |
| 328 | # Look for the longest completion so that we can format things nicely |
| 329 | while IFS='' read -r compline; do |
| 330 | [[ -z $compline ]] && continue |
| 331 | |
| 332 | # Before checking if the completion matches what the user typed, |
| 333 | # we need to strip any description and escape the completion to handle special |
| 334 | # characters because those escape characters are part of what the user typed. |
| 335 | # Don't call "printf" in a sub-shell because it will be much slower |
| 336 | # since we are in a loop. |
| 337 | printf -v comp "%%q" "${compline%%%%$tab*}" &>/dev/null || comp=$(printf "%%q" "${compline%%%%$tab*}") |
| 338 | |
| 339 | # Only consider the completions that match |
| 340 | [[ $comp == "$cur"* ]] || continue |
| 341 | |
| 342 | # The completions matches. Add it to the list of full completions including |
| 343 | # its description. We don't escape the completion because it may get printed |
| 344 | # in a list if there are more than one and we don't want show escape characters |
| 345 | # in that list. |
| 346 | COMPREPLY+=("$compline") |
| 347 | |
| 348 | # Strip any description before checking the length, and again, don't escape |
| 349 | # the completion because this length is only used when printing the completions |
| 350 | # in a list and we don't want show escape characters in that list. |
| 351 | comp=${compline%%%%$tab*} |
| 352 | if ((${#comp}>longest)); then |
| 353 | longest=${#comp} |
| 354 | fi |
| 355 | done < <(printf "%%s\n" "${completions[@]}") |
| 356 | |
| 357 | # If there is a single completion left, remove the description text and escape any special characters |
| 358 | if ((${#COMPREPLY[*]} == 1)); then |
| 359 | __%[1]s_debug "COMPREPLY[0]: ${COMPREPLY[0]}" |
| 360 | COMPREPLY[0]=$(printf "%%q" "${COMPREPLY[0]%%%%$tab*}") |
| 361 | __%[1]s_debug "Removed description from single completion, which is now: ${COMPREPLY[0]}" |
| 362 | else |
| 363 | # Format the descriptions |
| 364 | __%[1]s_format_comp_descriptions $longest |
| 365 | fi |
| 366 | } |
| 367 | |
| 368 | __%[1]s_handle_special_char() |
| 369 | { |
| 370 | local comp="$1" |
| 371 | local char=$2 |
| 372 | if [[ "$comp" == *${char}* && "$COMP_WORDBREAKS" == *${char}* ]]; then |
| 373 | local word=${comp%%"${comp##*${char}}"} |
| 374 | local idx=${#COMPREPLY[*]} |
| 375 | while ((--idx >= 0)); do |
| 376 | COMPREPLY[idx]=${COMPREPLY[idx]#"$word"} |
| 377 | done |
| 378 | fi |
| 379 | } |
| 380 | |
| 381 | __%[1]s_format_comp_descriptions() |
| 382 | { |
| 383 | local tab=$'\t' |
| 384 | local comp desc maxdesclength |
| 385 | local longest=$1 |
| 386 | |
| 387 | local i ci |
| 388 | for ci in ${!COMPREPLY[*]}; do |
| 389 | comp=${COMPREPLY[ci]} |
| 390 | # Properly format the description string which follows a tab character if there is one |
| 391 | if [[ "$comp" == *$tab* ]]; then |
| 392 | __%[1]s_debug "Original comp: $comp" |
| 393 | desc=${comp#*$tab} |
| 394 | comp=${comp%%%%$tab*} |
| 395 | |
| 396 | # $COLUMNS stores the current shell width. |
| 397 | # Remove an extra 4 because we add 2 spaces and 2 parentheses. |
| 398 | maxdesclength=$(( COLUMNS - longest - 4 )) |
| 399 | |
| 400 | # Make sure we can fit a description of at least 8 characters |
| 401 | # if we are to align the descriptions. |
| 402 | if ((maxdesclength > 8)); then |
| 403 | # Add the proper number of spaces to align the descriptions |
| 404 | for ((i = ${#comp} ; i < longest ; i++)); do |
| 405 | comp+=" " |
| 406 | done |
| 407 | else |
| 408 | # Don't pad the descriptions so we can fit more text after the completion |
| 409 | maxdesclength=$(( COLUMNS - ${#comp} - 4 )) |
| 410 | fi |
| 411 | |
| 412 | # If there is enough space for any description text, |
| 413 | # truncate the descriptions that are too long for the shell width |
| 414 | if ((maxdesclength > 0)); then |
| 415 | if ((${#desc} > maxdesclength)); then |
| 416 | desc=${desc:0:$(( maxdesclength - 1 ))} |
| 417 | desc+="…" |
| 418 | fi |
| 419 | comp+=" ($desc)" |
| 420 | fi |
| 421 | COMPREPLY[ci]=$comp |
| 422 | __%[1]s_debug "Final comp: $comp" |
| 423 | fi |
| 424 | done |
| 425 | } |
| 426 | |
| 427 | __start_%[1]s() |
| 428 | { |
| 429 | local cur prev words cword split |
| 430 | |
| 431 | COMPREPLY=() |
| 432 | |
| 433 | # Call _init_completion from the bash-completion package |
| 434 | # to prepare the arguments properly |
| 435 | if declare -F _init_completion >/dev/null 2>&1; then |
| 436 | _init_completion -n =: || return |
| 437 | else |
| 438 | __%[1]s_init_completion -n =: || return |
| 439 | fi |
| 440 | |
| 441 | __%[1]s_debug |
| 442 | __%[1]s_debug "========= starting completion logic ==========" |
| 443 | __%[1]s_debug "cur is ${cur}, words[*] is ${words[*]}, #words[@] is ${#words[@]}, cword is $cword" |
| 444 | |
| 445 | # The user could have moved the cursor backwards on the command-line. |
| 446 | # We need to trigger completion from the $cword location, so we need |
| 447 | # to truncate the command-line ($words) up to the $cword location. |
| 448 | words=("${words[@]:0:$cword+1}") |
| 449 | __%[1]s_debug "Truncated words[*]: ${words[*]}," |
| 450 | |
| 451 | local out directive |
| 452 | __%[1]s_get_completion_results |
| 453 | __%[1]s_process_completion_results |
| 454 | } |
| 455 | |
| 456 | if [[ $(type -t compopt) = "builtin" ]]; then |
| 457 | complete -o default -F __start_%[1]s %[1]s |
| 458 | else |
| 459 | complete -o default -o nospace -F __start_%[1]s %[1]s |
| 460 | fi |
| 461 | |
| 462 | # ex: ts=4 sw=4 et filetype=sh |
| 463 | `, name, compCmd, |
| 464 | ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp, |
| 465 | ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, ShellCompDirectiveKeepOrder, |
| 466 | activeHelpMarker)) |
| 467 | } |
| 468 | |
| 469 | // GenBashCompletionFileV2 generates Bash completion version 2. |
| 470 | func (c *Command) GenBashCompletionFileV2(filename string, includeDesc bool) error { |
| 471 | outFile, err := os.Create(filename) |
| 472 | if err != nil { |
| 473 | return err |
| 474 | } |
| 475 | defer outFile.Close() |
| 476 | |
| 477 | return c.GenBashCompletionV2(outFile, includeDesc) |
| 478 | } |
| 479 | |
| 480 | // GenBashCompletionV2 generates Bash completion file version 2 |
| 481 | // and writes it to the passed writer. |
| 482 | func (c *Command) GenBashCompletionV2(w io.Writer, includeDesc bool) error { |
| 483 | return c.genBashCompletion(w, includeDesc) |
| 484 | } |