@hop-top/kit 0.5.0-alpha.5 → 0.5.0-alpha.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/LICENSE-cobra.txt +174 -0
  3. package/NOTICE +15 -0
  4. package/README.md +10 -10
  5. package/dist/{alias-BOj0-VAr.d.ts → alias-BsJ2jGqQ.d.ts} +9 -1
  6. package/dist/alias.d.ts +1 -1
  7. package/dist/alias.js +4 -2
  8. package/dist/chunk-263IZ6Z6.js +915 -0
  9. package/dist/{chunk-S45UHXQF.js → chunk-DIDN4X5C.js} +8 -6
  10. package/dist/{chunk-ZC5TZYZJ.js → chunk-GHPJJV5L.js} +7 -3
  11. package/dist/chunk-JKMQSAJP.js +174 -0
  12. package/dist/chunk-JZ22ZUFA.js +1131 -0
  13. package/dist/chunk-NLMS7HGP.js +178 -0
  14. package/dist/chunk-QQQYCWSC.js +240 -0
  15. package/dist/chunk-XJTRY453.js +868 -0
  16. package/dist/{cli-8rfITnv4.d.ts → cli-C5B5tnpA.d.ts} +1 -60
  17. package/dist/cli.d.ts +2 -1
  18. package/dist/cli.js +5 -3
  19. package/dist/completion-sDKVXPUL.d.ts +109 -0
  20. package/dist/completion-values-By-mnjNt.d.ts +142 -0
  21. package/dist/completion-values.d.ts +1 -0
  22. package/dist/completion-values.js +29 -0
  23. package/dist/completion.d.ts +3 -0
  24. package/dist/completion.js +34 -0
  25. package/dist/compliance-AxFf-uMy.d.ts +60 -0
  26. package/dist/compliance.d.ts +1 -0
  27. package/dist/compliance.js +17 -0
  28. package/dist/config-CaK60ByQ.d.ts +241 -0
  29. package/dist/config.d.ts +1 -1
  30. package/dist/config.js +4 -2
  31. package/dist/{index-DEyjGoo2.d.ts → index-DCe1boBz.d.ts} +1 -1
  32. package/dist/index.d.ts +10 -4
  33. package/dist/index.js +40 -20
  34. package/dist/log-CkaxMX3U.d.ts +115 -0
  35. package/dist/log.d.ts +2 -0
  36. package/dist/log.js +14 -0
  37. package/dist/parity-CvMuYcVI.d.ts +61 -0
  38. package/dist/toolspec-UrWnoJ3Y.d.ts +336 -0
  39. package/dist/toolspec.d.ts +2 -0
  40. package/dist/toolspec.js +36 -0
  41. package/dist/tui/index.d.ts +3 -2
  42. package/package.json +43 -3
  43. package/src/alias.test.ts +110 -1
  44. package/src/alias.ts +19 -4
  45. package/src/cli.ts +5 -0
  46. package/src/completion-scripts.ts +16 -0
  47. package/src/completion-values.test.ts +70 -10
  48. package/src/completion-values.ts +170 -66
  49. package/src/completion.conformance.test.ts +297 -0
  50. package/src/completion.test.ts +256 -145
  51. package/src/completion.ts +764 -121
  52. package/src/config-merge.test.ts +425 -0
  53. package/src/config.test.ts +41 -0
  54. package/src/config.ts +265 -18
  55. package/src/index.test.ts +2 -1
  56. package/src/index.ts +8 -1
  57. package/src/log.test.ts +270 -1
  58. package/src/log.ts +172 -44
  59. package/src/published-types.test.ts +18 -0
  60. package/src/toolspec-internal.ts +197 -0
  61. package/src/toolspec-manifest.test.ts +82 -0
  62. package/src/toolspec-manifest.ts +404 -0
  63. package/src/toolspec-spec-schemas.ts +12 -0
  64. package/src/toolspec-spec.test.ts +273 -0
  65. package/src/toolspec-spec.ts +458 -0
  66. package/src/toolspec.from-command.test.ts +216 -0
  67. package/src/toolspec.ts +159 -0
  68. package/test/toolspec/fixture.ts +73 -0
  69. package/dist/chunk-IQXEISMC.js +0 -142
  70. package/dist/config-Bm9fBXch.d.ts +0 -134
@@ -0,0 +1,1131 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
+
3
+
4
+
5
+
6
+ var _chunkJKMQSAJPjs = require('./chunk-JKMQSAJP.js');
7
+
8
+
9
+ var _chunkR5U7XKVJjs = require('./chunk-R5U7XKVJ.js');
10
+
11
+ // src/completion.ts
12
+ var completion_exports = {};
13
+ _chunkR5U7XKVJjs.__export.call(void 0, completion_exports, {
14
+ NO_DESC_REQUEST_CMD: () => NO_DESC_REQUEST_CMD,
15
+ REQUEST_CMD: () => REQUEST_CMD,
16
+ SHELLS: () => SHELLS,
17
+ bindArgs: () => bindArgs,
18
+ bindFlag: () => bindFlag,
19
+ completeRequest: () => completeRequest,
20
+ completionCommand: () => completionCommand,
21
+ generateBashCompletion: () => generateBashCompletion,
22
+ generateFishCompletion: () => generateFishCompletion,
23
+ generatePowerShellCompletion: () => generatePowerShellCompletion,
24
+ generateZshCompletion: () => generateZshCompletion,
25
+ installCompletionRequest: () => installCompletionRequest,
26
+ registerRootAlias: () => registerRootAlias,
27
+ renderCompletionScript: () => renderCompletionScript
28
+ });
29
+ var _fs = require('fs');
30
+ var _commander = require('commander');
31
+
32
+ // src/completion-scripts.ts
33
+ var SCRIPT_TEMPLATES = {
34
+ bash: '# bash completion V2 for @@NAME_PAD36@@ -*- shell-script -*-\n\n__@@NAME@@_debug()\n{\n if [[ -n ${BASH_COMP_DEBUG_FILE-} ]]; then\n echo "$*" >> "${BASH_COMP_DEBUG_FILE}"\n fi\n}\n\n# Macs have bash3 for which the bash-completion package doesn\'t include\n# _init_completion. This is a minimal version of that function.\n__@@NAME@@_init_completion()\n{\n COMPREPLY=()\n _get_comp_words_by_ref "$@" cur prev words cword\n}\n\n# This function calls the @@NAME@@ program to obtain the completion\n# results and the directive. It fills the \'out\' and \'directive\' vars.\n__@@NAME@@_get_completion_results() {\n local requestComp lastParam lastChar args\n\n # Prepare the command to request completions for the program.\n # Calling ${words[0]} instead of directly @@NAME@@ allows handling aliases\n args=("${words[@]:1}")\n requestComp="${words[0]} @@COMP_CMD@@ ${args[*]}"\n\n lastParam=${words[$((${#words[@]}-1))]}\n lastChar=${lastParam:$((${#lastParam}-1)):1}\n __@@NAME@@_debug "lastParam ${lastParam}, lastChar ${lastChar}"\n\n if [[ -z ${cur} && ${lastChar} != = ]]; then\n # If the last parameter is complete (there is a space following it)\n # We add an extra empty parameter so we can indicate this to the go method.\n __@@NAME@@_debug "Adding extra empty parameter"\n requestComp="${requestComp} \'\'"\n fi\n\n # When completing a flag with an = (e.g., @@NAME@@ -n=<TAB>)\n # bash focuses on the part after the =, so we need to remove\n # the flag part from $cur\n if [[ ${cur} == -*=* ]]; then\n cur="${cur#*=}"\n fi\n\n __@@NAME@@_debug "Calling ${requestComp}"\n # Use eval to handle any environment variables and such\n out=$(eval "${requestComp}" 2>/dev/null)\n\n # Extract the directive integer at the very end of the output following a colon (:)\n directive=${out##*:}\n # Remove the directive\n out=${out%:*}\n if [[ ${directive} == "${out}" ]]; then\n # There is not directive specified\n directive=0\n fi\n __@@NAME@@_debug "The completion directive is: ${directive}"\n __@@NAME@@_debug "The completions are: ${out}"\n}\n\n__@@NAME@@_process_completion_results() {\n local shellCompDirectiveError=1\n local shellCompDirectiveNoSpace=2\n local shellCompDirectiveNoFileComp=4\n local shellCompDirectiveFilterFileExt=8\n local shellCompDirectiveFilterDirs=16\n local shellCompDirectiveKeepOrder=32\n\n if (((directive & shellCompDirectiveError) != 0)); then\n # Error code. No completion.\n __@@NAME@@_debug "Received error from custom completion go code"\n return\n else\n if (((directive & shellCompDirectiveNoSpace) != 0)); then\n if [[ $(type -t compopt) == builtin ]]; then\n __@@NAME@@_debug "Activating no space"\n compopt -o nospace\n else\n __@@NAME@@_debug "No space directive not supported in this version of bash"\n fi\n fi\n if (((directive & shellCompDirectiveKeepOrder) != 0)); then\n if [[ $(type -t compopt) == builtin ]]; then\n # no sort isn\'t supported for bash less than < 4.4\n if [[ ${BASH_VERSINFO[0]} -lt 4 || ( ${BASH_VERSINFO[0]} -eq 4 && ${BASH_VERSINFO[1]} -lt 4 ) ]]; then\n __@@NAME@@_debug "No sort directive not supported in this version of bash"\n else\n __@@NAME@@_debug "Activating keep order"\n compopt -o nosort\n fi\n else\n __@@NAME@@_debug "No sort directive not supported in this version of bash"\n fi\n fi\n if (((directive & shellCompDirectiveNoFileComp) != 0)); then\n if [[ $(type -t compopt) == builtin ]]; then\n __@@NAME@@_debug "Activating no file completion"\n compopt +o default\n else\n __@@NAME@@_debug "No file completion directive not supported in this version of bash"\n fi\n fi\n fi\n\n # Separate activeHelp from normal completions\n local completions=()\n local activeHelp=()\n __@@NAME@@_extract_activeHelp\n\n if (((directive & shellCompDirectiveFilterFileExt) != 0)); then\n # File extension filtering\n local fullFilter="" filter filteringCmd\n\n # Do not use quotes around the $completions variable or else newline\n # characters will be kept.\n for filter in ${completions[*]}; do\n fullFilter+="$filter|"\n done\n\n filteringCmd="_filedir $fullFilter"\n __@@NAME@@_debug "File filtering command: $filteringCmd"\n $filteringCmd\n elif (((directive & shellCompDirectiveFilterDirs) != 0)); then\n # File completion for directories only\n\n local subdir\n subdir=${completions[0]}\n if [[ -n $subdir ]]; then\n __@@NAME@@_debug "Listing directories in $subdir"\n pushd "$subdir" >/dev/null 2>&1 && _filedir -d && popd >/dev/null 2>&1 || return\n else\n __@@NAME@@_debug "Listing directories in ."\n _filedir -d\n fi\n else\n __@@NAME@@_handle_completion_types\n fi\n\n __@@NAME@@_handle_special_char "$cur" :\n __@@NAME@@_handle_special_char "$cur" =\n\n # Print the activeHelp statements before we finish\n __@@NAME@@_handle_activeHelp\n}\n\n__@@NAME@@_handle_activeHelp() {\n # Print the activeHelp statements\n if ((${#activeHelp[*]} != 0)); then\n if [ -z $COMP_TYPE ]; then\n # Bash v3 does not set the COMP_TYPE variable.\n printf "\\n";\n printf "%s\\n" "${activeHelp[@]}"\n printf "\\n"\n __@@NAME@@_reprint_commandLine\n return\n fi\n\n # Only print ActiveHelp on the second TAB press\n if [ $COMP_TYPE -eq 63 ]; then\n printf "\\n"\n printf "%s\\n" "${activeHelp[@]}"\n\n if ((${#COMPREPLY[*]} == 0)); then\n # When there are no completion choices from the program, file completion\n # may kick in if the program has not disabled it; in such a case, we want\n # to know if any files will match what the user typed, so that we know if\n # there will be completions presented, so that we know how to handle ActiveHelp.\n # To find out, we actually trigger the file completion ourselves;\n # the call to _filedir will fill COMPREPLY if files match.\n if (((directive & shellCompDirectiveNoFileComp) == 0)); then\n __@@NAME@@_debug "Listing files"\n _filedir\n fi\n fi\n\n if ((${#COMPREPLY[*]} != 0)); then\n # If there are completion choices to be shown, print a delimiter.\n # Re-printing the command-line will automatically be done\n # by the shell when it prints the completion choices.\n printf -- "--"\n else\n # When there are no completion choices at all, we need\n # to re-print the command-line since the shell will\n # not be doing it itself.\n __@@NAME@@_reprint_commandLine\n fi\n elif [ $COMP_TYPE -eq 37 ] || [ $COMP_TYPE -eq 42 ]; then\n # For completion type: menu-complete/menu-complete-backward and insert-completions\n # the completions are immediately inserted into the command-line, so we first\n # print the activeHelp message and reprint the command-line since the shell won\'t.\n printf "\\n"\n printf "%s\\n" "${activeHelp[@]}"\n\n __@@NAME@@_reprint_commandLine\n fi\n fi\n}\n\n__@@NAME@@_reprint_commandLine() {\n # The prompt format is only available from bash 4.4.\n # We test if it is available before using it.\n if (x=${PS1@P}) 2> /dev/null; then\n printf "%s" "${PS1@P}${COMP_LINE[@]}"\n else\n # Can\'t print the prompt. Just print the\n # text the user had typed, it is workable enough.\n printf "%s" "${COMP_LINE[@]}"\n fi\n}\n\n# Separate activeHelp lines from real completions.\n# Fills the $activeHelp and $completions arrays.\n__@@NAME@@_extract_activeHelp() {\n local activeHelpMarker="_activeHelp_ "\n local endIndex=${#activeHelpMarker}\n\n while IFS=\'\' read -r comp; do\n [[ -z $comp ]] && continue\n\n if [[ ${comp:0:endIndex} == $activeHelpMarker ]]; then\n comp=${comp:endIndex}\n __@@NAME@@_debug "ActiveHelp found: $comp"\n if [[ -n $comp ]]; then\n activeHelp+=("$comp")\n fi\n else\n # Not an activeHelp line but a normal completion\n completions+=("$comp")\n fi\n done <<<"${out}"\n}\n\n__@@NAME@@_handle_completion_types() {\n __@@NAME@@_debug "__@@NAME@@_handle_completion_types: COMP_TYPE is $COMP_TYPE"\n\n case $COMP_TYPE in\n 37|42)\n # Type: menu-complete/menu-complete-backward and insert-completions\n # If the user requested inserting one completion at a time, or all\n # completions at once on the command-line we must remove the descriptions.\n # https://github.com/spf13/cobra/issues/1508\n\n # If there are no completions, we don\'t need to do anything\n (( ${#completions[@]} == 0 )) && return 0\n\n local tab=$\'\\t\'\n\n # Strip any description and escape the completion to handled special characters\n IFS=$\'\\n\' read -ra completions -d \'\' < <(printf "%q\\n" "${completions[@]%%$tab*}")\n\n # Only consider the completions that match\n IFS=$\'\\n\' read -ra COMPREPLY -d \'\' < <(IFS=$\'\\n\'; compgen -W "${completions[*]}" -- "${cur}")\n\n # compgen looses the escaping so we need to escape all completions again since they will\n # all be inserted on the command-line.\n IFS=$\'\\n\' read -ra COMPREPLY -d \'\' < <(printf "%q\\n" "${COMPREPLY[@]}")\n ;;\n\n *)\n # Type: complete (normal completion)\n __@@NAME@@_handle_standard_completion_case\n ;;\n esac\n}\n\n__@@NAME@@_handle_standard_completion_case() {\n local tab=$\'\\t\'\n\n # If there are no completions, we don\'t need to do anything\n (( ${#completions[@]} == 0 )) && return 0\n\n # Short circuit to optimize if we don\'t have descriptions\n if [[ "${completions[*]}" != *$tab* ]]; then\n # First, escape the completions to handle special characters\n IFS=$\'\\n\' read -ra completions -d \'\' < <(printf "%q\\n" "${completions[@]}")\n # Only consider the completions that match what the user typed\n IFS=$\'\\n\' read -ra COMPREPLY -d \'\' < <(IFS=$\'\\n\'; compgen -W "${completions[*]}" -- "${cur}")\n\n # compgen looses the escaping so, if there is only a single completion, we need to\n # escape it again because it will be inserted on the command-line. If there are multiple\n # completions, we don\'t want to escape them because they will be printed in a list\n # and we don\'t want to show escape characters in that list.\n if (( ${#COMPREPLY[@]} == 1 )); then\n COMPREPLY[0]=$(printf "%q" "${COMPREPLY[0]}")\n fi\n return 0\n fi\n\n local longest=0\n local compline\n # Look for the longest completion so that we can format things nicely\n while IFS=\'\' read -r compline; do\n [[ -z $compline ]] && continue\n\n # Before checking if the completion matches what the user typed,\n # we need to strip any description and escape the completion to handle special\n # characters because those escape characters are part of what the user typed.\n # Don\'t call "printf" in a sub-shell because it will be much slower\n # since we are in a loop.\n printf -v comp "%q" "${compline%%$tab*}" &>/dev/null || comp=$(printf "%q" "${compline%%$tab*}")\n\n # Only consider the completions that match\n [[ $comp == "$cur"* ]] || continue\n\n # The completions matches. Add it to the list of full completions including\n # its description. We don\'t escape the completion because it may get printed\n # in a list if there are more than one and we don\'t want show escape characters\n # in that list.\n COMPREPLY+=("$compline")\n\n # Strip any description before checking the length, and again, don\'t escape\n # the completion because this length is only used when printing the completions\n # in a list and we don\'t want show escape characters in that list.\n comp=${compline%%$tab*}\n if ((${#comp}>longest)); then\n longest=${#comp}\n fi\n done < <(printf "%s\\n" "${completions[@]}")\n\n # If there is a single completion left, remove the description text and escape any special characters\n if ((${#COMPREPLY[*]} == 1)); then\n __@@NAME@@_debug "COMPREPLY[0]: ${COMPREPLY[0]}"\n COMPREPLY[0]=$(printf "%q" "${COMPREPLY[0]%%$tab*}")\n __@@NAME@@_debug "Removed description from single completion, which is now: ${COMPREPLY[0]}"\n else\n # Format the descriptions\n __@@NAME@@_format_comp_descriptions $longest\n fi\n}\n\n__@@NAME@@_handle_special_char()\n{\n local comp="$1"\n local char=$2\n if [[ "$comp" == *${char}* && "$COMP_WORDBREAKS" == *${char}* ]]; then\n local word=${comp%"${comp##*${char}}"}\n local idx=${#COMPREPLY[*]}\n while ((--idx >= 0)); do\n COMPREPLY[idx]=${COMPREPLY[idx]#"$word"}\n done\n fi\n}\n\n__@@NAME@@_format_comp_descriptions()\n{\n local tab=$\'\\t\'\n local comp desc maxdesclength\n local longest=$1\n\n local i ci\n for ci in ${!COMPREPLY[*]}; do\n comp=${COMPREPLY[ci]}\n # Properly format the description string which follows a tab character if there is one\n if [[ "$comp" == *$tab* ]]; then\n __@@NAME@@_debug "Original comp: $comp"\n desc=${comp#*$tab}\n comp=${comp%%$tab*}\n\n # $COLUMNS stores the current shell width.\n # Remove an extra 4 because we add 2 spaces and 2 parentheses.\n maxdesclength=$(( COLUMNS - longest - 4 ))\n\n # Make sure we can fit a description of at least 8 characters\n # if we are to align the descriptions.\n if ((maxdesclength > 8)); then\n # Add the proper number of spaces to align the descriptions\n for ((i = ${#comp} ; i < longest ; i++)); do\n comp+=" "\n done\n else\n # Don\'t pad the descriptions so we can fit more text after the completion\n maxdesclength=$(( COLUMNS - ${#comp} - 4 ))\n fi\n\n # If there is enough space for any description text,\n # truncate the descriptions that are too long for the shell width\n if ((maxdesclength > 0)); then\n if ((${#desc} > maxdesclength)); then\n desc=${desc:0:$(( maxdesclength - 1 ))}\n desc+="\u2026"\n fi\n comp+=" ($desc)"\n fi\n COMPREPLY[ci]=$comp\n __@@NAME@@_debug "Final comp: $comp"\n fi\n done\n}\n\n__start_@@NAME@@()\n{\n local cur prev words cword split\n\n COMPREPLY=()\n\n # Call _init_completion from the bash-completion package\n # to prepare the arguments properly\n if declare -F _init_completion >/dev/null 2>&1; then\n _init_completion -n =: || return\n else\n __@@NAME@@_init_completion -n =: || return\n fi\n\n __@@NAME@@_debug\n __@@NAME@@_debug "========= starting completion logic =========="\n __@@NAME@@_debug "cur is ${cur}, words[*] is ${words[*]}, #words[@] is ${#words[@]}, cword is $cword"\n\n # The user could have moved the cursor backwards on the command-line.\n # We need to trigger completion from the $cword location, so we need\n # to truncate the command-line ($words) up to the $cword location.\n words=("${words[@]:0:$cword+1}")\n __@@NAME@@_debug "Truncated words[*]: ${words[*]},"\n\n local out directive\n __@@NAME@@_get_completion_results\n __@@NAME@@_process_completion_results\n}\n\nif [[ $(type -t compopt) = "builtin" ]]; then\n complete -o default -F __start_@@NAME@@ @@NAME@@\nelse\n complete -o default -o nospace -F __start_@@NAME@@ @@NAME@@\nfi\n\n# ex: ts=4 sw=4 et filetype=sh\n',
35
+ zsh: '#compdef @@NAME@@\ncompdef _@@NAME@@ @@NAME@@\n\n# zsh completion for @@NAME_PAD36@@ -*- shell-script -*-\n\n__@@NAME@@_debug()\n{\n local file="$BASH_COMP_DEBUG_FILE"\n if [[ -n ${file} ]]; then\n echo "$*" >> "${file}"\n fi\n}\n\n_@@NAME@@()\n{\n local shellCompDirectiveError=1\n local shellCompDirectiveNoSpace=2\n local shellCompDirectiveNoFileComp=4\n local shellCompDirectiveFilterFileExt=8\n local shellCompDirectiveFilterDirs=16\n local shellCompDirectiveKeepOrder=32\n\n local lastParam lastChar flagPrefix requestComp out directive comp lastComp noSpace keepOrder\n local -a completions\n\n __@@NAME@@_debug "\\n========= starting completion logic =========="\n __@@NAME@@_debug "CURRENT: ${CURRENT}, words[*]: ${words[*]}"\n\n # The user could have moved the cursor backwards on the command-line.\n # We need to trigger completion from the $CURRENT location, so we need\n # to truncate the command-line ($words) up to the $CURRENT location.\n # (We cannot use $CURSOR as its value does not work when a command is an alias.)\n words=("${=words[1,CURRENT]}")\n __@@NAME@@_debug "Truncated words[*]: ${words[*]},"\n\n lastParam=${words[-1]}\n lastChar=${lastParam[-1]}\n __@@NAME@@_debug "lastParam: ${lastParam}, lastChar: ${lastChar}"\n\n # For zsh, when completing a flag with an = (e.g., @@NAME@@ -n=<TAB>)\n # completions must be prefixed with the flag\n setopt local_options BASH_REMATCH\n if [[ "${lastParam}" =~ \'-.*=\' ]]; then\n # We are dealing with a flag with an =\n flagPrefix="-P ${BASH_REMATCH}"\n fi\n\n # Prepare the command to obtain completions\n requestComp="${words[1]} @@COMP_CMD@@ ${words[2,-1]}"\n if [ "${lastChar}" = "" ]; then\n # If the last parameter is complete (there is a space following it)\n # We add an extra empty parameter so we can indicate this to the go completion code.\n __@@NAME@@_debug "Adding extra empty parameter"\n requestComp="${requestComp} \\"\\""\n fi\n\n __@@NAME@@_debug "About to call: eval ${requestComp}"\n\n # Use eval to handle any environment variables and such\n out=$(eval ${requestComp} 2>/dev/null)\n __@@NAME@@_debug "completion output: ${out}"\n\n # Extract the directive integer following a : from the last line\n local lastLine\n while IFS=\'\\n\' read -r line; do\n lastLine=${line}\n done < <(printf "%s\\n" "${out[@]}")\n __@@NAME@@_debug "last line: ${lastLine}"\n\n if [ "${lastLine[1]}" = : ]; then\n directive=${lastLine[2,-1]}\n # Remove the directive including the : and the newline\n local suffix\n (( suffix=${#lastLine}+2))\n out=${out[1,-$suffix]}\n else\n # There is no directive specified. Leave $out as is.\n __@@NAME@@_debug "No directive found. Setting do default"\n directive=0\n fi\n\n __@@NAME@@_debug "directive: ${directive}"\n __@@NAME@@_debug "completions: ${out}"\n __@@NAME@@_debug "flagPrefix: ${flagPrefix}"\n\n if [ $((directive & shellCompDirectiveError)) -ne 0 ]; then\n __@@NAME@@_debug "Completion received error. Ignoring completions."\n return\n fi\n\n local activeHelpMarker="_activeHelp_ "\n local endIndex=${#activeHelpMarker}\n local startIndex=$((${#activeHelpMarker}+1))\n local hasActiveHelp=0\n while IFS=\'\\n\' read -r comp; do\n # Check if this is an activeHelp statement (i.e., prefixed with $activeHelpMarker)\n if [ "${comp[1,$endIndex]}" = "$activeHelpMarker" ];then\n __@@NAME@@_debug "ActiveHelp found: $comp"\n comp="${comp[$startIndex,-1]}"\n if [ -n "$comp" ]; then\n compadd -x "${comp}"\n __@@NAME@@_debug "ActiveHelp will need delimiter"\n hasActiveHelp=1\n fi\n\n continue\n fi\n\n if [ -n "$comp" ]; then\n # If requested, completions are returned with a description.\n # The description is preceded by a TAB character.\n # For zsh\'s _describe, we need to use a : instead of a TAB.\n # We first need to escape any : as part of the completion itself.\n comp=${comp//:/\\\\:}\n\n local tab="$(printf \'\\t\')"\n comp=${comp//$tab/:}\n\n __@@NAME@@_debug "Adding completion: ${comp}"\n completions+=${comp}\n lastComp=$comp\n fi\n done < <(printf "%s\\n" "${out[@]}")\n\n # Add a delimiter after the activeHelp statements, but only if:\n # - there are completions following the activeHelp statements, or\n # - file completion will be performed (so there will be choices after the activeHelp)\n if [ $hasActiveHelp -eq 1 ]; then\n if [ ${#completions} -ne 0 ] || [ $((directive & shellCompDirectiveNoFileComp)) -eq 0 ]; then\n __@@NAME@@_debug "Adding activeHelp delimiter"\n compadd -x "--"\n hasActiveHelp=0\n fi\n fi\n\n if [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ]; then\n __@@NAME@@_debug "Activating nospace."\n noSpace="-S \'\'"\n fi\n\n if [ $((directive & shellCompDirectiveKeepOrder)) -ne 0 ]; then\n __@@NAME@@_debug "Activating keep order."\n keepOrder="-V"\n fi\n\n if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then\n # File extension filtering\n local filteringCmd\n filteringCmd=\'_files\'\n for filter in ${completions[@]}; do\n if [ ${filter[1]} != \'*\' ]; then\n # zsh requires a glob pattern to do file filtering\n filter="\\*.$filter"\n fi\n filteringCmd+=" -g $filter"\n done\n filteringCmd+=" ${flagPrefix}"\n\n __@@NAME@@_debug "File filtering command: $filteringCmd"\n _arguments \'*:filename:\'"$filteringCmd"\n elif [ $((directive & shellCompDirectiveFilterDirs)) -ne 0 ]; then\n # File completion for directories only\n local subdir\n subdir="${completions[1]}"\n if [ -n "$subdir" ]; then\n __@@NAME@@_debug "Listing directories in $subdir"\n pushd "${subdir}" >/dev/null 2>&1\n else\n __@@NAME@@_debug "Listing directories in ."\n fi\n\n local result\n _arguments \'*:dirname:_files -/\'" ${flagPrefix}"\n result=$?\n if [ -n "$subdir" ]; then\n popd >/dev/null 2>&1\n fi\n return $result\n else\n __@@NAME@@_debug "Calling _describe"\n if eval _describe $keepOrder "completions" completions $flagPrefix $noSpace; then\n __@@NAME@@_debug "_describe found some completions"\n\n # Return the success of having called _describe\n return 0\n else\n __@@NAME@@_debug "_describe did not find completions."\n __@@NAME@@_debug "Checking if we should do file completion."\n if [ $((directive & shellCompDirectiveNoFileComp)) -ne 0 ]; then\n __@@NAME@@_debug "deactivating file completion"\n\n # We must return an error code here to let zsh know that there were no\n # completions found by _describe; this is what will trigger other\n # matching algorithms to attempt to find completions.\n # For example zsh can match letters in the middle of words.\n return 1\n else\n # Perform file completion\n __@@NAME@@_debug "Activating file completion"\n\n # We must return the result of this command, so it must be the\n # last command, or else we must store its result to return it.\n _arguments \'*:filename:_files\'" ${flagPrefix}"\n fi\n fi\n fi\n}\n\n# don\'t run the completion function when being source-ed or eval-ed\nif [ "$funcstack[1]" = "_@@NAME@@" ]; then\n _@@NAME@@\nfi\n',
36
+ fish: `# fish completion for @@NAME_PAD36@@ -*- shell-script -*-
37
+
38
+ function __@@NAME_VAR@@_debug
39
+ set -l file "$BASH_COMP_DEBUG_FILE"
40
+ if test -n "$file"
41
+ echo "$argv" >> $file
42
+ end
43
+ end
44
+
45
+ function __@@NAME_VAR@@_perform_completion
46
+ __@@NAME_VAR@@_debug "Starting __@@NAME_VAR@@_perform_completion"
47
+
48
+ # Extract all args except the last one
49
+ set -l args (commandline -opc)
50
+ # Extract the last arg and escape it in case it is a space
51
+ set -l lastArg (string escape -- (commandline -ct))
52
+
53
+ __@@NAME_VAR@@_debug "args: $args"
54
+ __@@NAME_VAR@@_debug "last arg: $lastArg"
55
+
56
+ # Disable ActiveHelp which is not supported for fish shell
57
+ set -l requestComp "@@ACTIVE_HELP_VAR@@=0 $args[1] @@COMP_CMD@@ $args[2..-1] $lastArg"
58
+
59
+ __@@NAME_VAR@@_debug "Calling $requestComp"
60
+ set -l results (eval $requestComp 2> /dev/null)
61
+
62
+ # Some programs may output extra empty lines after the directive.
63
+ # Let's ignore them or else it will break completion.
64
+ # Ref: https://github.com/spf13/cobra/issues/1279
65
+ for line in $results[-1..1]
66
+ if test (string trim -- $line) = ""
67
+ # Found an empty line, remove it
68
+ set results $results[1..-2]
69
+ else
70
+ # Found non-empty line, we have our proper output
71
+ break
72
+ end
73
+ end
74
+
75
+ set -l comps $results[1..-2]
76
+ set -l directiveLine $results[-1]
77
+
78
+ # For Fish, when completing a flag with an = (e.g., <program> -n=<TAB>)
79
+ # completions must be prefixed with the flag
80
+ set -l flagPrefix (string match -r -- '-.*=' "$lastArg")
81
+
82
+ __@@NAME_VAR@@_debug "Comps: $comps"
83
+ __@@NAME_VAR@@_debug "DirectiveLine: $directiveLine"
84
+ __@@NAME_VAR@@_debug "flagPrefix: $flagPrefix"
85
+
86
+ for comp in $comps
87
+ printf "%s%s\\n" "$flagPrefix" "$comp"
88
+ end
89
+
90
+ printf "%s\\n" "$directiveLine"
91
+ end
92
+
93
+ # this function limits calls to __@@NAME_VAR@@_perform_completion, by caching the result behind $__@@NAME_VAR@@_perform_completion_once_result
94
+ function __@@NAME_VAR@@_perform_completion_once
95
+ __@@NAME_VAR@@_debug "Starting __@@NAME_VAR@@_perform_completion_once"
96
+
97
+ if test -n "$__@@NAME_VAR@@_perform_completion_once_result"
98
+ __@@NAME_VAR@@_debug "Seems like a valid result already exists, skipping __@@NAME_VAR@@_perform_completion"
99
+ return 0
100
+ end
101
+
102
+ set --global __@@NAME_VAR@@_perform_completion_once_result (__@@NAME_VAR@@_perform_completion)
103
+ if test -z "$__@@NAME_VAR@@_perform_completion_once_result"
104
+ __@@NAME_VAR@@_debug "No completions, probably due to a failure"
105
+ return 1
106
+ end
107
+
108
+ __@@NAME_VAR@@_debug "Performed completions and set __@@NAME_VAR@@_perform_completion_once_result"
109
+ return 0
110
+ end
111
+
112
+ # this function is used to clear the $__@@NAME_VAR@@_perform_completion_once_result variable after completions are run
113
+ function __@@NAME_VAR@@_clear_perform_completion_once_result
114
+ __@@NAME_VAR@@_debug ""
115
+ __@@NAME_VAR@@_debug "========= clearing previously set __@@NAME_VAR@@_perform_completion_once_result variable =========="
116
+ set --erase __@@NAME_VAR@@_perform_completion_once_result
117
+ __@@NAME_VAR@@_debug "Successfully erased the variable __@@NAME_VAR@@_perform_completion_once_result"
118
+ end
119
+
120
+ function __@@NAME_VAR@@_requires_order_preservation
121
+ __@@NAME_VAR@@_debug ""
122
+ __@@NAME_VAR@@_debug "========= checking if order preservation is required =========="
123
+
124
+ __@@NAME_VAR@@_perform_completion_once
125
+ if test -z "$__@@NAME_VAR@@_perform_completion_once_result"
126
+ __@@NAME_VAR@@_debug "Error determining if order preservation is required"
127
+ return 1
128
+ end
129
+
130
+ set -l directive (string sub --start 2 $__@@NAME_VAR@@_perform_completion_once_result[-1])
131
+ __@@NAME_VAR@@_debug "Directive is: $directive"
132
+
133
+ set -l shellCompDirectiveKeepOrder 32
134
+ set -l keeporder (math (math --scale 0 $directive / $shellCompDirectiveKeepOrder) % 2)
135
+ __@@NAME_VAR@@_debug "Keeporder is: $keeporder"
136
+
137
+ if test $keeporder -ne 0
138
+ __@@NAME_VAR@@_debug "This does require order preservation"
139
+ return 0
140
+ end
141
+
142
+ __@@NAME_VAR@@_debug "This doesn't require order preservation"
143
+ return 1
144
+ end
145
+
146
+
147
+ # This function does two things:
148
+ # - Obtain the completions and store them in the global __@@NAME_VAR@@_comp_results
149
+ # - Return false if file completion should be performed
150
+ function __@@NAME_VAR@@_prepare_completions
151
+ __@@NAME_VAR@@_debug ""
152
+ __@@NAME_VAR@@_debug "========= starting completion logic =========="
153
+
154
+ # Start fresh
155
+ set --erase __@@NAME_VAR@@_comp_results
156
+
157
+ __@@NAME_VAR@@_perform_completion_once
158
+ __@@NAME_VAR@@_debug "Completion results: $__@@NAME_VAR@@_perform_completion_once_result"
159
+
160
+ if test -z "$__@@NAME_VAR@@_perform_completion_once_result"
161
+ __@@NAME_VAR@@_debug "No completion, probably due to a failure"
162
+ # Might as well do file completion, in case it helps
163
+ return 1
164
+ end
165
+
166
+ set -l directive (string sub --start 2 $__@@NAME_VAR@@_perform_completion_once_result[-1])
167
+ set --global __@@NAME_VAR@@_comp_results $__@@NAME_VAR@@_perform_completion_once_result[1..-2]
168
+
169
+ __@@NAME_VAR@@_debug "Completions are: $__@@NAME_VAR@@_comp_results"
170
+ __@@NAME_VAR@@_debug "Directive is: $directive"
171
+
172
+ set -l shellCompDirectiveError 1
173
+ set -l shellCompDirectiveNoSpace 2
174
+ set -l shellCompDirectiveNoFileComp 4
175
+ set -l shellCompDirectiveFilterFileExt 8
176
+ set -l shellCompDirectiveFilterDirs 16
177
+
178
+ if test -z "$directive"
179
+ set directive 0
180
+ end
181
+
182
+ set -l compErr (math (math --scale 0 $directive / $shellCompDirectiveError) % 2)
183
+ if test $compErr -eq 1
184
+ __@@NAME_VAR@@_debug "Received error directive: aborting."
185
+ # Might as well do file completion, in case it helps
186
+ return 1
187
+ end
188
+
189
+ set -l filefilter (math (math --scale 0 $directive / $shellCompDirectiveFilterFileExt) % 2)
190
+ set -l dirfilter (math (math --scale 0 $directive / $shellCompDirectiveFilterDirs) % 2)
191
+ if test $filefilter -eq 1; or test $dirfilter -eq 1
192
+ __@@NAME_VAR@@_debug "File extension filtering or directory filtering not supported"
193
+ # Do full file completion instead
194
+ return 1
195
+ end
196
+
197
+ set -l nospace (math (math --scale 0 $directive / $shellCompDirectiveNoSpace) % 2)
198
+ set -l nofiles (math (math --scale 0 $directive / $shellCompDirectiveNoFileComp) % 2)
199
+
200
+ __@@NAME_VAR@@_debug "nospace: $nospace, nofiles: $nofiles"
201
+
202
+ # If we want to prevent a space, or if file completion is NOT disabled,
203
+ # we need to count the number of valid completions.
204
+ # To do so, we will filter on prefix as the completions we have received
205
+ # may not already be filtered so as to allow fish to match on different
206
+ # criteria than the prefix.
207
+ if test $nospace -ne 0; or test $nofiles -eq 0
208
+ set -l prefix (commandline -t | string escape --style=regex)
209
+ __@@NAME_VAR@@_debug "prefix: $prefix"
210
+
211
+ set -l completions (string match -r -- "^$prefix.*" $__@@NAME_VAR@@_comp_results)
212
+ set --global __@@NAME_VAR@@_comp_results $completions
213
+ __@@NAME_VAR@@_debug "Filtered completions are: $__@@NAME_VAR@@_comp_results"
214
+
215
+ # Important not to quote the variable for count to work
216
+ set -l numComps (count $__@@NAME_VAR@@_comp_results)
217
+ __@@NAME_VAR@@_debug "numComps: $numComps"
218
+
219
+ if test $numComps -eq 1; and test $nospace -ne 0
220
+ # We must first split on \\t to get rid of the descriptions to be
221
+ # able to check what the actual completion will be.
222
+ # We don't need descriptions anyway since there is only a single
223
+ # real completion which the shell will expand immediately.
224
+ set -l split (string split --max 1 \\t $__@@NAME_VAR@@_comp_results[1])
225
+
226
+ # Fish won't add a space if the completion ends with any
227
+ # of the following characters: @=/:.,
228
+ set -l lastChar (string sub -s -1 -- $split)
229
+ if not string match -r -q "[@=/:.,]" -- "$lastChar"
230
+ # In other cases, to support the "nospace" directive we trick the shell
231
+ # by outputting an extra, longer completion.
232
+ __@@NAME_VAR@@_debug "Adding second completion to perform nospace directive"
233
+ set --global __@@NAME_VAR@@_comp_results $split[1] $split[1].
234
+ __@@NAME_VAR@@_debug "Completions are now: $__@@NAME_VAR@@_comp_results"
235
+ end
236
+ end
237
+
238
+ if test $numComps -eq 0; and test $nofiles -eq 0
239
+ # To be consistent with bash and zsh, we only trigger file
240
+ # completion when there are no other completions
241
+ __@@NAME_VAR@@_debug "Requesting file completion"
242
+ return 1
243
+ end
244
+ end
245
+
246
+ return 0
247
+ end
248
+
249
+ # Since Fish completions are only loaded once the user triggers them, we trigger them ourselves
250
+ # so we can properly delete any completions provided by another script.
251
+ # Only do this if the program can be found, or else fish may print some errors; besides,
252
+ # the existing completions will only be loaded if the program can be found.
253
+ if type -q "@@NAME@@"
254
+ # The space after the program name is essential to trigger completion for the program
255
+ # and not completion of the program name itself.
256
+ # Also, we use '> /dev/null 2>&1' since '&>' is not supported in older versions of fish.
257
+ complete --do-complete "@@NAME@@ " > /dev/null 2>&1
258
+ end
259
+
260
+ # Remove any pre-existing completions for the program since we will be handling all of them.
261
+ complete -c @@NAME@@ -e
262
+
263
+ # this will get called after the two calls below and clear the $__@@NAME_VAR@@_perform_completion_once_result global
264
+ complete -c @@NAME@@ -n '__@@NAME_VAR@@_clear_perform_completion_once_result'
265
+ # The call to __@@NAME_VAR@@_prepare_completions will setup __@@NAME_VAR@@_comp_results
266
+ # which provides the program's completion choices.
267
+ # If this doesn't require order preservation, we don't use the -k flag
268
+ complete -c @@NAME@@ -n 'not __@@NAME_VAR@@_requires_order_preservation && __@@NAME_VAR@@_prepare_completions' -f -a '$__@@NAME_VAR@@_comp_results'
269
+ # otherwise we use the -k flag
270
+ complete -k -c @@NAME@@ -n '__@@NAME_VAR@@_requires_order_preservation && __@@NAME_VAR@@_prepare_completions' -f -a '$__@@NAME_VAR@@_comp_results'
271
+ `,
272
+ powershell: `# powershell completion for @@NAME_PAD36@@ -*- shell-script -*-
273
+
274
+ function __@@NAME@@_debug {
275
+ if ($env:BASH_COMP_DEBUG_FILE) {
276
+ "$args" | Out-File -Append -FilePath "$env:BASH_COMP_DEBUG_FILE"
277
+ }
278
+ }
279
+
280
+ filter __@@NAME@@_escapeStringWithSpecialChars {
281
+ $_ -replace '\\s|#|@|\\$|;|,|''|\\{|\\}|\\(|\\)|"|\`|\\||<|>|&','\`$&'
282
+ }
283
+
284
+ [scriptblock]\${__@@NAME_VAR@@CompleterBlock} = {
285
+ param(
286
+ $WordToComplete,
287
+ $CommandAst,
288
+ $CursorPosition
289
+ )
290
+
291
+ # Get the current command line and convert into a string
292
+ $Command = $CommandAst.CommandElements
293
+ $Command = "$Command"
294
+
295
+ __@@NAME@@_debug ""
296
+ __@@NAME@@_debug "========= starting completion logic =========="
297
+ __@@NAME@@_debug "WordToComplete: $WordToComplete Command: $Command CursorPosition: $CursorPosition"
298
+
299
+ # The user could have moved the cursor backwards on the command-line.
300
+ # We need to trigger completion from the $CursorPosition location, so we need
301
+ # to truncate the command-line ($Command) up to the $CursorPosition location.
302
+ # Make sure the $Command is longer then the $CursorPosition before we truncate.
303
+ # This happens because the $Command does not include the last space.
304
+ if ($Command.Length -gt $CursorPosition) {
305
+ $Command=$Command.Substring(0,$CursorPosition)
306
+ }
307
+ __@@NAME@@_debug "Truncated command: $Command"
308
+
309
+ $ShellCompDirectiveError=1
310
+ $ShellCompDirectiveNoSpace=2
311
+ $ShellCompDirectiveNoFileComp=4
312
+ $ShellCompDirectiveFilterFileExt=8
313
+ $ShellCompDirectiveFilterDirs=16
314
+ $ShellCompDirectiveKeepOrder=32
315
+
316
+ # Prepare the command to request completions for the program.
317
+ # Split the command at the first space to separate the program and arguments.
318
+ $Program,$Arguments = $Command.Split(" ",2)
319
+
320
+ $RequestComp="$Program @@COMP_CMD@@ $Arguments"
321
+ __@@NAME@@_debug "RequestComp: $RequestComp"
322
+
323
+ # we cannot use $WordToComplete because it
324
+ # has the wrong values if the cursor was moved
325
+ # so use the last argument
326
+ if ($WordToComplete -ne "" ) {
327
+ $WordToComplete = $Arguments.Split(" ")[-1]
328
+ }
329
+ __@@NAME@@_debug "New WordToComplete: $WordToComplete"
330
+
331
+
332
+ # Check for flag with equal sign
333
+ $IsEqualFlag = ($WordToComplete -Like "--*=*" )
334
+ if ( $IsEqualFlag ) {
335
+ __@@NAME@@_debug "Completing equal sign flag"
336
+ # Remove the flag part
337
+ $Flag,$WordToComplete = $WordToComplete.Split("=",2)
338
+ }
339
+
340
+ if ( $WordToComplete -eq "" -And ( -Not $IsEqualFlag )) {
341
+ # If the last parameter is complete (there is a space following it)
342
+ # We add an extra empty parameter so we can indicate this to the go method.
343
+ __@@NAME@@_debug "Adding extra empty parameter"
344
+ # PowerShell 7.2+ changed the way how the arguments are passed to executables,
345
+ # so for pre-7.2 or when Legacy argument passing is enabled we need to use
346
+ # \`"\`" to pass an empty argument, a "" or '' does not work!!!
347
+ if ($PSVersionTable.PsVersion -lt [version]'7.2.0' -or
348
+ ($PSVersionTable.PsVersion -lt [version]'7.3.0' -and -not [ExperimentalFeature]::IsEnabled("PSNativeCommandArgumentPassing")) -or
349
+ (($PSVersionTable.PsVersion -ge [version]'7.3.0' -or [ExperimentalFeature]::IsEnabled("PSNativeCommandArgumentPassing")) -and
350
+ $PSNativeCommandArgumentPassing -eq 'Legacy')) {
351
+ $RequestComp="$RequestComp" + ' \`"\`"'
352
+ } else {
353
+ $RequestComp="$RequestComp" + ' ""'
354
+ }
355
+ }
356
+
357
+ __@@NAME@@_debug "Calling $RequestComp"
358
+ # First disable ActiveHelp which is not supported for Powershell
359
+ \${env:@@ACTIVE_HELP_VAR@@}=0
360
+
361
+ #call the command store the output in $out and redirect stderr and stdout to null
362
+ # $Out is an array contains each line per element
363
+ Invoke-Expression -OutVariable out "$RequestComp" 2>&1 | Out-Null
364
+
365
+ # get directive from last line
366
+ [int]$Directive = $Out[-1].TrimStart(':')
367
+ if ($Directive -eq "") {
368
+ # There is no directive specified
369
+ $Directive = 0
370
+ }
371
+ __@@NAME@@_debug "The completion directive is: $Directive"
372
+
373
+ # remove directive (last element) from out
374
+ $Out = $Out | Where-Object { $_ -ne $Out[-1] }
375
+ __@@NAME@@_debug "The completions are: $Out"
376
+
377
+ if (($Directive -band $ShellCompDirectiveError) -ne 0 ) {
378
+ # Error code. No completion.
379
+ __@@NAME@@_debug "Received error from custom completion go code"
380
+ return
381
+ }
382
+
383
+ $Longest = 0
384
+ [Array]$Values = $Out | ForEach-Object {
385
+ #Split the output in name and description
386
+ $Name, $Description = $_.Split("\`t",2)
387
+ __@@NAME@@_debug "Name: $Name Description: $Description"
388
+
389
+ # Look for the longest completion so that we can format things nicely
390
+ if ($Longest -lt $Name.Length) {
391
+ $Longest = $Name.Length
392
+ }
393
+
394
+ # Set the description to a one space string if there is none set.
395
+ # This is needed because the CompletionResult does not accept an empty string as argument
396
+ if (-Not $Description) {
397
+ $Description = " "
398
+ }
399
+ New-Object -TypeName PSCustomObject -Property @{
400
+ Name = "$Name"
401
+ Description = "$Description"
402
+ }
403
+ }
404
+
405
+
406
+ $Space = " "
407
+ if (($Directive -band $ShellCompDirectiveNoSpace) -ne 0 ) {
408
+ # remove the space here
409
+ __@@NAME@@_debug "ShellCompDirectiveNoSpace is called"
410
+ $Space = ""
411
+ }
412
+
413
+ if ((($Directive -band $ShellCompDirectiveFilterFileExt) -ne 0 ) -or
414
+ (($Directive -band $ShellCompDirectiveFilterDirs) -ne 0 )) {
415
+ __@@NAME@@_debug "ShellCompDirectiveFilterFileExt ShellCompDirectiveFilterDirs are not supported"
416
+
417
+ # return here to prevent the completion of the extensions
418
+ return
419
+ }
420
+
421
+ $Values = $Values | Where-Object {
422
+ # filter the result
423
+ $_.Name -like "$WordToComplete*"
424
+
425
+ # Join the flag back if we have an equal sign flag
426
+ if ( $IsEqualFlag ) {
427
+ __@@NAME@@_debug "Join the equal sign flag back to the completion value"
428
+ $_.Name = $Flag + "=" + $_.Name
429
+ }
430
+ }
431
+
432
+ # we sort the values in ascending order by name if keep order isn't passed
433
+ if (($Directive -band $ShellCompDirectiveKeepOrder) -eq 0 ) {
434
+ $Values = $Values | Sort-Object -Property Name
435
+ }
436
+
437
+ if (($Directive -band $ShellCompDirectiveNoFileComp) -ne 0 ) {
438
+ __@@NAME@@_debug "ShellCompDirectiveNoFileComp is called"
439
+
440
+ if ($Values.Length -eq 0) {
441
+ # Just print an empty string here so the
442
+ # shell does not start to complete paths.
443
+ # We cannot use CompletionResult here because
444
+ # it does not accept an empty string as argument.
445
+ ""
446
+ return
447
+ }
448
+ }
449
+
450
+ # Get the current mode
451
+ $Mode = (Get-PSReadLineKeyHandler | Where-Object {$_.Key -eq "Tab" }).Function
452
+ __@@NAME@@_debug "Mode: $Mode"
453
+
454
+ $Values | ForEach-Object {
455
+
456
+ # store temporary because switch will overwrite $_
457
+ $comp = $_
458
+
459
+ # PowerShell supports three different completion modes
460
+ # - TabCompleteNext (default windows style - on each key press the next option is displayed)
461
+ # - Complete (works like bash)
462
+ # - MenuComplete (works like zsh)
463
+ # You set the mode with Set-PSReadLineKeyHandler -Key Tab -Function <mode>
464
+
465
+ # CompletionResult Arguments:
466
+ # 1) CompletionText text to be used as the auto completion result
467
+ # 2) ListItemText text to be displayed in the suggestion list
468
+ # 3) ResultType type of completion result
469
+ # 4) ToolTip text for the tooltip with details about the object
470
+
471
+ switch ($Mode) {
472
+
473
+ # bash like
474
+ "Complete" {
475
+
476
+ if ($Values.Length -eq 1) {
477
+ __@@NAME@@_debug "Only one completion left"
478
+
479
+ # insert space after value
480
+ $CompletionText = $($comp.Name | __@@NAME@@_escapeStringWithSpecialChars) + $Space
481
+ if ($ExecutionContext.SessionState.LanguageMode -eq "FullLanguage"){
482
+ [System.Management.Automation.CompletionResult]::new($CompletionText, "$($comp.Name)", 'ParameterValue', "$($comp.Description)")
483
+ } else {
484
+ $CompletionText
485
+ }
486
+
487
+ } else {
488
+ # Add the proper number of spaces to align the descriptions
489
+ while($comp.Name.Length -lt $Longest) {
490
+ $comp.Name = $comp.Name + " "
491
+ }
492
+
493
+ # Check for empty description and only add parentheses if needed
494
+ if ($($comp.Description) -eq " " ) {
495
+ $Description = ""
496
+ } else {
497
+ $Description = " ($($comp.Description))"
498
+ }
499
+
500
+ $CompletionText = "$($comp.Name)$Description"
501
+ if ($ExecutionContext.SessionState.LanguageMode -eq "FullLanguage"){
502
+ [System.Management.Automation.CompletionResult]::new($CompletionText, "$($comp.Name)$Description", 'ParameterValue', "$($comp.Description)")
503
+ } else {
504
+ $CompletionText
505
+ }
506
+ }
507
+ }
508
+
509
+ # zsh like
510
+ "MenuComplete" {
511
+ # insert space after value
512
+ # MenuComplete will automatically show the ToolTip of
513
+ # the highlighted value at the bottom of the suggestions.
514
+
515
+ $CompletionText = $($comp.Name | __@@NAME@@_escapeStringWithSpecialChars) + $Space
516
+ if ($ExecutionContext.SessionState.LanguageMode -eq "FullLanguage"){
517
+ [System.Management.Automation.CompletionResult]::new($CompletionText, "$($comp.Name)", 'ParameterValue', "$($comp.Description)")
518
+ } else {
519
+ $CompletionText
520
+ }
521
+ }
522
+
523
+ # TabCompleteNext and in case we get something unknown
524
+ Default {
525
+ # Like MenuComplete but we don't want to add a space here because
526
+ # the user need to press space anyway to get the completion.
527
+ # Description will not be shown because that's not possible with TabCompleteNext
528
+
529
+ $CompletionText = $($comp.Name | __@@NAME@@_escapeStringWithSpecialChars)
530
+ if ($ExecutionContext.SessionState.LanguageMode -eq "FullLanguage"){
531
+ [System.Management.Automation.CompletionResult]::new($CompletionText, "$($comp.Name)", 'ParameterValue', "$($comp.Description)")
532
+ } else {
533
+ $CompletionText
534
+ }
535
+ }
536
+ }
537
+
538
+ }
539
+ }
540
+
541
+ Register-ArgumentCompleter -CommandName '@@NAME@@' -ScriptBlock \${__@@NAME_VAR@@CompleterBlock}
542
+ `
543
+ };
544
+
545
+ // src/completion.ts
546
+ var REQUEST_CMD = "__complete";
547
+ var NO_DESC_REQUEST_CMD = "__completeNoDesc";
548
+ var SHELLS = ["bash", "zsh", "fish", "powershell"];
549
+ function internals(c) {
550
+ return c;
551
+ }
552
+ var FLAG_COMPLETERS = /* @__PURE__ */ Symbol.for("@hop-top/kit/completion/flags");
553
+ var ARGS_COMPLETER = /* @__PURE__ */ Symbol.for("@hop-top/kit/completion/args");
554
+ var ROOT_ALIASES = /* @__PURE__ */ Symbol.for("@hop-top/kit/completion/aliases");
555
+ var BUILTIN = /* @__PURE__ */ Symbol.for("@hop-top/kit/completion/builtin");
556
+ var INSTALLED = /* @__PURE__ */ Symbol.for("@hop-top/kit/completion/installed");
557
+ function configEnvVar(name, suffix) {
558
+ return `${name}_${suffix}`.toUpperCase().replace(/[^A-Z0-9_]/g, "_");
559
+ }
560
+ function renderCompletionScript(shell, name, includeDescriptions = true) {
561
+ const vars = {
562
+ NAME_PAD36: name.padEnd(36),
563
+ // Shell identifiers cannot hold '-' or ':'.
564
+ NAME_VAR: name.replace(/[-:]/g, "_"),
565
+ ACTIVE_HELP_VAR: configEnvVar(name, "ACTIVE_HELP"),
566
+ COMP_CMD: includeDescriptions ? REQUEST_CMD : NO_DESC_REQUEST_CMD,
567
+ NAME: name
568
+ };
569
+ return SCRIPT_TEMPLATES[shell].replace(
570
+ /@@(NAME_PAD36|NAME_VAR|ACTIVE_HELP_VAR|COMP_CMD|NAME)@@/g,
571
+ (_m, k) => vars[k]
572
+ );
573
+ }
574
+ function generateBashCompletion(program, includeDescriptions = true) {
575
+ return renderCompletionScript("bash", program.name(), includeDescriptions);
576
+ }
577
+ function generateZshCompletion(program, includeDescriptions = true) {
578
+ return renderCompletionScript("zsh", program.name(), includeDescriptions);
579
+ }
580
+ function generateFishCompletion(program, includeDescriptions = true) {
581
+ return renderCompletionScript("fish", program.name(), includeDescriptions);
582
+ }
583
+ function generatePowerShellCompletion(program, includeDescriptions = true) {
584
+ return renderCompletionScript("powershell", program.name(), includeDescriptions);
585
+ }
586
+ function shellHelp(sh, p) {
587
+ switch (sh) {
588
+ case "bash":
589
+ return `
590
+ This script depends on the 'bash-completion' package.
591
+ If it is not installed already, you can install it via your OS's package manager.
592
+
593
+ To load completions in your current shell session:
594
+
595
+ source <(${p} completion bash)
596
+
597
+ To load completions for every new session, execute once:
598
+
599
+ #### Linux:
600
+
601
+ ${p} completion bash > /etc/bash_completion.d/${p}
602
+
603
+ #### macOS:
604
+
605
+ ${p} completion bash > $(brew --prefix)/etc/bash_completion.d/${p}
606
+
607
+ You will need to start a new shell for this setup to take effect.
608
+ `;
609
+ case "zsh":
610
+ return `
611
+ If shell completion is not already enabled in your environment you will need
612
+ to enable it. You can execute the following once:
613
+
614
+ echo "autoload -U compinit; compinit" >> ~/.zshrc
615
+
616
+ To load completions in your current shell session:
617
+
618
+ source <(${p} completion zsh)
619
+
620
+ To load completions for every new session, execute once:
621
+
622
+ #### Linux:
623
+
624
+ ${p} completion zsh > "\${fpath[1]}/_${p}"
625
+
626
+ #### macOS:
627
+
628
+ ${p} completion zsh > $(brew --prefix)/share/zsh/site-functions/_${p}
629
+
630
+ You will need to start a new shell for this setup to take effect.
631
+ `;
632
+ case "fish":
633
+ return `
634
+ To load completions in your current shell session:
635
+
636
+ ${p} completion fish | source
637
+
638
+ To load completions for every new session, execute once:
639
+
640
+ ${p} completion fish > ~/.config/fish/completions/${p}.fish
641
+
642
+ You will need to start a new shell for this setup to take effect.
643
+ `;
644
+ case "powershell":
645
+ return `
646
+ To load completions in your current shell session:
647
+
648
+ ${p} completion powershell | Out-String | Invoke-Expression
649
+
650
+ To load completions for every new session, add the output of the above command
651
+ to your powershell profile.
652
+ `;
653
+ }
654
+ }
655
+ var NO_FILE_COMPLETIONS = _chunkJKMQSAJPjs.funcCompleter.call(void 0, () => []);
656
+ function completionCommand(program) {
657
+ installCompletionRequest(program);
658
+ const cmd = new (0, _commander.Command)("completion").description("Generate the autocompletion script for the specified shell");
659
+ cmd[BUILTIN] = true;
660
+ bindArgs(cmd, NO_FILE_COMPLETIONS);
661
+ for (const sh of SHELLS) {
662
+ const leaf = cmd.command(sh).description(`Generate the autocompletion script for ${sh}`).option("--no-descriptions", "disable completion descriptions").addHelpText("after", shellHelp(sh, program.name())).action((opts) => {
663
+ process.stdout.write(
664
+ renderCompletionScript(sh, program.name(), opts.descriptions !== false)
665
+ );
666
+ });
667
+ bindArgs(leaf, NO_FILE_COMPLETIONS);
668
+ }
669
+ return cmd;
670
+ }
671
+ function bindFlag(cmd, flag, completer) {
672
+ const name = flag.replace(/^--?/, "");
673
+ if (!cmd.options.some((o) => o.long === `--${name}`)) return;
674
+ const t = cmd;
675
+ const m = _nullishCoalesce(t[FLAG_COMPLETERS], () => ( (t[FLAG_COMPLETERS] = /* @__PURE__ */ new Map())));
676
+ if (!m.has(name)) m.set(name, completer);
677
+ }
678
+ function bindArgs(cmd, completer) {
679
+ cmd[ARGS_COMPLETER] = completer;
680
+ }
681
+ function registerRootAlias(root, name, target) {
682
+ const t = root;
683
+ (_nullishCoalesce(t[ROOT_ALIASES], () => ( (t[ROOT_ALIASES] = /* @__PURE__ */ new Map())))).set(name, target.trim().split(/\s+/).join(" "));
684
+ }
685
+ var stdio = {
686
+ out: (s) => {
687
+ process.stdout.write(s);
688
+ },
689
+ err: (s) => {
690
+ process.stderr.write(s);
691
+ }
692
+ };
693
+ function userArgs(argv, opts) {
694
+ let from = _optionalChain([opts, 'optionalAccess', _ => _.from]);
695
+ if (argv === void 0 && from === void 0) {
696
+ if (_optionalChain([process, 'access', _2 => _2.versions, 'optionalAccess', _3 => _3.electron])) from = "electron";
697
+ const ea = _nullishCoalesce(process.execArgv, () => ( []));
698
+ if (["-e", "--eval", "-p", "--print"].some((f) => ea.includes(f))) from = "eval";
699
+ }
700
+ const a = _nullishCoalesce(argv, () => ( process.argv));
701
+ switch (from) {
702
+ case void 0:
703
+ case "node":
704
+ return a.slice(2);
705
+ case "electron":
706
+ return process.defaultApp ? a.slice(2) : a.slice(1);
707
+ case "user":
708
+ return a.slice(0);
709
+ case "eval":
710
+ return a.slice(1);
711
+ default:
712
+ return null;
713
+ }
714
+ }
715
+ async function serve(program, words, noDesc) {
716
+ if (words.length === 0) {
717
+ stdio.err(`Error: requires at least 1 arg(s), only received 0
718
+ `);
719
+ process.exitCode = 1;
720
+ return;
721
+ }
722
+ try {
723
+ await completeRequest(program, words, noDesc);
724
+ } catch (e) {
725
+ stdio.err(`Error: ${e instanceof Error ? e.message : String(e)}
726
+ `);
727
+ process.exitCode = 1;
728
+ }
729
+ }
730
+ function installCompletionRequest(program) {
731
+ const t = program;
732
+ if (t[INSTALLED]) return;
733
+ t[INSTALLED] = true;
734
+ const request = (argv, opts) => {
735
+ const words = userArgs(argv, opts);
736
+ const first = _optionalChain([words, 'optionalAccess', _4 => _4[0]]);
737
+ if (first !== REQUEST_CMD && first !== NO_DESC_REQUEST_CMD) return null;
738
+ return serve(program, words.slice(1), first === NO_DESC_REQUEST_CMD);
739
+ };
740
+ const parse = program.parse.bind(program);
741
+ const parseAsync = program.parseAsync.bind(program);
742
+ program.parse = ((argv, opts) => {
743
+ const pending = request(argv, opts);
744
+ if (!pending) return parse(argv, opts);
745
+ void pending;
746
+ return program;
747
+ });
748
+ program.parseAsync = (async (argv, opts) => {
749
+ const pending = request(argv, opts);
750
+ if (!pending) return parseAsync(argv, opts);
751
+ await pending;
752
+ return program;
753
+ });
754
+ }
755
+ async function completeRequest(program, words, noDesc = false, io = stdio) {
756
+ const { completions, directive, error } = await getCompletions(program, words);
757
+ if (error) compError(io, error);
758
+ if (!noDesc) {
759
+ const v = envConfig(program.name(), "COMPLETION_DESCRIPTIONS");
760
+ const b = v === void 0 ? void 0 : parseBool(v);
761
+ if (b !== void 0) noDesc = !b;
762
+ }
763
+ for (let c of completions) {
764
+ if (noDesc) c = c.split(" ")[0];
765
+ c = c.split("\n")[0];
766
+ io.out(`${goTrimSpace(c)}
767
+ `);
768
+ }
769
+ io.out(`:${directive}
770
+ `);
771
+ io.err(`Completion ended with directive: ${_chunkJKMQSAJPjs.directiveName.call(void 0, directive)}
772
+ `);
773
+ }
774
+ function envConfig(prog, suffix) {
775
+ for (const k of [configEnvVar(prog, suffix), configEnvVar("COBRA", suffix)]) {
776
+ const v = process.env[k];
777
+ if (v) return v;
778
+ }
779
+ return void 0;
780
+ }
781
+ function parseBool(v) {
782
+ if (["1", "t", "T", "TRUE", "true", "True"].includes(v)) return true;
783
+ if (["0", "f", "F", "FALSE", "false", "False"].includes(v)) return false;
784
+ return void 0;
785
+ }
786
+ function goTrimSpace(s) {
787
+ const ws = "[\\t\\n\\v\\f\\r \\u0085\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]";
788
+ return s.replace(new RegExp(`^${ws}+|${ws}+$`, "g"), "");
789
+ }
790
+ function compError(io, msg) {
791
+ const line = `[Debug] [Error] ${msg}
792
+ `;
793
+ const file = process.env["BASH_COMP_DEBUG_FILE"];
794
+ if (file) {
795
+ try {
796
+ _fs.appendFileSync.call(void 0, file, line);
797
+ } catch (e2) {
798
+ }
799
+ }
800
+ io.err(line);
801
+ }
802
+ function flagName(f) {
803
+ return _nullishCoalesce(_nullishCoalesce(f.long, () => ( f.short)), () => ( ""));
804
+ }
805
+ function toFlag(o, owner, root, inherited) {
806
+ const help = _optionalChain([internals, 'call', _5 => _5(owner), 'access', _6 => _6._getHelpOption, 'optionalCall', _7 => _7()]) === o;
807
+ const version = !help && internals(owner)._versionOptionName === o.attributeName();
808
+ let usage = o.description;
809
+ if (help) usage = `help for ${owner.name()}`;
810
+ else if (version) usage = `version for ${root.name()}`;
811
+ else if (_optionalChain([o, 'access', _8 => _8.argChoices, 'optionalAccess', _9 => _9.length])) {
812
+ const suffix = `(one of: ${o.argChoices.join(", ")})`;
813
+ usage = usage ? `${usage} ${suffix}` : suffix;
814
+ }
815
+ return {
816
+ owner,
817
+ long: _optionalChain([o, 'access', _10 => _10.long, 'optionalAccess', _11 => _11.replace, 'call', _12 => _12(/^--/, "")]),
818
+ short: _optionalChain([o, 'access', _13 => _13.short, 'optionalAccess', _14 => _14.replace, 'call', _15 => _15(/^-/, "")]),
819
+ usage,
820
+ takesValue: o.required || o.optional,
821
+ multi: o.variadic,
822
+ hidden: o.hidden,
823
+ required: o.mandatory,
824
+ stops: help || version,
825
+ inherited,
826
+ choices: o.argChoices
827
+ };
828
+ }
829
+ function flagsOf(root, chain) {
830
+ const cmd = chain[chain.length - 1];
831
+ const out = [];
832
+ for (let i = chain.length - 2; i >= 0; i--) {
833
+ const anc = chain[i];
834
+ if (internals(anc)._enablePositionalOptions) break;
835
+ for (const o of anc.options) out.push(toFlag(o, anc, root, true));
836
+ }
837
+ if (isShim(root, cmd)) {
838
+ out.push({
839
+ owner: cmd,
840
+ long: "help",
841
+ short: "h",
842
+ usage: `help for ${cmd.name()}`,
843
+ takesValue: false,
844
+ multi: false,
845
+ hidden: false,
846
+ required: false,
847
+ stops: true,
848
+ inherited: false
849
+ });
850
+ return out;
851
+ }
852
+ for (const o of cmd.options) out.push(toFlag(o, cmd, root, false));
853
+ const help = _optionalChain([internals, 'call', _16 => _16(cmd), 'access', _17 => _17._getHelpOption, 'optionalCall', _18 => _18()]);
854
+ if (help && !cmd.options.includes(help)) out.push(toFlag(help, cmd, root, false));
855
+ return out;
856
+ }
857
+ function rootAliases(root) {
858
+ return _nullishCoalesce(root[ROOT_ALIASES], () => ( /* @__PURE__ */ new Map()));
859
+ }
860
+ function isShim(root, cmd) {
861
+ return cmd.parent === root && rootAliases(root).has(cmd.name());
862
+ }
863
+ var lookupLong = (flags, name) => flags.find((f) => f.long === name);
864
+ var lookupShort = (flags, s) => flags.find((f) => f.short === s);
865
+ function subcommand(cmd, word) {
866
+ return cmd.commands.find((c) => c.name() === word || c.aliases().includes(word));
867
+ }
868
+ function isFlagArg(a) {
869
+ return a.length >= 3 && a.startsWith("--") || a.length >= 2 && a[0] === "-" && a[1] !== "-";
870
+ }
871
+ function consumesNext(flags, s) {
872
+ if (s.includes("=")) return false;
873
+ if (s.startsWith("--")) return _nullishCoalesce(_optionalChain([lookupLong, 'call', _19 => _19(flags, s.slice(2)), 'optionalAccess', _20 => _20.takesValue]), () => ( true));
874
+ if (s.startsWith("-") && s.length === 2) return _nullishCoalesce(_optionalChain([lookupShort, 'call', _21 => _21(flags, s.slice(1)), 'optionalAccess', _22 => _22.takesValue]), () => ( true));
875
+ return false;
876
+ }
877
+ function stripFlags(args, flags) {
878
+ const commands = [];
879
+ for (let i = 0; i < args.length; ) {
880
+ const s = args[i++];
881
+ if (s === "--") break;
882
+ if (s.startsWith("-") && consumesNext(flags, s)) {
883
+ if (args.length - i <= 1) break;
884
+ i++;
885
+ continue;
886
+ }
887
+ if (s !== "" && !s.startsWith("-")) commands.push(s);
888
+ }
889
+ return commands;
890
+ }
891
+ function argsMinusFirst(args, x, flags) {
892
+ for (let pos = 0; pos < args.length; ) {
893
+ const s = args[pos];
894
+ if (s === "--") break;
895
+ if (s.startsWith("-") && consumesNext(flags, s)) {
896
+ pos += 2;
897
+ continue;
898
+ }
899
+ if (!s.startsWith("-") && s === x) return [...args.slice(0, pos), ...args.slice(pos + 1)];
900
+ pos++;
901
+ }
902
+ return args;
903
+ }
904
+ function find(root, args) {
905
+ const chain = [root];
906
+ const words = [];
907
+ let rest = args;
908
+ for (; ; ) {
909
+ const cur = chain[chain.length - 1];
910
+ const flags = flagsOf(root, chain);
911
+ const next = stripFlags(rest, flags)[0];
912
+ if (next === void 0) break;
913
+ const sub = subcommand(cur, next);
914
+ if (!sub) break;
915
+ rest = argsMinusFirst(rest, next, flags);
916
+ words.push(sub.name());
917
+ chain.push(sub);
918
+ }
919
+ return { chain, words, rest };
920
+ }
921
+ function parseFlags(flags, args) {
922
+ const seen = [];
923
+ const positionals = [];
924
+ let dashdash = false;
925
+ for (let i = 0; i < args.length; ) {
926
+ const s = args[i++];
927
+ if (dashdash || s.length < 2 || !s.startsWith("-")) {
928
+ positionals.push(s);
929
+ continue;
930
+ }
931
+ if (s === "--") {
932
+ dashdash = true;
933
+ continue;
934
+ }
935
+ if (s.startsWith("--")) {
936
+ const body = s.slice(2);
937
+ if (body.startsWith("-") || body.startsWith("=")) throw new Error(`bad flag syntax: ${s}`);
938
+ const eq = body.indexOf("=");
939
+ const name = eq < 0 ? body : body.slice(0, eq);
940
+ const f = lookupLong(flags, name);
941
+ if (!f) throw new Error(`unknown flag: --${name}`);
942
+ if (eq < 0 && f.takesValue) {
943
+ if (i >= args.length) throw new Error(`flag needs an argument: ${s}`);
944
+ i++;
945
+ }
946
+ seen.push(f);
947
+ continue;
948
+ }
949
+ const shorthands = s.slice(1);
950
+ for (let j = 0; j < shorthands.length; j++) {
951
+ const c = shorthands[j];
952
+ const f = lookupShort(flags, c);
953
+ if (!f) throw new Error(`unknown shorthand flag: '${c}' in -${shorthands}`);
954
+ seen.push(f);
955
+ const rest = shorthands.slice(j + 1);
956
+ if (rest.startsWith("=")) break;
957
+ if (!f.takesValue) continue;
958
+ if (rest === "") {
959
+ if (i >= args.length) throw new Error(`flag needs an argument: '${c}' in -${shorthands}`);
960
+ i++;
961
+ }
962
+ break;
963
+ }
964
+ }
965
+ return { seen, positionals };
966
+ }
967
+ function checkFlagCompletion(cmd, flags, args, last) {
968
+ let name = "";
969
+ let trimmed = args;
970
+ let withEqual = false;
971
+ let value = last;
972
+ if (last.startsWith("-")) {
973
+ const idx = last.indexOf("=");
974
+ if (idx < 0) return { args, toComplete: last };
975
+ name = last.startsWith("--") ? last.slice(2, idx) : last.slice(0, idx).slice(-1);
976
+ value = last.slice(idx + 1);
977
+ withEqual = true;
978
+ }
979
+ if (name === "" && args.length > 0) {
980
+ const prev = args[args.length - 1];
981
+ if (isFlagArg(prev) && !prev.includes("=")) {
982
+ name = prev.startsWith("--") ? prev.slice(2) : prev.slice(-1);
983
+ trimmed = args.slice(0, -1);
984
+ }
985
+ }
986
+ if (name === "") return { args: trimmed, toComplete: value };
987
+ const flag = _nullishCoalesce((name.length === 1 ? lookupShort(flags, name) : void 0), () => ( lookupLong(flags, name)));
988
+ if (!flag) {
989
+ return {
990
+ args,
991
+ toComplete: last,
992
+ error: `Subcommand '${cmd.name()}' does not support flag '${name}'`
993
+ };
994
+ }
995
+ if (!withEqual && !flag.takesValue) return { args, toComplete: value };
996
+ return { flag, args: trimmed, toComplete: value };
997
+ }
998
+ function orderedFlags(flags) {
999
+ const byName = (a, b) => {
1000
+ const x = flagName(a);
1001
+ const y = flagName(b);
1002
+ return x < y ? -1 : x > y ? 1 : 0;
1003
+ };
1004
+ return [
1005
+ ...flags.filter((f) => f.inherited).sort(byName),
1006
+ ...flags.filter((f) => !f.inherited).sort(byName)
1007
+ ];
1008
+ }
1009
+ function flagNameCompletions(f, toComplete) {
1010
+ if (f.hidden) return [];
1011
+ const out = [];
1012
+ if (f.long && `--${f.long}`.startsWith(toComplete)) out.push(`--${f.long} ${f.usage}`);
1013
+ if (f.short && `-${f.short}`.startsWith(toComplete)) out.push(`-${f.short} ${f.usage}`);
1014
+ return out;
1015
+ }
1016
+ function requiredFlags(flags, seen, toComplete) {
1017
+ return orderedFlags(flags).filter((f) => f.required && !seen.includes(f)).flatMap((f) => flagNameCompletions(f, toComplete));
1018
+ }
1019
+ function positionalChoices(cmd, n) {
1020
+ const args = cmd.registeredArguments;
1021
+ const last = args[args.length - 1];
1022
+ const a = _nullishCoalesce(args[n], () => ( (_optionalChain([last, 'optionalAccess', _23 => _23.variadic]) ? last : void 0)));
1023
+ return _optionalChain([a, 'optionalAccess', _24 => _24.argChoices]);
1024
+ }
1025
+ async function getCompletions(root, args) {
1026
+ const toCompleteRaw = args.length ? args[args.length - 1] : "";
1027
+ const { chain, words, rest } = find(root, args.slice(0, -1));
1028
+ const cmd = chain[chain.length - 1];
1029
+ const flags = flagsOf(root, chain);
1030
+ const fc = checkFlagCompletion(cmd, flags, rest, toCompleteRaw);
1031
+ const { flag, toComplete } = fc;
1032
+ const flagCompletion = !fc.args.includes("--");
1033
+ let parsed;
1034
+ try {
1035
+ parsed = parseFlags(flags, fc.args);
1036
+ } catch (e) {
1037
+ return {
1038
+ completions: [],
1039
+ directive: _chunkJKMQSAJPjs.ShellCompDirective.Default,
1040
+ error: `Error while parsing flags from args [${fc.args.join(" ")}]: ${e.message}`
1041
+ };
1042
+ }
1043
+ if (fc.error && flagCompletion) {
1044
+ return { completions: [], directive: _chunkJKMQSAJPjs.ShellCompDirective.Default, error: fc.error };
1045
+ }
1046
+ if (parsed.seen.some((f) => f.stops)) {
1047
+ return { completions: [], directive: _chunkJKMQSAJPjs.ShellCompDirective.NoFileComp };
1048
+ }
1049
+ const finalArgs = parsed.positionals;
1050
+ const ctx = { commandPath: words.join(" "), args: finalArgs };
1051
+ let completions = [];
1052
+ if (!flag && toComplete.startsWith("-") && !toComplete.includes("=") && flagCompletion) {
1053
+ completions = requiredFlags(flags, parsed.seen, toComplete);
1054
+ if (completions.length === 0) {
1055
+ for (const f of orderedFlags(flags)) {
1056
+ if (!parsed.seen.includes(f) || f.multi) completions.push(...flagNameCompletions(f, toComplete));
1057
+ }
1058
+ }
1059
+ const noSpace = completions.length === 1 && completions[0].endsWith("=");
1060
+ return {
1061
+ completions,
1062
+ directive: noSpace ? _chunkJKMQSAJPjs.ShellCompDirective.NoSpace : _chunkJKMQSAJPjs.ShellCompDirective.NoFileComp
1063
+ };
1064
+ }
1065
+ let directive = _chunkJKMQSAJPjs.ShellCompDirective.Default;
1066
+ if (!flag) {
1067
+ const localGiven = parsed.seen.some((f) => !f.inherited);
1068
+ if (finalArgs.length === 0 && !localGiven) {
1069
+ const subs = cmd.commands.filter((s) => !internals(s)._hidden && !s[BUILTIN]).sort((a, b) => a.name() < b.name() ? -1 : a.name() > b.name() ? 1 : 0);
1070
+ for (const s of subs) {
1071
+ if (s.name().startsWith(toComplete)) {
1072
+ completions.push(`${s.name()} ${s.summary() || s.description()}`);
1073
+ }
1074
+ directive = _chunkJKMQSAJPjs.ShellCompDirective.NoFileComp;
1075
+ }
1076
+ }
1077
+ completions.push(...requiredFlags(flags, parsed.seen, toComplete));
1078
+ const choices = positionalChoices(cmd, finalArgs.length);
1079
+ if (_optionalChain([choices, 'optionalAccess', _25 => _25.length])) {
1080
+ completions.push(...choices.filter((v) => v.startsWith(toComplete)));
1081
+ return { completions, directive: _chunkJKMQSAJPjs.ShellCompDirective.NoFileComp };
1082
+ }
1083
+ }
1084
+ const result = flag && flagCompletion ? await flagValueCompletion(flag, ctx, toComplete) : await argsCompletion(root, cmd, ctx, toComplete);
1085
+ if (result) {
1086
+ completions.push(...result.completions);
1087
+ directive = result.directive;
1088
+ }
1089
+ return { completions, directive };
1090
+ }
1091
+ async function flagValueCompletion(flag, ctx, toComplete) {
1092
+ const bound = _optionalChain([flag, 'access', _26 => _26.owner, 'access', _27 => _27[FLAG_COMPLETERS], 'optionalAccess', _28 => _28.get, 'call', _29 => _29(flagName(flag))]);
1093
+ if (bound) return _chunkJKMQSAJPjs.resolveCompletions.call(void 0, bound, toComplete, ctx);
1094
+ if (!_optionalChain([flag, 'access', _30 => _30.choices, 'optionalAccess', _31 => _31.length])) return null;
1095
+ const lower = toComplete.toLowerCase();
1096
+ return {
1097
+ completions: flag.choices.filter((v) => v.toLowerCase().startsWith(lower)),
1098
+ directive: _chunkJKMQSAJPjs.ShellCompDirective.NoFileComp
1099
+ };
1100
+ }
1101
+ async function argsCompletion(root, cmd, ctx, toComplete) {
1102
+ const bound = cmd[ARGS_COMPLETER];
1103
+ const aliases = cmd === root ? rootAliases(root) : /* @__PURE__ */ new Map();
1104
+ if (!bound && aliases.size === 0) return null;
1105
+ const r = bound ? await _chunkJKMQSAJPjs.resolveCompletions.call(void 0, bound, toComplete, ctx) : { completions: [], directive: _chunkJKMQSAJPjs.ShellCompDirective.Default };
1106
+ if (aliases.size > 0) {
1107
+ r.directive |= _chunkJKMQSAJPjs.ShellCompDirective.NoFileComp;
1108
+ for (const [name, target] of [...aliases].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) {
1109
+ if (name.startsWith(toComplete)) r.completions.push(`${name} alias for ${target}`);
1110
+ }
1111
+ }
1112
+ return r;
1113
+ }
1114
+
1115
+
1116
+
1117
+
1118
+
1119
+
1120
+
1121
+
1122
+
1123
+
1124
+
1125
+
1126
+
1127
+
1128
+
1129
+
1130
+
1131
+ exports.REQUEST_CMD = REQUEST_CMD; exports.NO_DESC_REQUEST_CMD = NO_DESC_REQUEST_CMD; exports.SHELLS = SHELLS; exports.renderCompletionScript = renderCompletionScript; exports.generateBashCompletion = generateBashCompletion; exports.generateZshCompletion = generateZshCompletion; exports.generateFishCompletion = generateFishCompletion; exports.generatePowerShellCompletion = generatePowerShellCompletion; exports.completionCommand = completionCommand; exports.bindFlag = bindFlag; exports.bindArgs = bindArgs; exports.registerRootAlias = registerRootAlias; exports.installCompletionRequest = installCompletionRequest; exports.completeRequest = completeRequest; exports.completion_exports = completion_exports;