@hop-top/kit 0.5.0-alpha.1 → 0.5.0-alpha.10
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.
- package/CHANGELOG.md +251 -0
- package/LICENSE +1 -1
- package/LICENSE-cobra.txt +174 -0
- package/NOTICE +15 -0
- package/README.md +55 -259
- package/dist/aim-DZHwwiIc.d.ts +139 -0
- package/dist/aim.d.ts +1 -116
- package/dist/aim.js +13 -414
- package/dist/alias-D9_qFlyP.d.ts +174 -0
- package/dist/alias.d.ts +2 -73
- package/dist/alias.js +27 -207
- package/dist/api-DAexsu2H.d.ts +77 -0
- package/dist/api.d.ts +1 -62
- package/dist/api.js +10 -164
- package/dist/auth-2-jfgiHn.d.ts +34 -0
- package/dist/auth.d.ts +1 -26
- package/dist/auth.js +6 -40
- package/dist/chunk-2JV3A7OP.js +1894 -0
- package/dist/chunk-3FIKGFKI.js +54 -0
- package/dist/chunk-4UE5TCMQ.js +104 -0
- package/dist/chunk-6HFAEZ52.js +29 -0
- package/dist/chunk-6SVOHNIC.js +17 -0
- package/dist/chunk-72XZWQX7.js +504 -0
- package/dist/chunk-ABQSE7AI.js +513 -0
- package/dist/chunk-BDNNPRX6.js +41 -0
- package/dist/chunk-BLS2OBIQ.js +263 -0
- package/dist/chunk-BRNEKPWX.js +37 -0
- package/dist/chunk-CSJWB6D3.js +151 -0
- package/dist/chunk-GGWJRWWA.js +309 -0
- package/dist/chunk-GHPJJV5L.js +613 -0
- package/dist/chunk-IXVQ62NZ.js +334 -0
- package/dist/chunk-JKMQSAJP.js +174 -0
- package/dist/chunk-JZ22ZUFA.js +1131 -0
- package/dist/chunk-K7VCKJ27.js +814 -0
- package/dist/chunk-KVG7YCTS.js +115 -0
- package/dist/chunk-L23O2FFE.js +51 -0
- package/dist/chunk-MQXYDYRD.js +968 -0
- package/dist/chunk-MUIQVU6E.js +251 -0
- package/dist/chunk-NLMS7HGP.js +178 -0
- package/dist/chunk-POR5L2DG.js +247 -0
- package/dist/chunk-PSFYJGDG.js +1445 -0
- package/dist/chunk-QJVSKKRQ.js +369 -0
- package/dist/chunk-QPUCXQXT.js +67 -0
- package/dist/chunk-QQQYCWSC.js +240 -0
- package/dist/chunk-R5U7XKVJ.js +16 -0
- package/dist/chunk-SNVGDYX7.js +187 -0
- package/dist/chunk-T46YPHKN.js +669 -0
- package/dist/chunk-UKZIAQA7.js +26 -0
- package/dist/chunk-WBVO43HU.js +355 -0
- package/dist/chunk-WUOAQVOA.js +86 -0
- package/dist/chunk-WWUKGJB5.js +90 -0
- package/dist/chunk-XJTRY453.js +868 -0
- package/dist/chunk-YGYQUFGY.js +219 -0
- package/dist/chunk-YOBAUCVN.js +583 -0
- package/dist/cli-C5B5tnpA.d.ts +400 -0
- package/dist/cli.d.ts +7 -309
- package/dist/cli.js +70 -945
- package/dist/completion-csVun6SP.d.ts +112 -0
- package/dist/completion-values-By-mnjNt.d.ts +142 -0
- package/dist/completion-values.d.ts +1 -0
- package/dist/completion-values.js +29 -0
- package/dist/completion.d.ts +3 -0
- package/dist/completion.js +34 -0
- package/dist/compliance-AxFf-uMy.d.ts +60 -0
- package/dist/compliance.d.ts +1 -0
- package/dist/compliance.js +17 -0
- package/dist/config-CaK60ByQ.d.ts +241 -0
- package/dist/config.d.ts +1 -97
- package/dist/config.js +8 -78
- package/dist/errcorrect-BcX1Ft0K.d.ts +44 -0
- package/dist/errcorrect.d.ts +1 -37
- package/dist/errcorrect.js +8 -68
- package/dist/error-Do8Qji43.d.ts +231 -0
- package/dist/id/index.d.ts +2 -83
- package/dist/id/index.js +14 -65
- package/dist/index-BKJZClJx.d.ts +1486 -0
- package/dist/index-C3Zw4wDJ.d.ts +359 -0
- package/dist/index-DCe1boBz.d.ts +328 -0
- package/dist/index-VLDcI5NF.d.ts +95 -0
- package/dist/index.d.ts +37 -0
- package/dist/index.js +132 -0
- package/dist/llm-DYuR7_uX.d.ts +1069 -0
- package/dist/llm-anthropic-Cd_I2xXB.d.ts +67 -0
- package/dist/llm-anthropic.d.ts +2 -0
- package/dist/llm-anthropic.js +13 -0
- package/dist/llm-openai-DyFrucmV.d.ts +87 -0
- package/dist/llm-openai.d.ts +2 -0
- package/dist/llm-openai.js +19 -0
- package/dist/llm.d.ts +1 -188
- package/dist/llm.js +101 -356
- package/dist/log-CkaxMX3U.d.ts +115 -0
- package/dist/log.d.ts +2 -0
- package/dist/log.js +14 -0
- package/dist/mcp/index.d.ts +4 -0
- package/dist/mcp/index.js +184 -0
- package/dist/netpolicy-Brx5XZUB.d.ts +151 -0
- package/dist/netpolicy.d.ts +1 -0
- package/dist/netpolicy.js +25 -0
- package/dist/output-CjZWmL8s.d.ts +420 -0
- package/dist/output.d.ts +3 -213
- package/dist/output.js +137 -447
- package/dist/parity-CvMuYcVI.d.ts +61 -0
- package/dist/progress-CAzyxeWl.d.ts +38 -0
- package/dist/progress.d.ts +1 -30
- package/dist/progress.js +6 -55
- package/dist/provenance-SMFHm5gx.d.ts +30 -0
- package/dist/provenance.d.ts +1 -24
- package/dist/provenance.js +6 -31
- package/dist/routellm-B0nv59mH.d.ts +111 -0
- package/dist/routellm.d.ts +2 -64
- package/dist/routellm.js +13 -255
- package/dist/rpc-D31Lg0Kc.d.ts +32 -0
- package/dist/rpc.d.ts +2 -25
- package/dist/rpc.js +4 -98
- package/dist/safety-CUaYEjZc.d.ts +30 -0
- package/dist/safety.d.ts +1 -24
- package/dist/safety.js +6 -43
- package/dist/scope-BrhYB4ij.d.ts +141 -0
- package/dist/scope.d.ts +1 -121
- package/dist/scope.js +20 -377
- package/dist/serve-D8yWMrTc.d.ts +646 -0
- package/dist/serve.d.ts +3 -0
- package/dist/serve.js +75 -0
- package/dist/sqlstore.js +6 -39
- package/dist/stream-CrjeCp0M.d.ts +44 -0
- package/dist/stream.d.ts +1 -35
- package/dist/stream.js +8 -51
- package/dist/telemetry/index.d.ts +1 -315
- package/dist/telemetry/index.js +26 -599
- package/dist/toolspec-DcPwwoAZ.d.ts +368 -0
- package/dist/toolspec.d.ts +2 -0
- package/dist/toolspec.js +37 -0
- package/dist/tui/index.d.ts +6 -298
- package/dist/tui/index.js +17 -381
- package/dist/upgrade-p_zh3pvV.d.ts +102 -0
- package/dist/upgrade.d.ts +1 -95
- package/dist/upgrade.js +6 -114
- package/dist/xdg-DB7Shoib.d.ts +179 -0
- package/dist/xdg.d.ts +1 -169
- package/dist/xdg.js +14 -128
- package/package.json +192 -24
- package/src/README.md +15 -0
- package/src/alias.conformance.test.ts +250 -0
- package/src/alias.test.ts +206 -2
- package/src/alias.ts +196 -21
- package/src/cli.help-command.test.ts +105 -0
- package/src/cli.offline.test.ts +93 -0
- package/src/cli.parity.test.ts +192 -0
- package/src/cli.test.ts +95 -1
- package/src/cli.ts +195 -25
- package/src/completion-scripts.ts +16 -0
- package/src/completion-values.test.ts +76 -16
- package/src/completion-values.ts +170 -66
- package/src/completion.conformance.test.ts +297 -0
- package/src/completion.test.ts +256 -145
- package/src/completion.ts +767 -121
- package/src/compliance.test.ts +196 -2
- package/src/compliance.ts +440 -20
- package/src/config-merge.test.ts +425 -0
- package/src/config.test.ts +228 -1
- package/src/config.ts +429 -16
- package/src/gen/crud_pb.ts +7 -7
- package/src/id/README.md +38 -0
- package/src/id/contract.test.ts +1 -1
- package/src/id/index.test.ts +1 -1
- package/src/id/index.ts +3 -2
- package/src/index.test.ts +71 -0
- package/src/index.ts +46 -0
- package/src/llm-anthropic.conformance.test.ts +1135 -0
- package/src/llm-anthropic.test.ts +152 -0
- package/src/llm-anthropic.ts +940 -0
- package/src/llm-choice-hermetic.test.ts +335 -0
- package/src/llm-config.test.ts +232 -0
- package/src/llm-config.ts +106 -0
- package/src/llm-endpoint.ts +254 -0
- package/src/llm-error.ts +17 -0
- package/src/llm-errors.ts +152 -0
- package/src/llm-file.ts +126 -0
- package/src/llm-http.ts +317 -0
- package/src/llm-keys.ts +167 -0
- package/src/llm-media.conformance.test.ts +87 -0
- package/src/llm-media.test.ts +279 -0
- package/src/llm-media.ts +322 -0
- package/src/llm-openai.conformance.test.ts +407 -0
- package/src/llm-openai.test.ts +510 -0
- package/src/llm-openai.ts +708 -0
- package/src/llm-payload.ts +155 -0
- package/src/llm-quote.ts +46 -0
- package/src/llm-routellm.conformance.test.ts +44 -0
- package/src/llm-toolnames.conformance.test.ts +112 -0
- package/src/llm-toolnames.test.ts +132 -0
- package/src/llm-toolnames.ts +298 -0
- package/src/llm-uri.ts +99 -0
- package/src/llm.test.ts +43 -15
- package/src/llm.toolcall.test.ts +175 -0
- package/src/llm.ts +602 -190
- package/src/log.parity.test.ts +105 -0
- package/src/log.test.ts +270 -1
- package/src/log.ts +228 -49
- package/src/mcp/README.md +63 -0
- package/src/mcp/args-separator.test.ts +164 -0
- package/src/mcp/args.test.ts +223 -0
- package/src/mcp/args.ts +160 -0
- package/src/mcp/audit.test.ts +520 -0
- package/src/mcp/audit.ts +70 -0
- package/src/mcp/bridge.test.ts +222 -0
- package/src/mcp/bridge.ts +291 -0
- package/src/mcp/conformance.test.ts +357 -0
- package/src/mcp/dispatch.ts +359 -0
- package/src/mcp/identity.test.ts +166 -0
- package/src/mcp/identity.ts +72 -0
- package/src/mcp/index.ts +176 -0
- package/src/mcp/legacy-notify.test.ts +59 -0
- package/src/mcp/legacy.ts +367 -0
- package/src/mcp/mcp.test.ts +707 -0
- package/src/mcp/modern-confirm.test.ts +520 -0
- package/src/mcp/modern-confirm.ts +484 -0
- package/src/mcp/modern.ts +788 -0
- package/src/mcp/stdio.test.ts +313 -0
- package/src/mcp/stdio.ts +254 -0
- package/src/mcp/tasks.ts +82 -0
- package/src/mcp/testtree.ts +250 -0
- package/src/mcp/toolname.test.ts +147 -0
- package/src/mcp/types.ts +689 -0
- package/src/netpolicy.test.ts +280 -0
- package/src/netpolicy.ts +256 -0
- package/src/output/README.md +46 -0
- package/src/output/builtins.ts +5 -5
- package/src/output/dispatch.ts +10 -2
- package/src/output/error.ts +459 -0
- package/src/output/formatter.ts +29 -5
- package/src/output/formatters/README.md +50 -0
- package/src/output/formatters/csv.ts +48 -12
- package/src/output/formatters/json.ts +4 -25
- package/src/output/formatters/project.ts +34 -0
- package/src/output/formatters/table.ts +8 -6
- package/src/output/formatters/text.ts +7 -3
- package/src/output/formatters/yaml.ts +5 -22
- package/src/output/projection.test.ts +298 -0
- package/src/output/projection.ts +33 -59
- package/src/output/template.ts +11 -21
- package/src/output.surface.test.ts +41 -0
- package/src/output.ts +64 -3
- package/src/published-types.test.ts +133 -0
- package/src/routellm.test.ts +209 -28
- package/src/routellm.toolcall.test.ts +521 -0
- package/src/routellm.ts +213 -177
- package/src/router/README.md +44 -0
- package/src/router/server.test.ts +41 -0
- package/src/router/server.ts +11 -0
- package/src/safety.test.ts +19 -9
- package/src/scope-defaults.json +29 -29
- package/src/serve.test.ts +1257 -0
- package/src/serve.ts +1665 -0
- package/src/telemetry/README.md +48 -0
- package/src/telemetry/client.test.ts +31 -0
- package/src/telemetry/client.ts +12 -6
- package/src/telemetry/offline.test.ts +64 -0
- package/src/toolspec-internal.ts +279 -0
- package/src/toolspec-manifest.test.ts +167 -0
- package/src/toolspec-manifest.ts +410 -0
- package/src/toolspec-spec-schemas.ts +12 -0
- package/src/toolspec-spec.test.ts +273 -0
- package/src/toolspec-spec.ts +458 -0
- package/src/toolspec.from-command.test.ts +350 -0
- package/src/toolspec.test.ts +2 -2
- package/src/toolspec.ts +222 -0
- package/src/triton/README.md +34 -0
- package/src/tui/README.md +42 -0
- package/src/tui/parity.test.ts +120 -31
- package/src/tui/parity.ts +58 -7
- package/src/wizard.test.ts +7 -7
- package/test/llm/conformance-helpers.ts +100 -0
- package/test/output/csv.test.ts +164 -0
- package/test/output/dispatch.test.ts +1 -2
- package/test/output/error.test.ts +277 -0
- package/test/output/smoke-capture.ts +2 -2
- package/test/output/smoke.test.ts +2 -2
- package/test/output/taxonomy-contract.test.ts +148 -0
- package/test/setup-env.ts +16 -0
- package/test/toolspec/fixture.ts +79 -0
- package/tsconfig.json +3 -1
- package/tsconfig.test.json +10 -0
- package/vitest.config.ts +9 -0
- package/src/tui/parity.json +0 -74
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// Code generated by make completion-regen; DO NOT EDIT.
|
|
2
|
+
//
|
|
3
|
+
// cobra's bash (V2), zsh, fish and powershell completion scripts, as the
|
|
4
|
+
// cobra version in go.mod writes them, with the program-dependent parts
|
|
5
|
+
// replaced by @@...@@ tokens (go/console/cli/completion/
|
|
6
|
+
// completion_templates_test.go). Derived from Cobra
|
|
7
|
+
// (https://github.com/spf13/cobra), Copyright 2013-2023 The Cobra
|
|
8
|
+
// Authors, licensed under the Apache License, Version 2.0; the full text
|
|
9
|
+
// is in sdk/ts/LICENSE-cobra.txt.
|
|
10
|
+
|
|
11
|
+
export const SCRIPT_TEMPLATES = {
|
|
12
|
+
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+=\"…\"\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",
|
|
13
|
+
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",
|
|
14
|
+
fish: "# fish completion for @@NAME_PAD36@@ -*- shell-script -*-\n\nfunction __@@NAME_VAR@@_debug\n set -l file \"$BASH_COMP_DEBUG_FILE\"\n if test -n \"$file\"\n echo \"$argv\" >> $file\n end\nend\n\nfunction __@@NAME_VAR@@_perform_completion\n __@@NAME_VAR@@_debug \"Starting __@@NAME_VAR@@_perform_completion\"\n\n # Extract all args except the last one\n set -l args (commandline -opc)\n # Extract the last arg and escape it in case it is a space\n set -l lastArg (string escape -- (commandline -ct))\n\n __@@NAME_VAR@@_debug \"args: $args\"\n __@@NAME_VAR@@_debug \"last arg: $lastArg\"\n\n # Disable ActiveHelp which is not supported for fish shell\n set -l requestComp \"@@ACTIVE_HELP_VAR@@=0 $args[1] @@COMP_CMD@@ $args[2..-1] $lastArg\"\n\n __@@NAME_VAR@@_debug \"Calling $requestComp\"\n set -l results (eval $requestComp 2> /dev/null)\n\n # Some programs may output extra empty lines after the directive.\n # Let's ignore them or else it will break completion.\n # Ref: https://github.com/spf13/cobra/issues/1279\n for line in $results[-1..1]\n if test (string trim -- $line) = \"\"\n # Found an empty line, remove it\n set results $results[1..-2]\n else\n # Found non-empty line, we have our proper output\n break\n end\n end\n\n set -l comps $results[1..-2]\n set -l directiveLine $results[-1]\n\n # For Fish, when completing a flag with an = (e.g., <program> -n=<TAB>)\n # completions must be prefixed with the flag\n set -l flagPrefix (string match -r -- '-.*=' \"$lastArg\")\n\n __@@NAME_VAR@@_debug \"Comps: $comps\"\n __@@NAME_VAR@@_debug \"DirectiveLine: $directiveLine\"\n __@@NAME_VAR@@_debug \"flagPrefix: $flagPrefix\"\n\n for comp in $comps\n printf \"%s%s\\n\" \"$flagPrefix\" \"$comp\"\n end\n\n printf \"%s\\n\" \"$directiveLine\"\nend\n\n# this function limits calls to __@@NAME_VAR@@_perform_completion, by caching the result behind $__@@NAME_VAR@@_perform_completion_once_result\nfunction __@@NAME_VAR@@_perform_completion_once\n __@@NAME_VAR@@_debug \"Starting __@@NAME_VAR@@_perform_completion_once\"\n\n if test -n \"$__@@NAME_VAR@@_perform_completion_once_result\"\n __@@NAME_VAR@@_debug \"Seems like a valid result already exists, skipping __@@NAME_VAR@@_perform_completion\"\n return 0\n end\n\n set --global __@@NAME_VAR@@_perform_completion_once_result (__@@NAME_VAR@@_perform_completion)\n if test -z \"$__@@NAME_VAR@@_perform_completion_once_result\"\n __@@NAME_VAR@@_debug \"No completions, probably due to a failure\"\n return 1\n end\n\n __@@NAME_VAR@@_debug \"Performed completions and set __@@NAME_VAR@@_perform_completion_once_result\"\n return 0\nend\n\n# this function is used to clear the $__@@NAME_VAR@@_perform_completion_once_result variable after completions are run\nfunction __@@NAME_VAR@@_clear_perform_completion_once_result\n __@@NAME_VAR@@_debug \"\"\n __@@NAME_VAR@@_debug \"========= clearing previously set __@@NAME_VAR@@_perform_completion_once_result variable ==========\"\n set --erase __@@NAME_VAR@@_perform_completion_once_result\n __@@NAME_VAR@@_debug \"Successfully erased the variable __@@NAME_VAR@@_perform_completion_once_result\"\nend\n\nfunction __@@NAME_VAR@@_requires_order_preservation\n __@@NAME_VAR@@_debug \"\"\n __@@NAME_VAR@@_debug \"========= checking if order preservation is required ==========\"\n\n __@@NAME_VAR@@_perform_completion_once\n if test -z \"$__@@NAME_VAR@@_perform_completion_once_result\"\n __@@NAME_VAR@@_debug \"Error determining if order preservation is required\"\n return 1\n end\n\n set -l directive (string sub --start 2 $__@@NAME_VAR@@_perform_completion_once_result[-1])\n __@@NAME_VAR@@_debug \"Directive is: $directive\"\n\n set -l shellCompDirectiveKeepOrder 32\n set -l keeporder (math (math --scale 0 $directive / $shellCompDirectiveKeepOrder) % 2)\n __@@NAME_VAR@@_debug \"Keeporder is: $keeporder\"\n\n if test $keeporder -ne 0\n __@@NAME_VAR@@_debug \"This does require order preservation\"\n return 0\n end\n\n __@@NAME_VAR@@_debug \"This doesn't require order preservation\"\n return 1\nend\n\n\n# This function does two things:\n# - Obtain the completions and store them in the global __@@NAME_VAR@@_comp_results\n# - Return false if file completion should be performed\nfunction __@@NAME_VAR@@_prepare_completions\n __@@NAME_VAR@@_debug \"\"\n __@@NAME_VAR@@_debug \"========= starting completion logic ==========\"\n\n # Start fresh\n set --erase __@@NAME_VAR@@_comp_results\n\n __@@NAME_VAR@@_perform_completion_once\n __@@NAME_VAR@@_debug \"Completion results: $__@@NAME_VAR@@_perform_completion_once_result\"\n\n if test -z \"$__@@NAME_VAR@@_perform_completion_once_result\"\n __@@NAME_VAR@@_debug \"No completion, probably due to a failure\"\n # Might as well do file completion, in case it helps\n return 1\n end\n\n set -l directive (string sub --start 2 $__@@NAME_VAR@@_perform_completion_once_result[-1])\n set --global __@@NAME_VAR@@_comp_results $__@@NAME_VAR@@_perform_completion_once_result[1..-2]\n\n __@@NAME_VAR@@_debug \"Completions are: $__@@NAME_VAR@@_comp_results\"\n __@@NAME_VAR@@_debug \"Directive is: $directive\"\n\n set -l shellCompDirectiveError 1\n set -l shellCompDirectiveNoSpace 2\n set -l shellCompDirectiveNoFileComp 4\n set -l shellCompDirectiveFilterFileExt 8\n set -l shellCompDirectiveFilterDirs 16\n\n if test -z \"$directive\"\n set directive 0\n end\n\n set -l compErr (math (math --scale 0 $directive / $shellCompDirectiveError) % 2)\n if test $compErr -eq 1\n __@@NAME_VAR@@_debug \"Received error directive: aborting.\"\n # Might as well do file completion, in case it helps\n return 1\n end\n\n set -l filefilter (math (math --scale 0 $directive / $shellCompDirectiveFilterFileExt) % 2)\n set -l dirfilter (math (math --scale 0 $directive / $shellCompDirectiveFilterDirs) % 2)\n if test $filefilter -eq 1; or test $dirfilter -eq 1\n __@@NAME_VAR@@_debug \"File extension filtering or directory filtering not supported\"\n # Do full file completion instead\n return 1\n end\n\n set -l nospace (math (math --scale 0 $directive / $shellCompDirectiveNoSpace) % 2)\n set -l nofiles (math (math --scale 0 $directive / $shellCompDirectiveNoFileComp) % 2)\n\n __@@NAME_VAR@@_debug \"nospace: $nospace, nofiles: $nofiles\"\n\n # If we want to prevent a space, or if file completion is NOT disabled,\n # we need to count the number of valid completions.\n # To do so, we will filter on prefix as the completions we have received\n # may not already be filtered so as to allow fish to match on different\n # criteria than the prefix.\n if test $nospace -ne 0; or test $nofiles -eq 0\n set -l prefix (commandline -t | string escape --style=regex)\n __@@NAME_VAR@@_debug \"prefix: $prefix\"\n\n set -l completions (string match -r -- \"^$prefix.*\" $__@@NAME_VAR@@_comp_results)\n set --global __@@NAME_VAR@@_comp_results $completions\n __@@NAME_VAR@@_debug \"Filtered completions are: $__@@NAME_VAR@@_comp_results\"\n\n # Important not to quote the variable for count to work\n set -l numComps (count $__@@NAME_VAR@@_comp_results)\n __@@NAME_VAR@@_debug \"numComps: $numComps\"\n\n if test $numComps -eq 1; and test $nospace -ne 0\n # We must first split on \\t to get rid of the descriptions to be\n # able to check what the actual completion will be.\n # We don't need descriptions anyway since there is only a single\n # real completion which the shell will expand immediately.\n set -l split (string split --max 1 \\t $__@@NAME_VAR@@_comp_results[1])\n\n # Fish won't add a space if the completion ends with any\n # of the following characters: @=/:.,\n set -l lastChar (string sub -s -1 -- $split)\n if not string match -r -q \"[@=/:.,]\" -- \"$lastChar\"\n # In other cases, to support the \"nospace\" directive we trick the shell\n # by outputting an extra, longer completion.\n __@@NAME_VAR@@_debug \"Adding second completion to perform nospace directive\"\n set --global __@@NAME_VAR@@_comp_results $split[1] $split[1].\n __@@NAME_VAR@@_debug \"Completions are now: $__@@NAME_VAR@@_comp_results\"\n end\n end\n\n if test $numComps -eq 0; and test $nofiles -eq 0\n # To be consistent with bash and zsh, we only trigger file\n # completion when there are no other completions\n __@@NAME_VAR@@_debug \"Requesting file completion\"\n return 1\n end\n end\n\n return 0\nend\n\n# Since Fish completions are only loaded once the user triggers them, we trigger them ourselves\n# so we can properly delete any completions provided by another script.\n# Only do this if the program can be found, or else fish may print some errors; besides,\n# the existing completions will only be loaded if the program can be found.\nif type -q \"@@NAME@@\"\n # The space after the program name is essential to trigger completion for the program\n # and not completion of the program name itself.\n # Also, we use '> /dev/null 2>&1' since '&>' is not supported in older versions of fish.\n complete --do-complete \"@@NAME@@ \" > /dev/null 2>&1\nend\n\n# Remove any pre-existing completions for the program since we will be handling all of them.\ncomplete -c @@NAME@@ -e\n\n# this will get called after the two calls below and clear the $__@@NAME_VAR@@_perform_completion_once_result global\ncomplete -c @@NAME@@ -n '__@@NAME_VAR@@_clear_perform_completion_once_result'\n# The call to __@@NAME_VAR@@_prepare_completions will setup __@@NAME_VAR@@_comp_results\n# which provides the program's completion choices.\n# If this doesn't require order preservation, we don't use the -k flag\ncomplete -c @@NAME@@ -n 'not __@@NAME_VAR@@_requires_order_preservation && __@@NAME_VAR@@_prepare_completions' -f -a '$__@@NAME_VAR@@_comp_results'\n# otherwise we use the -k flag\ncomplete -k -c @@NAME@@ -n '__@@NAME_VAR@@_requires_order_preservation && __@@NAME_VAR@@_prepare_completions' -f -a '$__@@NAME_VAR@@_comp_results'\n",
|
|
15
|
+
powershell: "# powershell completion for @@NAME_PAD36@@ -*- shell-script -*-\n\nfunction __@@NAME@@_debug {\n if ($env:BASH_COMP_DEBUG_FILE) {\n \"$args\" | Out-File -Append -FilePath \"$env:BASH_COMP_DEBUG_FILE\"\n }\n}\n\nfilter __@@NAME@@_escapeStringWithSpecialChars {\n $_ -replace '\\s|#|@|\\$|;|,|''|\\{|\\}|\\(|\\)|\"|`|\\||<|>|&','`$&'\n}\n\n[scriptblock]${__@@NAME_VAR@@CompleterBlock} = {\n param(\n $WordToComplete,\n $CommandAst,\n $CursorPosition\n )\n\n # Get the current command line and convert into a string\n $Command = $CommandAst.CommandElements\n $Command = \"$Command\"\n\n __@@NAME@@_debug \"\"\n __@@NAME@@_debug \"========= starting completion logic ==========\"\n __@@NAME@@_debug \"WordToComplete: $WordToComplete Command: $Command CursorPosition: $CursorPosition\"\n\n # The user could have moved the cursor backwards on the command-line.\n # We need to trigger completion from the $CursorPosition location, so we need\n # to truncate the command-line ($Command) up to the $CursorPosition location.\n # Make sure the $Command is longer then the $CursorPosition before we truncate.\n # This happens because the $Command does not include the last space.\n if ($Command.Length -gt $CursorPosition) {\n $Command=$Command.Substring(0,$CursorPosition)\n }\n __@@NAME@@_debug \"Truncated command: $Command\"\n\n $ShellCompDirectiveError=1\n $ShellCompDirectiveNoSpace=2\n $ShellCompDirectiveNoFileComp=4\n $ShellCompDirectiveFilterFileExt=8\n $ShellCompDirectiveFilterDirs=16\n $ShellCompDirectiveKeepOrder=32\n\n # Prepare the command to request completions for the program.\n # Split the command at the first space to separate the program and arguments.\n $Program,$Arguments = $Command.Split(\" \",2)\n\n $RequestComp=\"$Program @@COMP_CMD@@ $Arguments\"\n __@@NAME@@_debug \"RequestComp: $RequestComp\"\n\n # we cannot use $WordToComplete because it\n # has the wrong values if the cursor was moved\n # so use the last argument\n if ($WordToComplete -ne \"\" ) {\n $WordToComplete = $Arguments.Split(\" \")[-1]\n }\n __@@NAME@@_debug \"New WordToComplete: $WordToComplete\"\n\n\n # Check for flag with equal sign\n $IsEqualFlag = ($WordToComplete -Like \"--*=*\" )\n if ( $IsEqualFlag ) {\n __@@NAME@@_debug \"Completing equal sign flag\"\n # Remove the flag part\n $Flag,$WordToComplete = $WordToComplete.Split(\"=\",2)\n }\n\n if ( $WordToComplete -eq \"\" -And ( -Not $IsEqualFlag )) {\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 # PowerShell 7.2+ changed the way how the arguments are passed to executables,\n # so for pre-7.2 or when Legacy argument passing is enabled we need to use\n # `\"`\" to pass an empty argument, a \"\" or '' does not work!!!\n if ($PSVersionTable.PsVersion -lt [version]'7.2.0' -or\n ($PSVersionTable.PsVersion -lt [version]'7.3.0' -and -not [ExperimentalFeature]::IsEnabled(\"PSNativeCommandArgumentPassing\")) -or\n (($PSVersionTable.PsVersion -ge [version]'7.3.0' -or [ExperimentalFeature]::IsEnabled(\"PSNativeCommandArgumentPassing\")) -and\n $PSNativeCommandArgumentPassing -eq 'Legacy')) {\n $RequestComp=\"$RequestComp\" + ' `\"`\"'\n } else {\n $RequestComp=\"$RequestComp\" + ' \"\"'\n }\n }\n\n __@@NAME@@_debug \"Calling $RequestComp\"\n # First disable ActiveHelp which is not supported for Powershell\n ${env:@@ACTIVE_HELP_VAR@@}=0\n\n #call the command store the output in $out and redirect stderr and stdout to null\n # $Out is an array contains each line per element\n Invoke-Expression -OutVariable out \"$RequestComp\" 2>&1 | Out-Null\n\n # get directive from last line\n [int]$Directive = $Out[-1].TrimStart(':')\n if ($Directive -eq \"\") {\n # There is no directive specified\n $Directive = 0\n }\n __@@NAME@@_debug \"The completion directive is: $Directive\"\n\n # remove directive (last element) from out\n $Out = $Out | Where-Object { $_ -ne $Out[-1] }\n __@@NAME@@_debug \"The completions are: $Out\"\n\n if (($Directive -band $ShellCompDirectiveError) -ne 0 ) {\n # Error code. No completion.\n __@@NAME@@_debug \"Received error from custom completion go code\"\n return\n }\n\n $Longest = 0\n [Array]$Values = $Out | ForEach-Object {\n #Split the output in name and description\n $Name, $Description = $_.Split(\"`t\",2)\n __@@NAME@@_debug \"Name: $Name Description: $Description\"\n\n # Look for the longest completion so that we can format things nicely\n if ($Longest -lt $Name.Length) {\n $Longest = $Name.Length\n }\n\n # Set the description to a one space string if there is none set.\n # This is needed because the CompletionResult does not accept an empty string as argument\n if (-Not $Description) {\n $Description = \" \"\n }\n New-Object -TypeName PSCustomObject -Property @{\n Name = \"$Name\"\n Description = \"$Description\"\n }\n }\n\n\n $Space = \" \"\n if (($Directive -band $ShellCompDirectiveNoSpace) -ne 0 ) {\n # remove the space here\n __@@NAME@@_debug \"ShellCompDirectiveNoSpace is called\"\n $Space = \"\"\n }\n\n if ((($Directive -band $ShellCompDirectiveFilterFileExt) -ne 0 ) -or\n (($Directive -band $ShellCompDirectiveFilterDirs) -ne 0 )) {\n __@@NAME@@_debug \"ShellCompDirectiveFilterFileExt ShellCompDirectiveFilterDirs are not supported\"\n\n # return here to prevent the completion of the extensions\n return\n }\n\n $Values = $Values | Where-Object {\n # filter the result\n $_.Name -like \"$WordToComplete*\"\n\n # Join the flag back if we have an equal sign flag\n if ( $IsEqualFlag ) {\n __@@NAME@@_debug \"Join the equal sign flag back to the completion value\"\n $_.Name = $Flag + \"=\" + $_.Name\n }\n }\n\n # we sort the values in ascending order by name if keep order isn't passed\n if (($Directive -band $ShellCompDirectiveKeepOrder) -eq 0 ) {\n $Values = $Values | Sort-Object -Property Name\n }\n\n if (($Directive -band $ShellCompDirectiveNoFileComp) -ne 0 ) {\n __@@NAME@@_debug \"ShellCompDirectiveNoFileComp is called\"\n\n if ($Values.Length -eq 0) {\n # Just print an empty string here so the\n # shell does not start to complete paths.\n # We cannot use CompletionResult here because\n # it does not accept an empty string as argument.\n \"\"\n return\n }\n }\n\n # Get the current mode\n $Mode = (Get-PSReadLineKeyHandler | Where-Object {$_.Key -eq \"Tab\" }).Function\n __@@NAME@@_debug \"Mode: $Mode\"\n\n $Values | ForEach-Object {\n\n # store temporary because switch will overwrite $_\n $comp = $_\n\n # PowerShell supports three different completion modes\n # - TabCompleteNext (default windows style - on each key press the next option is displayed)\n # - Complete (works like bash)\n # - MenuComplete (works like zsh)\n # You set the mode with Set-PSReadLineKeyHandler -Key Tab -Function <mode>\n\n # CompletionResult Arguments:\n # 1) CompletionText text to be used as the auto completion result\n # 2) ListItemText text to be displayed in the suggestion list\n # 3) ResultType type of completion result\n # 4) ToolTip text for the tooltip with details about the object\n\n switch ($Mode) {\n\n # bash like\n \"Complete\" {\n\n if ($Values.Length -eq 1) {\n __@@NAME@@_debug \"Only one completion left\"\n\n # insert space after value\n $CompletionText = $($comp.Name | __@@NAME@@_escapeStringWithSpecialChars) + $Space\n if ($ExecutionContext.SessionState.LanguageMode -eq \"FullLanguage\"){\n [System.Management.Automation.CompletionResult]::new($CompletionText, \"$($comp.Name)\", 'ParameterValue', \"$($comp.Description)\")\n } else {\n $CompletionText\n }\n\n } else {\n # Add the proper number of spaces to align the descriptions\n while($comp.Name.Length -lt $Longest) {\n $comp.Name = $comp.Name + \" \"\n }\n\n # Check for empty description and only add parentheses if needed\n if ($($comp.Description) -eq \" \" ) {\n $Description = \"\"\n } else {\n $Description = \" ($($comp.Description))\"\n }\n\n $CompletionText = \"$($comp.Name)$Description\"\n if ($ExecutionContext.SessionState.LanguageMode -eq \"FullLanguage\"){\n [System.Management.Automation.CompletionResult]::new($CompletionText, \"$($comp.Name)$Description\", 'ParameterValue', \"$($comp.Description)\")\n } else {\n $CompletionText\n }\n }\n }\n\n # zsh like\n \"MenuComplete\" {\n # insert space after value\n # MenuComplete will automatically show the ToolTip of\n # the highlighted value at the bottom of the suggestions.\n\n $CompletionText = $($comp.Name | __@@NAME@@_escapeStringWithSpecialChars) + $Space\n if ($ExecutionContext.SessionState.LanguageMode -eq \"FullLanguage\"){\n [System.Management.Automation.CompletionResult]::new($CompletionText, \"$($comp.Name)\", 'ParameterValue', \"$($comp.Description)\")\n } else {\n $CompletionText\n }\n }\n\n # TabCompleteNext and in case we get something unknown\n Default {\n # Like MenuComplete but we don't want to add a space here because\n # the user need to press space anyway to get the completion.\n # Description will not be shown because that's not possible with TabCompleteNext\n\n $CompletionText = $($comp.Name | __@@NAME@@_escapeStringWithSpecialChars)\n if ($ExecutionContext.SessionState.LanguageMode -eq \"FullLanguage\"){\n [System.Management.Automation.CompletionResult]::new($CompletionText, \"$($comp.Name)\", 'ParameterValue', \"$($comp.Description)\")\n } else {\n $CompletionText\n }\n }\n }\n\n }\n}\n\nRegister-ArgumentCompleter -CommandName '@@NAME@@' -ScriptBlock ${__@@NAME_VAR@@CompleterBlock}\n",
|
|
16
|
+
} as const;
|
|
@@ -8,6 +8,9 @@ import {
|
|
|
8
8
|
configKeysCompleter,
|
|
9
9
|
fileCompleter,
|
|
10
10
|
dirCompleter,
|
|
11
|
+
resolveCompletions,
|
|
12
|
+
directiveName,
|
|
13
|
+
ShellCompDirective,
|
|
11
14
|
type CompletionItem,
|
|
12
15
|
} from './completion-values';
|
|
13
16
|
|
|
@@ -84,7 +87,7 @@ describe('prefixedCompleter', () => {
|
|
|
84
87
|
const inner = staticValues('a', 'b');
|
|
85
88
|
const c = prefixedCompleter('env', inner);
|
|
86
89
|
const result = c.complete('');
|
|
87
|
-
expect(result).toEqual([{ value: 'env:', description: 'env
|
|
90
|
+
expect(result).toEqual([{ value: 'env:', description: 'env values' }]);
|
|
88
91
|
});
|
|
89
92
|
|
|
90
93
|
it('completes values after colon', () => {
|
|
@@ -112,47 +115,104 @@ describe('prefixedCompleter', () => {
|
|
|
112
115
|
});
|
|
113
116
|
|
|
114
117
|
describe('configKeysCompleter', () => {
|
|
115
|
-
it('returns top-level keys', () => {
|
|
118
|
+
it('returns top-level keys', async () => {
|
|
116
119
|
const c = configKeysCompleter({ name: 'x', version: '1', debug: true });
|
|
117
|
-
const items = c.complete('');
|
|
120
|
+
const items = await c.complete('');
|
|
118
121
|
const values = items.map((i: CompletionItem) => i.value);
|
|
119
122
|
expect(values).toContain('name');
|
|
120
123
|
expect(values).toContain('version');
|
|
121
124
|
expect(values).toContain('debug');
|
|
122
125
|
});
|
|
123
126
|
|
|
124
|
-
it('returns nested keys with dot notation', () => {
|
|
127
|
+
it('returns nested keys with dot notation', async () => {
|
|
125
128
|
const c = configKeysCompleter({ db: { host: 'localhost', port: 5432 } });
|
|
126
|
-
const items = c.complete('db.');
|
|
129
|
+
const items = await c.complete('db.');
|
|
127
130
|
const values = items.map((i: CompletionItem) => i.value);
|
|
128
131
|
expect(values).toContain('db.host');
|
|
129
132
|
expect(values).toContain('db.port');
|
|
130
133
|
});
|
|
131
134
|
|
|
132
|
-
it('
|
|
135
|
+
it('returns leaf keys only, lowercased', async () => {
|
|
136
|
+
const c = configKeysCompleter({ Server: { Port: 1 }, tags: ['a'] });
|
|
137
|
+
const values = (await c.complete('')).map((i: CompletionItem) => i.value);
|
|
138
|
+
expect(values).toEqual(['server.port', 'tags']);
|
|
139
|
+
expect((await c.complete('SER')).map((i: CompletionItem) => i.value))
|
|
140
|
+
.toEqual(['server.port']);
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
it('filters by prefix', async () => {
|
|
133
144
|
const c = configKeysCompleter({ name: 'x', namespace: 'y', version: '1' });
|
|
134
|
-
const items = c.complete('na');
|
|
145
|
+
const items = await c.complete('na');
|
|
135
146
|
const values = items.map((i: CompletionItem) => i.value);
|
|
136
147
|
expect(values).toEqual(['name', 'namespace']);
|
|
137
148
|
});
|
|
138
149
|
});
|
|
139
150
|
|
|
140
151
|
describe('fileCompleter', () => {
|
|
141
|
-
it('returns
|
|
152
|
+
it('returns its extensions and filters by extension', async () => {
|
|
142
153
|
const c = fileCompleter('.ts', '.js');
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
154
|
+
expect(await c.complete('')).toEqual([{ value: '.ts' }, { value: '.js' }]);
|
|
155
|
+
expect(await resolveCompletions(c, 'x')).toEqual({
|
|
156
|
+
completions: ['.ts', '.js'], directive: ShellCompDirective.FilterFileExt,
|
|
157
|
+
});
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
it('without extensions falls back to default completion', async () => {
|
|
161
|
+
expect(await resolveCompletions(fileCompleter(), '')).toEqual({
|
|
162
|
+
completions: [], directive: ShellCompDirective.Default,
|
|
163
|
+
});
|
|
147
164
|
});
|
|
148
165
|
});
|
|
149
166
|
|
|
150
167
|
describe('dirCompleter', () => {
|
|
151
|
-
it('
|
|
168
|
+
it('completes directories only', async () => {
|
|
152
169
|
const c = dirCompleter();
|
|
153
|
-
|
|
154
|
-
expect(
|
|
155
|
-
|
|
170
|
+
expect(await c.complete('')).toEqual([]);
|
|
171
|
+
expect(await resolveCompletions(c, 'src')).toEqual({
|
|
172
|
+
completions: [], directive: ShellCompDirective.FilterDirs,
|
|
173
|
+
});
|
|
174
|
+
});
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
describe('resolveCompletions', () => {
|
|
178
|
+
it('joins descriptions with a tab and completes no files', async () => {
|
|
179
|
+
const c = staticCompleter({ value: 'a', description: 'A' }, { value: 'b' });
|
|
180
|
+
expect(await resolveCompletions(c, '')).toEqual({
|
|
181
|
+
completions: ['a\tA', 'b'], directive: ShellCompDirective.NoFileComp,
|
|
182
|
+
});
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
it('turns a thrown or rejected completer into the error directive', async () => {
|
|
186
|
+
const sync = funcCompleter(() => { throw new Error('down'); });
|
|
187
|
+
const rejected = funcCompleter(async () => { throw new Error('down'); });
|
|
188
|
+
for (const c of [sync, rejected, prefixedCompleter('env', rejected)]) {
|
|
189
|
+
expect(await resolveCompletions(c, 'env:')).toEqual({
|
|
190
|
+
completions: [], directive: ShellCompDirective.Error,
|
|
191
|
+
});
|
|
192
|
+
}
|
|
193
|
+
});
|
|
194
|
+
|
|
195
|
+
it('passes the context through to the completer', async () => {
|
|
196
|
+
let seen;
|
|
197
|
+
const c = funcCompleter((_p, ctx) => { seen = ctx; return []; });
|
|
198
|
+
await resolveCompletions(c, '', { commandPath: 'deploy', args: ['x'] });
|
|
199
|
+
expect(seen).toEqual({ commandPath: 'deploy', args: ['x'] });
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
it('awaits async inner completers of prefixed', async () => {
|
|
203
|
+
const c = prefixedCompleter('env', funcCompleter(async () => [{ value: 'prod' }]));
|
|
204
|
+
expect(await resolveCompletions(c, 'env:')).toEqual({
|
|
205
|
+
completions: ['env:prod'], directive: ShellCompDirective.NoFileComp,
|
|
206
|
+
});
|
|
207
|
+
});
|
|
208
|
+
});
|
|
209
|
+
|
|
210
|
+
describe('directiveName', () => {
|
|
211
|
+
it('names cobra directives', () => {
|
|
212
|
+
expect(directiveName(0)).toBe('ShellCompDirectiveDefault');
|
|
213
|
+
expect(directiveName(4)).toBe('ShellCompDirectiveNoFileComp');
|
|
214
|
+
expect(directiveName(6)).toBe('ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp');
|
|
215
|
+
expect(directiveName(64)).toBe('ERROR: unexpected ShellCompDirective value: 64');
|
|
156
216
|
});
|
|
157
217
|
});
|
|
158
218
|
|
package/src/completion-values.ts
CHANGED
|
@@ -2,10 +2,28 @@
|
|
|
2
2
|
* @module completion-values
|
|
3
3
|
* @package @hop-top/kit
|
|
4
4
|
*
|
|
5
|
-
* Dynamic value completion
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
5
|
+
* Dynamic value completion for Commander-based CLIs. Ports Go
|
|
6
|
+
* `console/cli/completion`; behaviour is pinned by
|
|
7
|
+
* `contracts/completion-v1/completers.json`.
|
|
8
|
+
*
|
|
9
|
+
* A {@link Completer} turns the word being completed into
|
|
10
|
+
* {@link CompletionItem}s. `bindFlag` / `bindArgs` (in `completion`)
|
|
11
|
+
* attach one to a flag or to a command's positional arguments; the
|
|
12
|
+
* scripts `completion <shell>` writes call back into the program's
|
|
13
|
+
* hidden `__complete` entry point, which runs the bound completer and
|
|
14
|
+
* prints the result through {@link resolveCompletions} in cobra's wire
|
|
15
|
+
* format.
|
|
16
|
+
*
|
|
17
|
+
* Contract:
|
|
18
|
+
* - Prefix matching in static, config-key and the dimension half of
|
|
19
|
+
* prefixed completers is case-insensitive; an empty prefix returns
|
|
20
|
+
* every item. {@link funcCompleter} sees the raw prefix, unfiltered.
|
|
21
|
+
* - A completer fails by throwing (or rejecting); the bridge turns that
|
|
22
|
+
* into {@link ShellCompDirective.Error}.
|
|
23
|
+
* - {@link fileCompleter} and {@link dirCompleter} yield a directive,
|
|
24
|
+
* not suggestions: filter by extension (the extensions travel as the
|
|
25
|
+
* completions), directories only, or plain file completion when no
|
|
26
|
+
* extension is given.
|
|
9
27
|
*/
|
|
10
28
|
|
|
11
29
|
export interface CompletionItem {
|
|
@@ -13,10 +31,102 @@ export interface CompletionItem {
|
|
|
13
31
|
description?: string;
|
|
14
32
|
}
|
|
15
33
|
|
|
34
|
+
/** What a completer knows about the command line it completes. */
|
|
35
|
+
export interface CompletionContext {
|
|
36
|
+
/** Space-separated path of the command below the root; empty for the root. */
|
|
37
|
+
commandPath: string;
|
|
38
|
+
/** Positional arguments already given, flags removed. */
|
|
39
|
+
args: string[];
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** What a file completer asks the shell for. */
|
|
43
|
+
export type FileFilter =
|
|
44
|
+
| { kind: 'extensions'; extensions: string[] }
|
|
45
|
+
| { kind: 'dirs' };
|
|
46
|
+
|
|
16
47
|
export interface Completer {
|
|
17
|
-
complete(
|
|
48
|
+
complete(
|
|
49
|
+
prefix: string,
|
|
50
|
+
ctx?: CompletionContext,
|
|
51
|
+
): CompletionItem[] | Promise<CompletionItem[]>;
|
|
52
|
+
/** Set by {@link fileCompleter} and {@link dirCompleter}. */
|
|
53
|
+
readonly fileFilter?: FileFilter;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** cobra's shell directive bits, read by the scripts from the `:<n>` line. */
|
|
57
|
+
export const ShellCompDirective = {
|
|
58
|
+
Default: 0,
|
|
59
|
+
Error: 1,
|
|
60
|
+
NoSpace: 2,
|
|
61
|
+
NoFileComp: 4,
|
|
62
|
+
FilterFileExt: 8,
|
|
63
|
+
FilterDirs: 16,
|
|
64
|
+
KeepOrder: 32,
|
|
65
|
+
} as const;
|
|
66
|
+
|
|
67
|
+
/** cobra's name for a directive, as printed on stderr after a request. */
|
|
68
|
+
export function directiveName(d: number): string {
|
|
69
|
+
if (d >= 64) return `ERROR: unexpected ShellCompDirective value: ${d}`;
|
|
70
|
+
const names: [number, string][] = [
|
|
71
|
+
[ShellCompDirective.Error, 'ShellCompDirectiveError'],
|
|
72
|
+
[ShellCompDirective.NoSpace, 'ShellCompDirectiveNoSpace'],
|
|
73
|
+
[ShellCompDirective.NoFileComp, 'ShellCompDirectiveNoFileComp'],
|
|
74
|
+
[ShellCompDirective.FilterFileExt, 'ShellCompDirectiveFilterFileExt'],
|
|
75
|
+
[ShellCompDirective.FilterDirs, 'ShellCompDirectiveFilterDirs'],
|
|
76
|
+
[ShellCompDirective.KeepOrder, 'ShellCompDirectiveKeepOrder'],
|
|
77
|
+
];
|
|
78
|
+
const set = names.filter(([bit]) => (d & bit) === bit).map(([, n]) => n);
|
|
79
|
+
return set.length ? set.join(', ') : 'ShellCompDirectiveDefault';
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Completions in wire form plus the directive. */
|
|
83
|
+
export interface ResolvedCompletions {
|
|
84
|
+
/** `value`, or `value\tdescription` when there is one. */
|
|
85
|
+
completions: string[];
|
|
86
|
+
directive: number;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Runs `c` for `toComplete` and converts the result to the shell wire
|
|
91
|
+
* format: values with any description joined by a tab, plus the
|
|
92
|
+
* directive (no file completion on success, error when `c` fails).
|
|
93
|
+
*/
|
|
94
|
+
export async function resolveCompletions(
|
|
95
|
+
c: Completer,
|
|
96
|
+
toComplete: string,
|
|
97
|
+
ctx: CompletionContext = { commandPath: '', args: [] },
|
|
98
|
+
): Promise<ResolvedCompletions> {
|
|
99
|
+
const f = c.fileFilter;
|
|
100
|
+
if (f?.kind === 'dirs') {
|
|
101
|
+
return { completions: [], directive: ShellCompDirective.FilterDirs };
|
|
102
|
+
}
|
|
103
|
+
if (f?.kind === 'extensions') {
|
|
104
|
+
// An empty filter list would filter every candidate out.
|
|
105
|
+
return f.extensions.length === 0
|
|
106
|
+
? { completions: [], directive: ShellCompDirective.Default }
|
|
107
|
+
: { completions: [...f.extensions], directive: ShellCompDirective.FilterFileExt };
|
|
108
|
+
}
|
|
109
|
+
try {
|
|
110
|
+
const items = await c.complete(toComplete, ctx);
|
|
111
|
+
return {
|
|
112
|
+
completions: items.map(withDescription),
|
|
113
|
+
directive: ShellCompDirective.NoFileComp,
|
|
114
|
+
};
|
|
115
|
+
} catch {
|
|
116
|
+
return { completions: [], directive: ShellCompDirective.Error };
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** `value`, or `value\tdescription` when there is one. */
|
|
121
|
+
export function withDescription(i: CompletionItem): string {
|
|
122
|
+
return i.description ? `${i.value}\t${i.description}` : i.value;
|
|
18
123
|
}
|
|
19
124
|
|
|
125
|
+
/**
|
|
126
|
+
* Maps flag names and argument positions to completers, for sharing
|
|
127
|
+
* completers across a command tree (Go `Registry`). A lookup table
|
|
128
|
+
* only: `bindFlag` / `bindArgs` wire a completer into completion.
|
|
129
|
+
*/
|
|
20
130
|
export class CompletionRegistry {
|
|
21
131
|
private flags = new Map<string, Completer>();
|
|
22
132
|
private args = new Map<string, Completer>();
|
|
@@ -38,12 +148,12 @@ export class CompletionRegistry {
|
|
|
38
148
|
}
|
|
39
149
|
}
|
|
40
150
|
|
|
41
|
-
/** Filter items by case-insensitive prefix match. */
|
|
151
|
+
/** Filter items by case-insensitive prefix match; keeps duplicates. */
|
|
42
152
|
function filterByPrefix(
|
|
43
153
|
items: CompletionItem[],
|
|
44
154
|
prefix: string,
|
|
45
155
|
): CompletionItem[] {
|
|
46
|
-
if (!prefix) return items;
|
|
156
|
+
if (!prefix) return [...items];
|
|
47
157
|
const lp = prefix.toLowerCase();
|
|
48
158
|
return items.filter(i => i.value.toLowerCase().startsWith(lp));
|
|
49
159
|
}
|
|
@@ -65,109 +175,103 @@ export function staticValues(...values: string[]): Completer {
|
|
|
65
175
|
return staticCompleter(...items);
|
|
66
176
|
}
|
|
67
177
|
|
|
68
|
-
/**
|
|
178
|
+
/**
|
|
179
|
+
* Completer backed by a callback. The callback sees the raw prefix;
|
|
180
|
+
* nothing is filtered for it. Throw (or reject) to fail.
|
|
181
|
+
*/
|
|
69
182
|
export function funcCompleter(
|
|
70
|
-
fn: (
|
|
183
|
+
fn: (
|
|
184
|
+
prefix: string,
|
|
185
|
+
ctx: CompletionContext,
|
|
186
|
+
) => CompletionItem[] | Promise<CompletionItem[]>,
|
|
71
187
|
): Completer {
|
|
72
|
-
return {
|
|
188
|
+
return {
|
|
189
|
+
complete(prefix, ctx = { commandPath: '', args: [] }) {
|
|
190
|
+
return fn(prefix, ctx);
|
|
191
|
+
},
|
|
192
|
+
};
|
|
73
193
|
}
|
|
74
194
|
|
|
75
195
|
/**
|
|
76
|
-
* Completer for dimensioned values like `env:prod`.
|
|
77
|
-
*
|
|
78
|
-
*
|
|
196
|
+
* Completer for dimensioned values like `env:prod`. While no colon is
|
|
197
|
+
* typed it suggests `dimension:` (matched case-insensitively); after
|
|
198
|
+
* the first colon it delegates the rest to `values` and re-prepends
|
|
199
|
+
* the declared `dimension:`.
|
|
79
200
|
*/
|
|
80
201
|
export function prefixedCompleter(
|
|
81
202
|
dimension: string,
|
|
82
203
|
values: Completer,
|
|
83
204
|
): Completer {
|
|
205
|
+
const lower = dimension.toLowerCase();
|
|
206
|
+
const prepend = (items: CompletionItem[]) =>
|
|
207
|
+
items.map(i => {
|
|
208
|
+
const v = `${dimension}:${i.value}`;
|
|
209
|
+
return i.description ? { value: v, description: i.description } : { value: v };
|
|
210
|
+
});
|
|
84
211
|
return {
|
|
85
|
-
complete(prefix
|
|
212
|
+
complete(prefix, ctx) {
|
|
86
213
|
const colonIdx = prefix.indexOf(':');
|
|
87
214
|
if (colonIdx < 0) {
|
|
88
|
-
|
|
89
|
-
return
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
const dim = prefix.slice(0, colonIdx);
|
|
93
|
-
if (dim !== dimension) return [];
|
|
94
|
-
|
|
95
|
-
const valPrefix = prefix.slice(colonIdx + 1);
|
|
96
|
-
const inner = values.complete(valPrefix);
|
|
97
|
-
if (Array.isArray(inner)) {
|
|
98
|
-
return inner.map(i => ({
|
|
99
|
-
value: `${dimension}:${i.value}`,
|
|
100
|
-
description: i.description,
|
|
101
|
-
}));
|
|
215
|
+
const dim = `${dimension}:`;
|
|
216
|
+
return dim.toLowerCase().startsWith(prefix.toLowerCase())
|
|
217
|
+
? [{ value: dim, description: `${dimension} values` }]
|
|
218
|
+
: [];
|
|
102
219
|
}
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
value: `${dimension}:${i.value}`,
|
|
107
|
-
description: i.description,
|
|
108
|
-
})),
|
|
109
|
-
);
|
|
220
|
+
if (prefix.slice(0, colonIdx).toLowerCase() !== lower) return [];
|
|
221
|
+
const inner = values.complete(prefix.slice(colonIdx + 1), ctx);
|
|
222
|
+
return Array.isArray(inner) ? prepend(inner) : inner.then(prepend);
|
|
110
223
|
},
|
|
111
224
|
};
|
|
112
225
|
}
|
|
113
226
|
|
|
114
|
-
/**
|
|
115
|
-
function
|
|
116
|
-
obj: Record<string, any>,
|
|
117
|
-
prefix = '',
|
|
118
|
-
): string[] {
|
|
119
|
-
const keys: string[] = [];
|
|
227
|
+
/** The dotted leaf keys of a config tree, lowercased like viper's AllKeys. */
|
|
228
|
+
function leafKeys(obj: Record<string, unknown>, prefix: string, out: Set<string>): void {
|
|
120
229
|
for (const [k, v] of Object.entries(obj)) {
|
|
121
|
-
const full = prefix ? `${prefix}.${k}` : k;
|
|
122
|
-
keys.push(full);
|
|
230
|
+
const full = prefix ? `${prefix}.${k.toLowerCase()}` : k.toLowerCase();
|
|
123
231
|
if (v != null && typeof v === 'object' && !Array.isArray(v)) {
|
|
124
|
-
|
|
232
|
+
leafKeys(v as Record<string, unknown>, full, out);
|
|
233
|
+
} else {
|
|
234
|
+
out.add(full);
|
|
125
235
|
}
|
|
126
236
|
}
|
|
127
|
-
return keys;
|
|
128
237
|
}
|
|
129
238
|
|
|
130
|
-
/**
|
|
239
|
+
/**
|
|
240
|
+
* Completer that suggests config keys: the dotted leaf keys of
|
|
241
|
+
* `config`, lowercased, matched case-insensitively.
|
|
242
|
+
*/
|
|
131
243
|
export function configKeysCompleter(
|
|
132
|
-
config: Record<string,
|
|
244
|
+
config: Record<string, unknown>,
|
|
133
245
|
): Completer {
|
|
134
246
|
return {
|
|
135
247
|
complete(prefix: string) {
|
|
136
|
-
const
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
prefix,
|
|
140
|
-
);
|
|
248
|
+
const keys = new Set<string>();
|
|
249
|
+
leafKeys(config, '', keys);
|
|
250
|
+
return filterByPrefix([...keys].map(k => ({ value: k })), prefix);
|
|
141
251
|
},
|
|
142
252
|
};
|
|
143
253
|
}
|
|
144
254
|
|
|
145
255
|
/**
|
|
146
|
-
* Completer that
|
|
147
|
-
*
|
|
148
|
-
*
|
|
256
|
+
* Completer that asks the shell for files with these extensions (e.g.
|
|
257
|
+
* `.yaml`); none means any file. Its items are the extensions, which
|
|
258
|
+
* travel as the completions of a filter-by-extension directive.
|
|
149
259
|
*/
|
|
150
260
|
export function fileCompleter(...extensions: string[]): Completer {
|
|
151
|
-
const desc = extensions.length
|
|
152
|
-
? `Files: ${extensions.join(', ')}`
|
|
153
|
-
: 'Files';
|
|
154
261
|
return {
|
|
262
|
+
fileFilter: { kind: 'extensions', extensions: [...extensions] },
|
|
155
263
|
complete() {
|
|
156
|
-
return
|
|
157
|
-
{
|
|
158
|
-
value: '__file__',
|
|
159
|
-
description: desc,
|
|
160
|
-
},
|
|
161
|
-
];
|
|
264
|
+
return extensions.map(e => ({ value: e }));
|
|
162
265
|
},
|
|
163
266
|
};
|
|
164
267
|
}
|
|
165
268
|
|
|
166
|
-
/** Completer that
|
|
269
|
+
/** Completer that asks the shell for directories only. */
|
|
167
270
|
export function dirCompleter(): Completer {
|
|
168
271
|
return {
|
|
272
|
+
fileFilter: { kind: 'dirs' },
|
|
169
273
|
complete() {
|
|
170
|
-
return [
|
|
274
|
+
return [];
|
|
171
275
|
},
|
|
172
276
|
};
|
|
173
277
|
}
|