@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
package/src/completion.ts
CHANGED
|
@@ -2,157 +2,803 @@
|
|
|
2
2
|
* @module completion
|
|
3
3
|
* @package @hop-top/kit
|
|
4
4
|
*
|
|
5
|
-
* Shell completion
|
|
6
|
-
*
|
|
7
|
-
*
|
|
5
|
+
* Shell completion for Commander-based CLIs, in cobra's protocol so a
|
|
6
|
+
* TS kit CLI completes like a Go or Rust one
|
|
7
|
+
* (`contracts/completion-v1`, Go canonical):
|
|
8
|
+
*
|
|
9
|
+
* - `completion bash|zsh|fish|powershell [--no-descriptions]` writes
|
|
10
|
+
* cobra v1.10.2's scripts byte for byte ({@link completionCommand}).
|
|
11
|
+
* - The scripts call back into the hidden `__complete` /
|
|
12
|
+
* `__completeNoDesc` entry point. {@link installCompletionRequest}
|
|
13
|
+
* (done by `createCLI` and {@link completionCommand}) answers it
|
|
14
|
+
* before commander parses, so no hook or action runs on tab. It walks
|
|
15
|
+
* the live command tree: subcommands, aliases, each command's own and
|
|
16
|
+
* inherited flags, choices and the completers bound with
|
|
17
|
+
* {@link bindFlag} / {@link bindArgs}.
|
|
18
|
+
*
|
|
19
|
+
* Wire format: one completion per line (`value`, or
|
|
20
|
+
* `value<TAB>description`), then `:<directive>`; stderr carries
|
|
21
|
+
* `Completion ended with directive: <name>`. Exit code 0.
|
|
22
|
+
*
|
|
23
|
+
* Commander has no public accessor for a few facts read here; they are
|
|
24
|
+
* typed locally in {@link CommanderInternals} (commander 15).
|
|
8
25
|
*/
|
|
9
26
|
|
|
10
|
-
import {
|
|
27
|
+
import { appendFileSync } from 'node:fs';
|
|
28
|
+
import { Command, Option } from 'commander';
|
|
29
|
+
|
|
30
|
+
import { SCRIPT_TEMPLATES } from './completion-scripts';
|
|
31
|
+
import {
|
|
32
|
+
type Completer,
|
|
33
|
+
type CompletionContext,
|
|
34
|
+
directiveName,
|
|
35
|
+
funcCompleter,
|
|
36
|
+
resolveCompletions,
|
|
37
|
+
ShellCompDirective,
|
|
38
|
+
} from './completion-values';
|
|
39
|
+
|
|
40
|
+
/** Name of the hidden command a shell script calls for completions. */
|
|
41
|
+
export const REQUEST_CMD = '__complete';
|
|
42
|
+
/** Name of the hidden command that returns completions without descriptions. */
|
|
43
|
+
export const NO_DESC_REQUEST_CMD = '__completeNoDesc';
|
|
44
|
+
|
|
45
|
+
/** A shell `completion` writes a script for. */
|
|
46
|
+
export type Shell = 'bash' | 'zsh' | 'fish' | 'powershell';
|
|
47
|
+
/** Every shell, in the order the `completion` command lists them. */
|
|
48
|
+
export const SHELLS: readonly Shell[] = ['bash', 'zsh', 'fish', 'powershell'];
|
|
11
49
|
|
|
12
|
-
/**
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
50
|
+
/** commander 15 private members this module reads (no public accessor). */
|
|
51
|
+
interface CommanderInternals {
|
|
52
|
+
_hidden?: boolean;
|
|
53
|
+
_enablePositionalOptions?: boolean;
|
|
54
|
+
_versionOptionName?: string;
|
|
55
|
+
_getHelpOption?(): Option | null;
|
|
17
56
|
}
|
|
18
57
|
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
return cmd.options.map(o => o.long).filter(Boolean) as string[];
|
|
58
|
+
function internals(c: Command): CommanderInternals {
|
|
59
|
+
return c as unknown as CommanderInternals;
|
|
22
60
|
}
|
|
23
61
|
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
62
|
+
// Per-command state lives on the command under registry symbols, so two
|
|
63
|
+
// copies of this module (separate bundles) still share it.
|
|
64
|
+
const FLAG_COMPLETERS = Symbol.for('@hop-top/kit/completion/flags');
|
|
65
|
+
const ARGS_COMPLETER = Symbol.for('@hop-top/kit/completion/args');
|
|
66
|
+
const ROOT_ALIASES = Symbol.for('@hop-top/kit/completion/aliases');
|
|
67
|
+
const BUILTIN = Symbol.for('@hop-top/kit/completion/builtin');
|
|
68
|
+
const INSTALLED = Symbol.for('@hop-top/kit/completion/installed');
|
|
30
69
|
|
|
31
|
-
|
|
32
|
-
|
|
70
|
+
type Tagged = Command & {
|
|
71
|
+
[FLAG_COMPLETERS]?: Map<string, Completer>;
|
|
72
|
+
[ARGS_COMPLETER]?: Completer;
|
|
73
|
+
[ROOT_ALIASES]?: Map<string, string>;
|
|
74
|
+
[BUILTIN]?: boolean;
|
|
75
|
+
[INSTALLED]?: boolean;
|
|
76
|
+
};
|
|
33
77
|
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
78
|
+
// ---------------------------------------------------------------------------
|
|
79
|
+
// Scripts
|
|
80
|
+
// ---------------------------------------------------------------------------
|
|
37
81
|
|
|
38
|
-
|
|
82
|
+
/** cobra's `<PROGRAM>_<SUFFIX>` variable name. */
|
|
83
|
+
function configEnvVar(name: string, suffix: string): string {
|
|
84
|
+
return `${name}_${suffix}`.toUpperCase().replace(/[^A-Z0-9_]/g, '_');
|
|
39
85
|
}
|
|
40
86
|
|
|
41
|
-
|
|
42
|
-
|
|
87
|
+
/** The `completion <shell>` script for program `name`, cobra's byte for byte. */
|
|
88
|
+
export function renderCompletionScript(
|
|
89
|
+
shell: Shell,
|
|
90
|
+
name: string,
|
|
91
|
+
includeDescriptions = true,
|
|
92
|
+
): string {
|
|
93
|
+
const vars: Record<string, string> = {
|
|
94
|
+
NAME_PAD36: name.padEnd(36),
|
|
95
|
+
// Shell identifiers cannot hold '-' or ':'.
|
|
96
|
+
NAME_VAR: name.replace(/[-:]/g, '_'),
|
|
97
|
+
ACTIVE_HELP_VAR: configEnvVar(name, 'ACTIVE_HELP'),
|
|
98
|
+
COMP_CMD: includeDescriptions ? REQUEST_CMD : NO_DESC_REQUEST_CMD,
|
|
99
|
+
NAME: name,
|
|
100
|
+
};
|
|
101
|
+
return SCRIPT_TEMPLATES[shell].replace(
|
|
102
|
+
/@@(NAME_PAD36|NAME_VAR|ACTIVE_HELP_VAR|COMP_CMD|NAME)@@/g,
|
|
103
|
+
(_m, k: string) => vars[k]!,
|
|
104
|
+
);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Generate a bash completion script (cobra V2; needs bash-completion). */
|
|
108
|
+
export function generateBashCompletion(program: Command, includeDescriptions = true): string {
|
|
109
|
+
return renderCompletionScript('bash', program.name(), includeDescriptions);
|
|
43
110
|
}
|
|
44
111
|
|
|
45
112
|
/** Generate a zsh completion script for the given program. */
|
|
46
|
-
export function generateZshCompletion(program: Command): string {
|
|
47
|
-
|
|
48
|
-
const cmds = collectCommands(program);
|
|
49
|
-
const flags = collectFlags(program);
|
|
50
|
-
|
|
51
|
-
const cmdEntries = cmds
|
|
52
|
-
.map(c => {
|
|
53
|
-
const sub = program.commands.find(
|
|
54
|
-
s => s.name() === c || s.aliases().includes(c),
|
|
55
|
-
);
|
|
56
|
-
const desc = sub?.description() ?? '';
|
|
57
|
-
return ` '${c}:${desc}'`;
|
|
58
|
-
})
|
|
59
|
-
.join('\n');
|
|
60
|
-
|
|
61
|
-
const flagEntries = flags
|
|
62
|
-
.map(f => ` '${f}[${f}]'`)
|
|
63
|
-
.join('\n');
|
|
64
|
-
|
|
65
|
-
return `#compdef ${name}
|
|
66
|
-
# eval "$(${name} completion zsh)"
|
|
67
|
-
|
|
68
|
-
_${name}() {
|
|
69
|
-
local -a commands flags
|
|
70
|
-
|
|
71
|
-
commands=(
|
|
72
|
-
${cmdEntries}
|
|
73
|
-
)
|
|
74
|
-
|
|
75
|
-
flags=(
|
|
76
|
-
${flagEntries}
|
|
77
|
-
)
|
|
78
|
-
|
|
79
|
-
_arguments -s \\
|
|
80
|
-
'1:command:->cmds' \\
|
|
81
|
-
'*::flags:->flags'
|
|
82
|
-
|
|
83
|
-
case "$state" in
|
|
84
|
-
cmds)
|
|
85
|
-
_describe -t commands 'commands' commands
|
|
86
|
-
;;
|
|
87
|
-
flags)
|
|
88
|
-
_describe -t flags 'flags' flags
|
|
89
|
-
;;
|
|
90
|
-
esac
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
compdef _${name} ${name}
|
|
94
|
-
`;
|
|
113
|
+
export function generateZshCompletion(program: Command, includeDescriptions = true): string {
|
|
114
|
+
return renderCompletionScript('zsh', program.name(), includeDescriptions);
|
|
95
115
|
}
|
|
96
116
|
|
|
97
117
|
/** Generate a fish completion script for the given program. */
|
|
98
|
-
export function generateFishCompletion(program: Command): string {
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
const flags = collectFlags(program);
|
|
102
|
-
|
|
103
|
-
const lines = [
|
|
104
|
-
`# fish completion for ${name}`,
|
|
105
|
-
`# ${name} completion fish | source`,
|
|
106
|
-
'',
|
|
107
|
-
];
|
|
118
|
+
export function generateFishCompletion(program: Command, includeDescriptions = true): string {
|
|
119
|
+
return renderCompletionScript('fish', program.name(), includeDescriptions);
|
|
120
|
+
}
|
|
108
121
|
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
`-a '${c}' -d '${desc}'`
|
|
117
|
-
);
|
|
118
|
-
}
|
|
122
|
+
/** Generate a PowerShell completion script for the given program. */
|
|
123
|
+
export function generatePowerShellCompletion(
|
|
124
|
+
program: Command,
|
|
125
|
+
includeDescriptions = true,
|
|
126
|
+
): string {
|
|
127
|
+
return renderCompletionScript('powershell', program.name(), includeDescriptions);
|
|
128
|
+
}
|
|
119
129
|
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
130
|
+
function shellHelp(sh: Shell, p: string): string {
|
|
131
|
+
switch (sh) {
|
|
132
|
+
case 'bash':
|
|
133
|
+
return `
|
|
134
|
+
This script depends on the 'bash-completion' package.
|
|
135
|
+
If it is not installed already, you can install it via your OS's package manager.
|
|
136
|
+
|
|
137
|
+
To load completions in your current shell session:
|
|
138
|
+
|
|
139
|
+
\tsource <(${p} completion bash)
|
|
140
|
+
|
|
141
|
+
To load completions for every new session, execute once:
|
|
142
|
+
|
|
143
|
+
#### Linux:
|
|
144
|
+
|
|
145
|
+
\t${p} completion bash > /etc/bash_completion.d/${p}
|
|
146
|
+
|
|
147
|
+
#### macOS:
|
|
126
148
|
|
|
127
|
-
|
|
128
|
-
|
|
149
|
+
\t${p} completion bash > $(brew --prefix)/etc/bash_completion.d/${p}
|
|
150
|
+
|
|
151
|
+
You will need to start a new shell for this setup to take effect.
|
|
152
|
+
`;
|
|
153
|
+
case 'zsh':
|
|
154
|
+
return `
|
|
155
|
+
If shell completion is not already enabled in your environment you will need
|
|
156
|
+
to enable it. You can execute the following once:
|
|
157
|
+
|
|
158
|
+
\techo "autoload -U compinit; compinit" >> ~/.zshrc
|
|
159
|
+
|
|
160
|
+
To load completions in your current shell session:
|
|
161
|
+
|
|
162
|
+
\tsource <(${p} completion zsh)
|
|
163
|
+
|
|
164
|
+
To load completions for every new session, execute once:
|
|
165
|
+
|
|
166
|
+
#### Linux:
|
|
167
|
+
|
|
168
|
+
\t${p} completion zsh > "\${fpath[1]}/_${p}"
|
|
169
|
+
|
|
170
|
+
#### macOS:
|
|
171
|
+
|
|
172
|
+
\t${p} completion zsh > $(brew --prefix)/share/zsh/site-functions/_${p}
|
|
173
|
+
|
|
174
|
+
You will need to start a new shell for this setup to take effect.
|
|
175
|
+
`;
|
|
176
|
+
case 'fish':
|
|
177
|
+
return `
|
|
178
|
+
To load completions in your current shell session:
|
|
179
|
+
|
|
180
|
+
\t${p} completion fish | source
|
|
181
|
+
|
|
182
|
+
To load completions for every new session, execute once:
|
|
183
|
+
|
|
184
|
+
\t${p} completion fish > ~/.config/fish/completions/${p}.fish
|
|
185
|
+
|
|
186
|
+
You will need to start a new shell for this setup to take effect.
|
|
187
|
+
`;
|
|
188
|
+
case 'powershell':
|
|
189
|
+
return `
|
|
190
|
+
To load completions in your current shell session:
|
|
191
|
+
|
|
192
|
+
\t${p} completion powershell | Out-String | Invoke-Expression
|
|
193
|
+
|
|
194
|
+
To load completions for every new session, add the output of the above command
|
|
195
|
+
to your powershell profile.
|
|
196
|
+
`;
|
|
197
|
+
}
|
|
129
198
|
}
|
|
130
199
|
|
|
200
|
+
/** Completes nothing and no files: cobra's `NoFileCompletions`. */
|
|
201
|
+
const NO_FILE_COMPLETIONS = funcCompleter(() => []);
|
|
202
|
+
|
|
131
203
|
/**
|
|
132
|
-
*
|
|
133
|
-
*
|
|
204
|
+
* cobra's `completion` command: `completion bash|zsh|fish|powershell
|
|
205
|
+
* [--no-descriptions]`, each printing the script to stdout. Add it to
|
|
206
|
+
* the program (kit puts it in the hidden `management` group). It also
|
|
207
|
+
* installs the `__complete` entry point on `program`.
|
|
134
208
|
*/
|
|
135
209
|
export function completionCommand(program: Command): Command {
|
|
210
|
+
installCompletionRequest(program);
|
|
136
211
|
const cmd = new Command('completion')
|
|
137
|
-
.description('Generate
|
|
212
|
+
.description('Generate the autocompletion script for the specified shell');
|
|
213
|
+
(cmd as Tagged)[BUILTIN] = true;
|
|
214
|
+
bindArgs(cmd, NO_FILE_COMPLETIONS);
|
|
138
215
|
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
216
|
+
for (const sh of SHELLS) {
|
|
217
|
+
const leaf = cmd.command(sh)
|
|
218
|
+
.description(`Generate the autocompletion script for ${sh}`)
|
|
219
|
+
.option('--no-descriptions', 'disable completion descriptions')
|
|
220
|
+
.addHelpText('after', shellHelp(sh, program.name()))
|
|
221
|
+
.action((opts: { descriptions?: boolean }) => {
|
|
222
|
+
process.stdout.write(
|
|
223
|
+
renderCompletionScript(sh, program.name(), opts.descriptions !== false),
|
|
224
|
+
);
|
|
225
|
+
});
|
|
226
|
+
bindArgs(leaf, NO_FILE_COMPLETIONS);
|
|
227
|
+
}
|
|
228
|
+
return cmd;
|
|
229
|
+
}
|
|
144
230
|
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
231
|
+
// ---------------------------------------------------------------------------
|
|
232
|
+
// Binding
|
|
233
|
+
// ---------------------------------------------------------------------------
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* Binds `completer` as the value completion of `cmd`'s own flag `flag`
|
|
237
|
+
* (long name, with or without `--`). An unknown flag is silent and the
|
|
238
|
+
* first binding wins, as with cobra's `RegisterFlagCompletionFunc`. A
|
|
239
|
+
* flag subcommands inherit is bound on the command declaring it.
|
|
240
|
+
*/
|
|
241
|
+
export function bindFlag(cmd: Command, flag: string, completer: Completer): void {
|
|
242
|
+
const name = flag.replace(/^--?/, '');
|
|
243
|
+
if (!cmd.options.some(o => o.long === `--${name}`)) return;
|
|
244
|
+
const t = cmd as Tagged;
|
|
245
|
+
const m = (t[FLAG_COMPLETERS] ??= new Map());
|
|
246
|
+
if (!m.has(name)) m.set(name, completer);
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** Binds `completer` as the completion of `cmd`'s positional arguments; replaces an earlier binding. */
|
|
250
|
+
export function bindArgs(cmd: Command, completer: Completer): void {
|
|
251
|
+
(cmd as Tagged)[ARGS_COMPLETER] = completer;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* Records `name` as a root-level alias of the command at `target` (a
|
|
256
|
+
* space-separated path), so root argument completion offers it as
|
|
257
|
+
* `name<TAB>alias for <target>`, and a root subcommand named `name`
|
|
258
|
+
* completes as a flagless stand-in. `bridgeAliases` calls this for
|
|
259
|
+
* every alias but a visible or custom-dispatch proxy, which completes
|
|
260
|
+
* as an ordinary subcommand.
|
|
261
|
+
*/
|
|
262
|
+
export function registerRootAlias(root: Command, name: string, target: string): void {
|
|
263
|
+
const t = root as Tagged;
|
|
264
|
+
(t[ROOT_ALIASES] ??= new Map()).set(name, target.trim().split(/\s+/).join(' '));
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
// ---------------------------------------------------------------------------
|
|
268
|
+
// Request entry point
|
|
269
|
+
// ---------------------------------------------------------------------------
|
|
270
|
+
|
|
271
|
+
/** Where a request writes. */
|
|
272
|
+
export interface CompletionIO {
|
|
273
|
+
out(s: string): void;
|
|
274
|
+
err(s: string): void;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
const stdio: CompletionIO = {
|
|
278
|
+
out: s => { process.stdout.write(s); },
|
|
279
|
+
err: s => { process.stderr.write(s); },
|
|
280
|
+
};
|
|
281
|
+
|
|
282
|
+
type ParseOptions = { from?: string };
|
|
283
|
+
|
|
284
|
+
/** The user words of `argv`, as commander's `_prepareUserArgs` finds them. */
|
|
285
|
+
function userArgs(argv: readonly string[] | undefined, opts?: ParseOptions): string[] | null {
|
|
286
|
+
let from = opts?.from;
|
|
287
|
+
if (argv === undefined && from === undefined) {
|
|
288
|
+
if (process.versions?.electron) from = 'electron';
|
|
289
|
+
const ea = process.execArgv ?? [];
|
|
290
|
+
if (['-e', '--eval', '-p', '--print'].some(f => ea.includes(f))) from = 'eval';
|
|
291
|
+
}
|
|
292
|
+
const a = argv ?? process.argv;
|
|
293
|
+
switch (from) {
|
|
294
|
+
case undefined:
|
|
295
|
+
case 'node': return a.slice(2);
|
|
296
|
+
case 'electron': return (process as { defaultApp?: boolean }).defaultApp ? a.slice(2) : a.slice(1);
|
|
297
|
+
case 'user': return a.slice(0);
|
|
298
|
+
case 'eval': return a.slice(1);
|
|
299
|
+
default: return null;
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
async function serve(program: Command, words: string[], noDesc: boolean): Promise<void> {
|
|
304
|
+
if (words.length === 0) {
|
|
305
|
+
stdio.err(`Error: requires at least 1 arg(s), only received 0\n`);
|
|
306
|
+
process.exitCode = 1;
|
|
307
|
+
return;
|
|
308
|
+
}
|
|
309
|
+
try {
|
|
310
|
+
await completeRequest(program, words, noDesc);
|
|
311
|
+
} catch (e) {
|
|
312
|
+
stdio.err(`Error: ${e instanceof Error ? e.message : String(e)}\n`);
|
|
313
|
+
process.exitCode = 1;
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/**
|
|
318
|
+
* Makes `program.parse` / `parseAsync` answer `__complete` and
|
|
319
|
+
* `__completeNoDesc` requests themselves, before commander parses, so
|
|
320
|
+
* no hook, option handler or action runs on tab. Idempotent.
|
|
321
|
+
*/
|
|
322
|
+
export function installCompletionRequest(program: Command): void {
|
|
323
|
+
const t = program as Tagged;
|
|
324
|
+
if (t[INSTALLED]) return;
|
|
325
|
+
t[INSTALLED] = true;
|
|
326
|
+
const request = (argv?: readonly string[], opts?: ParseOptions) => {
|
|
327
|
+
const words = userArgs(argv, opts);
|
|
328
|
+
const first = words?.[0];
|
|
329
|
+
if (first !== REQUEST_CMD && first !== NO_DESC_REQUEST_CMD) return null;
|
|
330
|
+
return serve(program, words!.slice(1), first === NO_DESC_REQUEST_CMD);
|
|
331
|
+
};
|
|
332
|
+
const parse = program.parse.bind(program);
|
|
333
|
+
const parseAsync = program.parseAsync.bind(program);
|
|
334
|
+
program.parse = ((argv?: readonly string[], opts?: ParseOptions) => {
|
|
335
|
+
const pending = request(argv, opts);
|
|
336
|
+
if (!pending) return parse(argv, opts as never);
|
|
337
|
+
void pending;
|
|
338
|
+
return program;
|
|
339
|
+
}) as typeof program.parse;
|
|
340
|
+
program.parseAsync = (async (argv?: readonly string[], opts?: ParseOptions) => {
|
|
341
|
+
const pending = request(argv, opts);
|
|
342
|
+
if (!pending) return parseAsync(argv, opts as never);
|
|
343
|
+
await pending;
|
|
344
|
+
return program;
|
|
345
|
+
}) as typeof program.parseAsync;
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
/**
|
|
349
|
+
* Answers a completion request: `words` are the words after
|
|
350
|
+
* `__complete` (the last is the word being completed). Writes one
|
|
351
|
+
* completion per line, then `:<directive>`, to `io.out`, and the
|
|
352
|
+
* directive's name to `io.err`, in cobra's format.
|
|
353
|
+
*/
|
|
354
|
+
export async function completeRequest(
|
|
355
|
+
program: Command,
|
|
356
|
+
words: string[],
|
|
357
|
+
noDesc = false,
|
|
358
|
+
io: CompletionIO = stdio,
|
|
359
|
+
): Promise<void> {
|
|
360
|
+
const { completions, directive, error } = await getCompletions(program, words);
|
|
361
|
+
if (error) compError(io, error);
|
|
362
|
+
if (!noDesc) {
|
|
363
|
+
const v = envConfig(program.name(), 'COMPLETION_DESCRIPTIONS');
|
|
364
|
+
const b = v === undefined ? undefined : parseBool(v);
|
|
365
|
+
if (b !== undefined) noDesc = !b;
|
|
366
|
+
}
|
|
367
|
+
for (let c of completions) {
|
|
368
|
+
if (noDesc) c = c.split('\t')[0]!;
|
|
369
|
+
// First line only: a description with a line break would read as
|
|
370
|
+
// further completions.
|
|
371
|
+
c = c.split('\n')[0]!;
|
|
372
|
+
io.out(`${goTrimSpace(c)}\n`);
|
|
373
|
+
}
|
|
374
|
+
io.out(`:${directive}\n`);
|
|
375
|
+
io.err(`Completion ended with directive: ${directiveName(directive)}\n`);
|
|
376
|
+
}
|
|
150
377
|
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
378
|
+
/** cobra `getEnvConfig`: `<PROGRAM>_<SUFFIX>`, else `COBRA_<SUFFIX>`. */
|
|
379
|
+
function envConfig(prog: string, suffix: string): string | undefined {
|
|
380
|
+
for (const k of [configEnvVar(prog, suffix), configEnvVar('COBRA', suffix)]) {
|
|
381
|
+
const v = process.env[k];
|
|
382
|
+
if (v) return v;
|
|
383
|
+
}
|
|
384
|
+
return undefined;
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/** Go `strconv.ParseBool`. */
|
|
388
|
+
function parseBool(v: string): boolean | undefined {
|
|
389
|
+
if (['1', 't', 'T', 'TRUE', 'true', 'True'].includes(v)) return true;
|
|
390
|
+
if (['0', 'f', 'F', 'FALSE', 'false', 'False'].includes(v)) return false;
|
|
391
|
+
return undefined;
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
/** Go `strings.TrimSpace`. */
|
|
395
|
+
function goTrimSpace(s: string): string {
|
|
396
|
+
const ws = '[\\t\\n\\v\\f\\r \\u0085\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]';
|
|
397
|
+
return s.replace(new RegExp(`^${ws}+|${ws}+$`, 'g'), '');
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
/** cobra `CompErrorln`: stderr, plus `$BASH_COMP_DEBUG_FILE` when set. */
|
|
401
|
+
function compError(io: CompletionIO, msg: string): void {
|
|
402
|
+
const line = `[Debug] [Error] ${msg}\n`;
|
|
403
|
+
const file = process.env['BASH_COMP_DEBUG_FILE'];
|
|
404
|
+
if (file) {
|
|
405
|
+
try { appendFileSync(file, line); } catch { /* best effort */ }
|
|
406
|
+
}
|
|
407
|
+
io.err(line);
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
// ---------------------------------------------------------------------------
|
|
411
|
+
// Engine: cobra's getCompletions over a commander tree
|
|
412
|
+
// ---------------------------------------------------------------------------
|
|
413
|
+
|
|
414
|
+
/** A flag as completion sees it. */
|
|
415
|
+
interface Flag {
|
|
416
|
+
owner: Command;
|
|
417
|
+
/** Long name without `--`. */
|
|
418
|
+
long?: string;
|
|
419
|
+
/** Shorthand without `-`. */
|
|
420
|
+
short?: string;
|
|
421
|
+
usage: string;
|
|
422
|
+
takesValue: boolean;
|
|
423
|
+
multi: boolean;
|
|
424
|
+
hidden: boolean;
|
|
425
|
+
required: boolean;
|
|
426
|
+
/** Help or version: given, completion stops. */
|
|
427
|
+
stops: boolean;
|
|
428
|
+
inherited: boolean;
|
|
429
|
+
choices?: readonly string[];
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
function flagName(f: Flag): string {
|
|
433
|
+
return f.long ?? f.short ?? '';
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
function toFlag(o: Option, owner: Command, root: Command, inherited: boolean): Flag {
|
|
437
|
+
const help = internals(owner)._getHelpOption?.() === o;
|
|
438
|
+
const version = !help && internals(owner)._versionOptionName === o.attributeName();
|
|
439
|
+
let usage = o.description;
|
|
440
|
+
if (help) usage = `help for ${owner.name()}`;
|
|
441
|
+
else if (version) usage = `version for ${root.name()}`;
|
|
442
|
+
else if (o.argChoices?.length) {
|
|
443
|
+
const suffix = `(one of: ${o.argChoices.join(', ')})`;
|
|
444
|
+
usage = usage ? `${usage} ${suffix}` : suffix;
|
|
445
|
+
}
|
|
446
|
+
return {
|
|
447
|
+
owner,
|
|
448
|
+
long: o.long?.replace(/^--/, ''),
|
|
449
|
+
short: o.short?.replace(/^-/, ''),
|
|
450
|
+
usage,
|
|
451
|
+
takesValue: o.required || o.optional,
|
|
452
|
+
multi: o.variadic,
|
|
453
|
+
hidden: o.hidden,
|
|
454
|
+
required: o.mandatory,
|
|
455
|
+
stops: help || version,
|
|
456
|
+
inherited,
|
|
457
|
+
choices: o.argChoices,
|
|
458
|
+
};
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
/**
|
|
462
|
+
* The flags of the last command of `chain`, as commander accepts them:
|
|
463
|
+
* ancestors' options (unless an ancestor has positional options), then
|
|
464
|
+
* its own plus its help option. A root-alias shim takes no flags of its
|
|
465
|
+
* own, only help.
|
|
466
|
+
*/
|
|
467
|
+
function flagsOf(root: Command, chain: Command[]): Flag[] {
|
|
468
|
+
const cmd = chain[chain.length - 1]!;
|
|
469
|
+
const out: Flag[] = [];
|
|
470
|
+
for (let i = chain.length - 2; i >= 0; i--) {
|
|
471
|
+
const anc = chain[i]!;
|
|
472
|
+
if (internals(anc)._enablePositionalOptions) break;
|
|
473
|
+
for (const o of anc.options) out.push(toFlag(o, anc, root, true));
|
|
474
|
+
}
|
|
475
|
+
if (isShim(root, cmd)) {
|
|
476
|
+
out.push({
|
|
477
|
+
owner: cmd, long: 'help', short: 'h', usage: `help for ${cmd.name()}`,
|
|
478
|
+
takesValue: false, multi: false, hidden: false, required: false,
|
|
479
|
+
stops: true, inherited: false,
|
|
155
480
|
});
|
|
481
|
+
return out;
|
|
482
|
+
}
|
|
483
|
+
for (const o of cmd.options) out.push(toFlag(o, cmd, root, false));
|
|
484
|
+
const help = internals(cmd)._getHelpOption?.();
|
|
485
|
+
if (help && !cmd.options.includes(help)) out.push(toFlag(help, cmd, root, false));
|
|
486
|
+
return out;
|
|
487
|
+
}
|
|
156
488
|
|
|
157
|
-
|
|
489
|
+
function rootAliases(root: Command): Map<string, string> {
|
|
490
|
+
return (root as Tagged)[ROOT_ALIASES] ?? new Map();
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
/** A hidden root subcommand standing in for a deep root alias. */
|
|
494
|
+
function isShim(root: Command, cmd: Command): boolean {
|
|
495
|
+
return cmd.parent === root && rootAliases(root).has(cmd.name());
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
const lookupLong = (flags: Flag[], name: string) => flags.find(f => f.long === name);
|
|
499
|
+
const lookupShort = (flags: Flag[], s: string) => flags.find(f => f.short === s);
|
|
500
|
+
|
|
501
|
+
function subcommand(cmd: Command, word: string): Command | undefined {
|
|
502
|
+
return cmd.commands.find(c => c.name() === word || c.aliases().includes(word));
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
/** pflag `isFlagArg`. */
|
|
506
|
+
function isFlagArg(a: string): boolean {
|
|
507
|
+
return (a.length >= 3 && a.startsWith('--')) || (a.length >= 2 && a[0] === '-' && a[1] !== '-');
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
/** Whether a dash word consumes the next one (unknown flags do, as in cobra). */
|
|
511
|
+
function consumesNext(flags: Flag[], s: string): boolean {
|
|
512
|
+
if (s.includes('=')) return false;
|
|
513
|
+
if (s.startsWith('--')) return lookupLong(flags, s.slice(2))?.takesValue ?? true;
|
|
514
|
+
if (s.startsWith('-') && s.length === 2) return lookupShort(flags, s.slice(1))?.takesValue ?? true;
|
|
515
|
+
return false;
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
/** cobra `stripFlags`: the non-flag words, skipping flag values. */
|
|
519
|
+
function stripFlags(args: string[], flags: Flag[]): string[] {
|
|
520
|
+
const commands: string[] = [];
|
|
521
|
+
for (let i = 0; i < args.length;) {
|
|
522
|
+
const s = args[i++]!;
|
|
523
|
+
if (s === '--') break;
|
|
524
|
+
if (s.startsWith('-') && consumesNext(flags, s)) {
|
|
525
|
+
if (args.length - i <= 1) break;
|
|
526
|
+
i++;
|
|
527
|
+
continue;
|
|
528
|
+
}
|
|
529
|
+
if (s !== '' && !s.startsWith('-')) commands.push(s);
|
|
530
|
+
}
|
|
531
|
+
return commands;
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
/** cobra `argsMinusFirstX`: `args` without the first non-flag `x`. */
|
|
535
|
+
function argsMinusFirst(args: string[], x: string, flags: Flag[]): string[] {
|
|
536
|
+
for (let pos = 0; pos < args.length;) {
|
|
537
|
+
const s = args[pos]!;
|
|
538
|
+
if (s === '--') break;
|
|
539
|
+
if (s.startsWith('-') && consumesNext(flags, s)) {
|
|
540
|
+
pos += 2;
|
|
541
|
+
continue;
|
|
542
|
+
}
|
|
543
|
+
if (!s.startsWith('-') && s === x) return [...args.slice(0, pos), ...args.slice(pos + 1)];
|
|
544
|
+
pos++;
|
|
545
|
+
}
|
|
546
|
+
return args;
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
/** cobra `Find`: descend through subcommand names and aliases. */
|
|
550
|
+
function find(root: Command, args: string[]) {
|
|
551
|
+
const chain = [root];
|
|
552
|
+
const words: string[] = [];
|
|
553
|
+
let rest = args;
|
|
554
|
+
for (;;) {
|
|
555
|
+
const cur = chain[chain.length - 1]!;
|
|
556
|
+
const flags = flagsOf(root, chain);
|
|
557
|
+
const next = stripFlags(rest, flags)[0];
|
|
558
|
+
if (next === undefined) break;
|
|
559
|
+
const sub = subcommand(cur, next);
|
|
560
|
+
if (!sub) break;
|
|
561
|
+
rest = argsMinusFirst(rest, next, flags);
|
|
562
|
+
words.push(sub.name());
|
|
563
|
+
chain.push(sub);
|
|
564
|
+
}
|
|
565
|
+
return { chain, words, rest };
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
/** pflag's parse of the final command's arguments, with its error texts. */
|
|
569
|
+
function parseFlags(flags: Flag[], args: string[]): { seen: Flag[]; positionals: string[] } {
|
|
570
|
+
const seen: Flag[] = [];
|
|
571
|
+
const positionals: string[] = [];
|
|
572
|
+
let dashdash = false;
|
|
573
|
+
for (let i = 0; i < args.length;) {
|
|
574
|
+
const s = args[i++]!;
|
|
575
|
+
if (dashdash || s.length < 2 || !s.startsWith('-')) {
|
|
576
|
+
positionals.push(s);
|
|
577
|
+
continue;
|
|
578
|
+
}
|
|
579
|
+
if (s === '--') {
|
|
580
|
+
dashdash = true;
|
|
581
|
+
continue;
|
|
582
|
+
}
|
|
583
|
+
if (s.startsWith('--')) {
|
|
584
|
+
const body = s.slice(2);
|
|
585
|
+
if (body.startsWith('-') || body.startsWith('=')) throw new Error(`bad flag syntax: ${s}`);
|
|
586
|
+
const eq = body.indexOf('=');
|
|
587
|
+
const name = eq < 0 ? body : body.slice(0, eq);
|
|
588
|
+
const f = lookupLong(flags, name);
|
|
589
|
+
if (!f) throw new Error(`unknown flag: --${name}`);
|
|
590
|
+
if (eq < 0 && f.takesValue) {
|
|
591
|
+
if (i >= args.length) throw new Error(`flag needs an argument: ${s}`);
|
|
592
|
+
i++;
|
|
593
|
+
}
|
|
594
|
+
seen.push(f);
|
|
595
|
+
continue;
|
|
596
|
+
}
|
|
597
|
+
const shorthands = s.slice(1);
|
|
598
|
+
for (let j = 0; j < shorthands.length; j++) {
|
|
599
|
+
const c = shorthands[j]!;
|
|
600
|
+
const f = lookupShort(flags, c);
|
|
601
|
+
if (!f) throw new Error(`unknown shorthand flag: '${c}' in -${shorthands}`);
|
|
602
|
+
seen.push(f);
|
|
603
|
+
const rest = shorthands.slice(j + 1);
|
|
604
|
+
if (rest.startsWith('=')) break;
|
|
605
|
+
if (!f.takesValue) continue;
|
|
606
|
+
if (rest === '') {
|
|
607
|
+
if (i >= args.length) throw new Error(`flag needs an argument: '${c}' in -${shorthands}`);
|
|
608
|
+
i++;
|
|
609
|
+
}
|
|
610
|
+
break;
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
return { seen, positionals };
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
interface FlagCheck {
|
|
617
|
+
flag?: Flag;
|
|
618
|
+
args: string[];
|
|
619
|
+
toComplete: string;
|
|
620
|
+
error?: string;
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
/** cobra `checkIfFlagCompletion`: is the word the value of a flag? */
|
|
624
|
+
function checkFlagCompletion(cmd: Command, flags: Flag[], args: string[], last: string): FlagCheck {
|
|
625
|
+
let name = '';
|
|
626
|
+
let trimmed = args;
|
|
627
|
+
let withEqual = false;
|
|
628
|
+
let value = last;
|
|
629
|
+
if (last.startsWith('-')) {
|
|
630
|
+
const idx = last.indexOf('=');
|
|
631
|
+
if (idx < 0) return { args, toComplete: last };
|
|
632
|
+
// The last shorthand of a cluster: `-asd=` completes `d`.
|
|
633
|
+
name = last.startsWith('--') ? last.slice(2, idx) : last.slice(0, idx).slice(-1);
|
|
634
|
+
value = last.slice(idx + 1);
|
|
635
|
+
withEqual = true;
|
|
636
|
+
}
|
|
637
|
+
if (name === '' && args.length > 0) {
|
|
638
|
+
const prev = args[args.length - 1]!;
|
|
639
|
+
if (isFlagArg(prev) && !prev.includes('=')) {
|
|
640
|
+
name = prev.startsWith('--') ? prev.slice(2) : prev.slice(-1);
|
|
641
|
+
trimmed = args.slice(0, -1);
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
if (name === '') return { args: trimmed, toComplete: value };
|
|
645
|
+
// cobra `findFlag`: a one-letter name is a shorthand first.
|
|
646
|
+
const flag = (name.length === 1 ? lookupShort(flags, name) : undefined) ?? lookupLong(flags, name);
|
|
647
|
+
if (!flag) {
|
|
648
|
+
return {
|
|
649
|
+
args, toComplete: last,
|
|
650
|
+
error: `Subcommand '${cmd.name()}' does not support flag '${name}'`,
|
|
651
|
+
};
|
|
652
|
+
}
|
|
653
|
+
// A boolean flag takes no value: complete the word as an argument.
|
|
654
|
+
if (!withEqual && !flag.takesValue) return { args, toComplete: value };
|
|
655
|
+
return { flag, args: trimmed, toComplete: value };
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
/** Inherited first, then own, each sorted by name (pflag's visit order). */
|
|
659
|
+
function orderedFlags(flags: Flag[]): Flag[] {
|
|
660
|
+
const byName = (a: Flag, b: Flag) => {
|
|
661
|
+
const x = flagName(a);
|
|
662
|
+
const y = flagName(b);
|
|
663
|
+
return x < y ? -1 : x > y ? 1 : 0;
|
|
664
|
+
};
|
|
665
|
+
return [
|
|
666
|
+
...flags.filter(f => f.inherited).sort(byName),
|
|
667
|
+
...flags.filter(f => !f.inherited).sort(byName),
|
|
668
|
+
];
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
/** `--long<TAB>usage` and `-s<TAB>usage` when they match; nothing for a hidden flag. */
|
|
672
|
+
function flagNameCompletions(f: Flag, toComplete: string): string[] {
|
|
673
|
+
if (f.hidden) return [];
|
|
674
|
+
const out: string[] = [];
|
|
675
|
+
if (f.long && `--${f.long}`.startsWith(toComplete)) out.push(`--${f.long}\t${f.usage}`);
|
|
676
|
+
if (f.short && `-${f.short}`.startsWith(toComplete)) out.push(`-${f.short}\t${f.usage}`);
|
|
677
|
+
return out;
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
function requiredFlags(flags: Flag[], seen: Flag[], toComplete: string): string[] {
|
|
681
|
+
return orderedFlags(flags)
|
|
682
|
+
.filter(f => f.required && !seen.includes(f))
|
|
683
|
+
.flatMap(f => flagNameCompletions(f, toComplete));
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
/** The choices of the positional at index `n`, the variadic last one covering the rest. */
|
|
687
|
+
function positionalChoices(cmd: Command, n: number): readonly string[] | undefined {
|
|
688
|
+
const args = cmd.registeredArguments;
|
|
689
|
+
const last = args[args.length - 1];
|
|
690
|
+
const a = args[n] ?? (last?.variadic ? last : undefined);
|
|
691
|
+
return a?.argChoices;
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
interface Outcome {
|
|
695
|
+
completions: string[];
|
|
696
|
+
directive: number;
|
|
697
|
+
error?: string;
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
async function getCompletions(root: Command, args: string[]): Promise<Outcome> {
|
|
701
|
+
const toCompleteRaw = args.length ? args[args.length - 1]! : '';
|
|
702
|
+
const { chain, words, rest } = find(root, args.slice(0, -1));
|
|
703
|
+
const cmd = chain[chain.length - 1]!;
|
|
704
|
+
const flags = flagsOf(root, chain);
|
|
705
|
+
|
|
706
|
+
const fc = checkFlagCompletion(cmd, flags, rest, toCompleteRaw);
|
|
707
|
+
const { flag, toComplete } = fc;
|
|
708
|
+
// A `--` already on the line turns later dash words into arguments.
|
|
709
|
+
const flagCompletion = !fc.args.includes('--');
|
|
710
|
+
let parsed;
|
|
711
|
+
try {
|
|
712
|
+
parsed = parseFlags(flags, fc.args);
|
|
713
|
+
} catch (e) {
|
|
714
|
+
return {
|
|
715
|
+
completions: [], directive: ShellCompDirective.Default,
|
|
716
|
+
error: `Error while parsing flags from args [${fc.args.join(' ')}]: ${(e as Error).message}`,
|
|
717
|
+
};
|
|
718
|
+
}
|
|
719
|
+
if (fc.error && flagCompletion) {
|
|
720
|
+
return { completions: [], directive: ShellCompDirective.Default, error: fc.error };
|
|
721
|
+
}
|
|
722
|
+
if (parsed.seen.some(f => f.stops)) {
|
|
723
|
+
return { completions: [], directive: ShellCompDirective.NoFileComp };
|
|
724
|
+
}
|
|
725
|
+
const finalArgs = parsed.positionals;
|
|
726
|
+
const ctx: CompletionContext = { commandPath: words.join(' '), args: finalArgs };
|
|
727
|
+
|
|
728
|
+
let completions: string[] = [];
|
|
729
|
+
if (!flag && toComplete.startsWith('-') && !toComplete.includes('=') && flagCompletion) {
|
|
730
|
+
completions = requiredFlags(flags, parsed.seen, toComplete);
|
|
731
|
+
if (completions.length === 0) {
|
|
732
|
+
for (const f of orderedFlags(flags)) {
|
|
733
|
+
if (!parsed.seen.includes(f) || f.multi) completions.push(...flagNameCompletions(f, toComplete));
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
const noSpace = completions.length === 1 && completions[0]!.endsWith('=');
|
|
737
|
+
return {
|
|
738
|
+
completions,
|
|
739
|
+
directive: noSpace ? ShellCompDirective.NoSpace : ShellCompDirective.NoFileComp,
|
|
740
|
+
};
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
let directive: number = ShellCompDirective.Default;
|
|
744
|
+
if (!flag) {
|
|
745
|
+
const localGiven = parsed.seen.some(f => !f.inherited);
|
|
746
|
+
if (finalArgs.length === 0 && !localGiven) {
|
|
747
|
+
const subs = cmd.commands
|
|
748
|
+
.filter(s => !internals(s)._hidden && !(s as Tagged)[BUILTIN])
|
|
749
|
+
.sort((a, b) => (a.name() < b.name() ? -1 : a.name() > b.name() ? 1 : 0));
|
|
750
|
+
for (const s of subs) {
|
|
751
|
+
if (s.name().startsWith(toComplete)) {
|
|
752
|
+
completions.push(`${s.name()}\t${s.summary() || s.description()}`);
|
|
753
|
+
}
|
|
754
|
+
directive = ShellCompDirective.NoFileComp;
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
completions.push(...requiredFlags(flags, parsed.seen, toComplete));
|
|
758
|
+
|
|
759
|
+
// Positional choices play cobra's ValidArgs: they win over a binding.
|
|
760
|
+
const choices = positionalChoices(cmd, finalArgs.length);
|
|
761
|
+
if (choices?.length) {
|
|
762
|
+
completions.push(...choices.filter(v => v.startsWith(toComplete)));
|
|
763
|
+
return { completions, directive: ShellCompDirective.NoFileComp };
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
const result = flag && flagCompletion
|
|
768
|
+
? await flagValueCompletion(flag, ctx, toComplete)
|
|
769
|
+
: await argsCompletion(root, cmd, ctx, toComplete);
|
|
770
|
+
if (result) {
|
|
771
|
+
completions.push(...result.completions);
|
|
772
|
+
directive = result.directive;
|
|
773
|
+
}
|
|
774
|
+
return { completions, directive };
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
/** The completer bound to `flag`, else its choices; null when neither exists. */
|
|
778
|
+
async function flagValueCompletion(flag: Flag, ctx: CompletionContext, toComplete: string) {
|
|
779
|
+
const bound = (flag.owner as Tagged)[FLAG_COMPLETERS]?.get(flagName(flag));
|
|
780
|
+
if (bound) return resolveCompletions(bound, toComplete, ctx);
|
|
781
|
+
if (!flag.choices?.length) return null;
|
|
782
|
+
const lower = toComplete.toLowerCase();
|
|
783
|
+
return {
|
|
784
|
+
completions: flag.choices.filter(v => v.toLowerCase().startsWith(lower)),
|
|
785
|
+
directive: ShellCompDirective.NoFileComp,
|
|
786
|
+
};
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
/** The completer bound to `cmd`'s positionals, plus root aliases at the root. */
|
|
790
|
+
async function argsCompletion(root: Command, cmd: Command, ctx: CompletionContext, toComplete: string) {
|
|
791
|
+
const bound = (cmd as Tagged)[ARGS_COMPLETER];
|
|
792
|
+
const aliases = cmd === root ? rootAliases(root) : new Map<string, string>();
|
|
793
|
+
if (!bound && aliases.size === 0) return null;
|
|
794
|
+
const r = bound
|
|
795
|
+
? await resolveCompletions(bound, toComplete, ctx)
|
|
796
|
+
: { completions: [] as string[], directive: ShellCompDirective.Default as number };
|
|
797
|
+
if (aliases.size > 0) {
|
|
798
|
+
r.directive |= ShellCompDirective.NoFileComp;
|
|
799
|
+
for (const [name, target] of [...aliases].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) {
|
|
800
|
+
if (name.startsWith(toComplete)) r.completions.push(`${name}\talias for ${target}`);
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
return r;
|
|
158
804
|
}
|