@hop-top/kit 0.5.0-alpha.6 → 0.5.0-alpha.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/LICENSE-cobra.txt +174 -0
  3. package/NOTICE +15 -0
  4. package/README.md +3 -3
  5. package/dist/alias-D9_qFlyP.d.ts +174 -0
  6. package/dist/alias.d.ts +1 -1
  7. package/dist/alias.js +10 -2
  8. package/dist/chunk-263IZ6Z6.js +915 -0
  9. package/dist/{chunk-S45UHXQF.js → chunk-BLS2OBIQ.js} +106 -25
  10. package/dist/{chunk-7FDIN5KE.js → chunk-GHPJJV5L.js} +8 -4
  11. package/dist/chunk-JKMQSAJP.js +174 -0
  12. package/dist/chunk-JZ22ZUFA.js +1131 -0
  13. package/dist/{chunk-GAZPYCQD.js → chunk-NLMS7HGP.js} +93 -35
  14. package/dist/chunk-QQQYCWSC.js +240 -0
  15. package/dist/chunk-XJTRY453.js +868 -0
  16. package/dist/cli.js +6 -4
  17. package/dist/completion-csVun6SP.d.ts +112 -0
  18. package/dist/completion-values-By-mnjNt.d.ts +142 -0
  19. package/dist/completion-values.d.ts +1 -0
  20. package/dist/completion-values.js +29 -0
  21. package/dist/completion.d.ts +2 -1
  22. package/dist/completion.js +23 -2
  23. package/dist/compliance-AxFf-uMy.d.ts +60 -0
  24. package/dist/compliance.d.ts +1 -0
  25. package/dist/compliance.js +17 -0
  26. package/dist/config-CaK60ByQ.d.ts +241 -0
  27. package/dist/config.d.ts +1 -1
  28. package/dist/config.js +4 -2
  29. package/dist/index.d.ts +7 -5
  30. package/dist/index.js +26 -18
  31. package/dist/log-CkaxMX3U.d.ts +115 -0
  32. package/dist/log.d.ts +1 -1
  33. package/dist/log.js +2 -2
  34. package/dist/toolspec-UrWnoJ3Y.d.ts +336 -0
  35. package/dist/toolspec.d.ts +2 -1
  36. package/dist/toolspec.js +27 -2
  37. package/package.json +19 -3
  38. package/src/alias.conformance.test.ts +250 -0
  39. package/src/alias.test.ts +206 -2
  40. package/src/alias.ts +196 -21
  41. package/src/cli.ts +5 -0
  42. package/src/completion-scripts.ts +16 -0
  43. package/src/completion-values.test.ts +70 -10
  44. package/src/completion-values.ts +170 -66
  45. package/src/completion.conformance.test.ts +297 -0
  46. package/src/completion.test.ts +256 -145
  47. package/src/completion.ts +767 -121
  48. package/src/config-merge.test.ts +425 -0
  49. package/src/config.test.ts +41 -0
  50. package/src/config.ts +265 -18
  51. package/src/index.test.ts +2 -1
  52. package/src/index.ts +5 -1
  53. package/src/log.test.ts +270 -1
  54. package/src/log.ts +172 -44
  55. package/src/published-types.test.ts +18 -0
  56. package/src/toolspec-internal.ts +197 -0
  57. package/src/toolspec-manifest.test.ts +82 -0
  58. package/src/toolspec-manifest.ts +404 -0
  59. package/src/toolspec-spec-schemas.ts +12 -0
  60. package/src/toolspec-spec.test.ts +273 -0
  61. package/src/toolspec-spec.ts +458 -0
  62. package/src/toolspec.from-command.test.ts +216 -0
  63. package/src/toolspec.ts +159 -0
  64. package/test/toolspec/fixture.ts +73 -0
  65. package/dist/alias-BOj0-VAr.d.ts +0 -88
  66. package/dist/chunk-6RFRV4VP.js +0 -128
  67. package/dist/chunk-IQXEISMC.js +0 -142
  68. package/dist/chunk-W7ERKNSQ.js +0 -171
  69. package/dist/completion-CVnPcWMZ.d.ts +0 -32
  70. package/dist/config-Bm9fBXch.d.ts +0 -134
  71. package/dist/log-uKjHsK-c.d.ts +0 -62
  72. package/dist/toolspec-DPBr18Ub.d.ts +0 -106
package/src/alias.test.ts CHANGED
@@ -4,9 +4,10 @@ import * as path from 'path';
4
4
  import * as os from 'os';
5
5
  import {
6
6
  AliasStore, loadFrom, saveTo, findFirstNonFlag, Expander,
7
- bridgeAliases, findCommand,
7
+ bridgeAliases, findCommand, validateAliasName, AliasNameError,
8
8
  } from './alias';
9
- import { Command } from 'commander';
9
+ import { completeRequest } from './completion';
10
+ import { Command, CommanderError } from 'commander';
10
11
 
11
12
  let tmpDir: string;
12
13
 
@@ -421,3 +422,206 @@ describe('bridgeAliases', () => {
421
422
  expect(deploy?.aliases()).toEqual([]);
422
423
  });
423
424
  });
425
+
426
+ // ── bridgeAliases proxy dispatch ────────────────────────────
427
+
428
+ describe('bridgeAliases proxy dispatch', () => {
429
+ type Seen = { pos?: string; size?: string; verbose?: boolean };
430
+
431
+ function setup(
432
+ action: (
433
+ pos: string | undefined, opts: { size?: string },
434
+ ) => void | Promise<void>,
435
+ ): Command {
436
+ const program = new Command('x')
437
+ .exitOverride()
438
+ .option('-v, --verbose')
439
+ .configureOutput({ writeErr: () => {}, writeOut: () => {} });
440
+ program
441
+ .command('react')
442
+ .command('components')
443
+ .option('--size <n>')
444
+ .argument('[pos]')
445
+ .action(action);
446
+ const store = new AliasStore('/dev/null');
447
+ store.set('comp', 'react components');
448
+ store.set('compsz', 'react components --size 9');
449
+ bridgeAliases(program, store);
450
+ return program;
451
+ }
452
+
453
+ const tick = () => new Promise(r => setTimeout(r, 5));
454
+ let unhandled: unknown[];
455
+ const onUnhandled = (e: unknown) => { unhandled.push(e); };
456
+
457
+ beforeEach(() => {
458
+ unhandled = [];
459
+ process.on('unhandledRejection', onUnhandled);
460
+ });
461
+ afterEach(() => {
462
+ process.off('unhandledRejection', onUnhandled);
463
+ });
464
+
465
+ it('parseAsync awaits an async target action', async () => {
466
+ let done = false;
467
+ const program = setup(async () => { await tick(); done = true; });
468
+ await program.parseAsync(['node', 'x', 'comp']);
469
+ expect(done).toBe(true);
470
+ });
471
+
472
+ it('parseAsync rejects with the async target error', async () => {
473
+ const program = setup(async () => {
474
+ await tick();
475
+ throw new CommanderError(3, 'x.boom', 'boom');
476
+ });
477
+ const err = await program
478
+ .parseAsync(['node', 'x', 'comp'])
479
+ .catch((e: unknown) => e);
480
+ expect(err).toBeInstanceOf(CommanderError);
481
+ expect((err as CommanderError).exitCode).toBe(3);
482
+ await tick();
483
+ expect(unhandled).toEqual([]);
484
+ });
485
+
486
+ it('passes args and options through to the target', async () => {
487
+ let seen: Seen = {};
488
+ const program = setup((pos, o) => { seen = { pos, size: o.size }; });
489
+ await program.parseAsync(['node', 'x', 'comp', '--size', '3', 'p1']);
490
+ expect(seen).toEqual({ pos: 'p1', size: '3' });
491
+
492
+ await program.parseAsync(['node', 'x', 'compsz', 'p2']);
493
+ expect(seen).toEqual({ pos: 'p2', size: '9' });
494
+ });
495
+
496
+ it('keeps program-level options given around the alias', async () => {
497
+ let verbose: unknown;
498
+ const program = setup(() => { verbose = program.opts().verbose; });
499
+ await program.parseAsync(['node', 'x', '-v', 'comp']);
500
+ expect(verbose).toBe(true);
501
+
502
+ verbose = undefined;
503
+ await program.parseAsync(['node', 'x', 'comp', 'p1', '-v']);
504
+ expect(verbose).toBe(true);
505
+ });
506
+
507
+ it('sync parse runs a sync target and rethrows its errors', async () => {
508
+ let seen: string | undefined;
509
+ const ok = setup(pos => { seen = pos; });
510
+ ok.parse(['node', 'x', 'comp', 'p1']);
511
+ expect(seen).toBe('p1');
512
+
513
+ const bad = setup(() => { throw new Error('syncboom'); });
514
+ expect(() => bad.parse(['node', 'x', 'comp'])).toThrow('syncboom');
515
+
516
+ expect(() => ok.parse(['node', 'x', 'comp', '--bogus']))
517
+ .toThrow(CommanderError);
518
+ await tick();
519
+ expect(unhandled).toEqual([]);
520
+ });
521
+
522
+ it('unknown target still reports unknown command', async () => {
523
+ const program = new Command('x')
524
+ .exitOverride()
525
+ .configureOutput({ writeErr: () => {}, writeOut: () => {} });
526
+ program.command('real').action(() => {});
527
+ const store = new AliasStore('/dev/null');
528
+ store.set('nope', 'nonexistent');
529
+ bridgeAliases(program, store);
530
+ await expect(program.parseAsync(['node', 'x', 'nope']))
531
+ .rejects.toMatchObject({ code: 'commander.unknownCommand' });
532
+ });
533
+ });
534
+
535
+ // ── validateAliasName / bridge options ─────────────────────
536
+
537
+ describe('validateAliasName', () => {
538
+ it('keeps the Expander texts and adds duplicate', () => {
539
+ const msg = (name: string, rules = {}) => {
540
+ try { validateAliasName(name, rules); } catch (e) { return (e as Error).message; }
541
+ return 'ok';
542
+ };
543
+ expect(msg('')).toBe('alias name must not be empty');
544
+ expect(msg('a b')).toBe('alias name must not contain whitespace');
545
+ expect(msg('task', { builtins: ['task'] }))
546
+ .toBe('alias "task" conflicts with a built-in command');
547
+ expect(msg('d', { existing: { d: 'deploy' } }))
548
+ .toBe('alias "d" is already registered for "deploy"');
549
+ expect(msg('tl', { builtins: new Set(['task']) })).toBe('ok');
550
+ });
551
+
552
+ it('throws AliasNameError carrying the kind', () => {
553
+ expect(() => validateAliasName('task', { builtins: ['task'] }))
554
+ .toThrow(AliasNameError);
555
+ });
556
+ });
557
+
558
+ describe('bridgeAliases options', () => {
559
+ it('accepts a plain map and an empty options object keeps defaults', () => {
560
+ const program = new Command('test');
561
+ program.command('deploy').description('Deploy');
562
+ bridgeAliases(program, { d: 'deploy' }, {});
563
+ expect(findCommand(program, 'deploy')?.aliases()).toContain('d');
564
+ expect(program.commands.find(c => c.name() === 'd')).toBeUndefined();
565
+ });
566
+
567
+ it('options make a single-word alias a proxy', () => {
568
+ const program = new Command('test');
569
+ program.command('deploy').description('Deploy');
570
+ bridgeAliases(program, { d: 'deploy' }, {
571
+ hidden: false, describe: (n, t) => `${n} -> ${t}`,
572
+ });
573
+ const proxy = program.commands.find(c => c.name() === 'd');
574
+ expect(proxy?.description()).toBe('d -> deploy');
575
+ expect(findCommand(program, 'deploy')?.aliases()).not.toContain('d');
576
+ });
577
+
578
+ it('dispatch handler result is awaited by parseAsync', async () => {
579
+ const program = new Command('test').exitOverride();
580
+ program.command('deploy').action(() => {});
581
+ let done = false;
582
+ bridgeAliases(program, { d: 'deploy' }, {
583
+ dispatch: async () => { await new Promise(r => setTimeout(r, 5)); done = true; },
584
+ });
585
+ await program.parseAsync(['d'], { from: 'user' });
586
+ expect(done).toBe(true);
587
+ });
588
+ });
589
+
590
+ describe('bridgeAliases completion', () => {
591
+ async function complete(program: Command, words: string[]): Promise<string[]> {
592
+ let out = '';
593
+ await completeRequest(program, words, true, { out: s => { out += s; }, err: () => {} });
594
+ return out.split('\n').filter(l => l !== '' && !l.startsWith(':')).sort();
595
+ }
596
+
597
+ function tree(): Command {
598
+ const program = new Command('test');
599
+ program.command('deploy').description('Deploy').option('--env <e>');
600
+ return program;
601
+ }
602
+
603
+ it('a hidden proxy is a stand-in, offered once by name', async () => {
604
+ for (const dispatch of [undefined, false] as const) {
605
+ const program = tree();
606
+ bridgeAliases(program, { d: 'deploy' }, { describe: () => 'x', dispatch });
607
+ expect(await complete(program, ['d'])).toEqual(['d', 'deploy']);
608
+ expect(await complete(program, ['d', '--'])).toEqual(['--help']);
609
+ }
610
+ });
611
+
612
+ it('a hidden proxy with a dispatch handler completes its own flags', async () => {
613
+ const program = tree();
614
+ bridgeAliases(program, { d: 'deploy' }, { dispatch: () => {} });
615
+ program.commands.find(c => c.name() === 'd')!.option('-p, --path <p>');
616
+ expect(await complete(program, ['d'])).toEqual(['deploy']);
617
+ expect(await complete(program, ['d', '--'])).toEqual(['--path']);
618
+ });
619
+
620
+ it('a visible proxy is offered once, with its own flags', async () => {
621
+ const program = tree();
622
+ bridgeAliases(program, { d: 'deploy' }, { hidden: false, helpOption: true });
623
+ program.commands.find(c => c.name() === 'd')!.option('-p, --path <p>');
624
+ expect(await complete(program, ['d'])).toEqual(['d', 'deploy']);
625
+ expect(await complete(program, ['d', '--'])).toEqual(['--help', '--path']);
626
+ });
627
+ });
package/src/alias.ts CHANGED
@@ -9,6 +9,7 @@ import * as fs from 'fs';
9
9
  import * as path from 'path';
10
10
  import * as yaml from 'js-yaml';
11
11
  import { Command } from 'commander';
12
+ import { registerRootAlias } from './completion';
12
13
 
13
14
  export type AliasMap = Record<string, string>;
14
15
 
@@ -185,18 +186,117 @@ export class Expander {
185
186
  return [result, true];
186
187
  }
187
188
 
188
- /** Reject names that shadow builtins or contain whitespace. */
189
+ /**
190
+ * Reject names that shadow builtins or contain whitespace; see
191
+ * {@link validateAliasName}, which needs no config files.
192
+ */
189
193
  validateName(name: string): void {
190
- if (name === '') {
191
- throw new Error('alias name must not be empty');
192
- }
193
- if (/\s/.test(name)) {
194
- throw new Error('alias name must not contain whitespace');
194
+ validateAliasName(name, { builtins: this.cfg.builtins });
195
+ }
196
+ }
197
+
198
+ // ── Standalone validation and cycle detection ───────────────
199
+
200
+ /** The rule an alias name failed; see {@link validateAliasName}. */
201
+ export type AliasNameErrorKind = 'empty' | 'whitespace' | 'builtin' | 'duplicate';
202
+
203
+ /** An alias name {@link validateAliasName} refused. */
204
+ export class AliasNameError extends Error {
205
+ readonly kind: AliasNameErrorKind;
206
+ readonly alias: string;
207
+ /** The existing alias's target, for `duplicate`. */
208
+ readonly target?: string;
209
+
210
+ constructor(kind: AliasNameErrorKind, alias: string, target?: string) {
211
+ super(aliasNameMessage(kind, alias, target));
212
+ this.name = 'AliasNameError';
213
+ this.kind = kind;
214
+ this.alias = alias;
215
+ this.target = target;
216
+ }
217
+ }
218
+
219
+ function aliasNameMessage(
220
+ kind: AliasNameErrorKind, alias: string, target?: string,
221
+ ): string {
222
+ switch (kind) {
223
+ case 'empty': return 'alias name must not be empty';
224
+ case 'whitespace': return 'alias name must not contain whitespace';
225
+ case 'builtin': return `alias "${alias}" conflicts with a built-in command`;
226
+ case 'duplicate':
227
+ return `alias "${alias}" is already registered for "${target ?? ''}"`;
228
+ }
229
+ }
230
+
231
+ /** What {@link validateAliasName} checks a name against. */
232
+ export interface AliasNameRules {
233
+ /** Names an alias must not take: the tool's commands and reserved words. */
234
+ builtins?: Iterable<string>;
235
+ /** The alias map the name would join. */
236
+ existing?: AliasMap;
237
+ }
238
+
239
+ const WHITE_SPACE = /\p{White_Space}/u;
240
+
241
+ /**
242
+ * Check an alias name without a store, config file or command tree.
243
+ * Rules run in order and the first failure throws an
244
+ * {@link AliasNameError}: empty, whitespace (any Unicode White_Space
245
+ * character), builtin, duplicate.
246
+ */
247
+ export function validateAliasName(name: string, rules: AliasNameRules = {}): void {
248
+ if (name === '') throw new AliasNameError('empty', name);
249
+ if (WHITE_SPACE.test(name)) throw new AliasNameError('whitespace', name);
250
+ if (rules.builtins) {
251
+ for (const b of rules.builtins) {
252
+ if (b === name) throw new AliasNameError('builtin', name);
195
253
  }
196
- if (this.cfg.builtins?.has(name)) {
197
- throw new Error(`alias "${name}" conflicts with a built-in command`);
254
+ }
255
+ const existing = rules.existing;
256
+ if (existing && Object.prototype.hasOwnProperty.call(existing, name)) {
257
+ throw new AliasNameError('duplicate', name, existing[name]);
258
+ }
259
+ }
260
+
261
+ /**
262
+ * Report alias cycles in `aliases` (name -> target). An alias points at
263
+ * another when the first word of its target is a key of the map. Each
264
+ * cycle is a path starting at its smallest name and ending with it
265
+ * again (`['a', 'b', 'a']`); cycles are sorted by first name. An alias
266
+ * that only leads into a cycle is not part of one.
267
+ */
268
+ export function detectCycles(aliases: AliasMap): string[][] {
269
+ const has = (n: string) => Object.prototype.hasOwnProperty.call(aliases, n);
270
+ const next = (n: string): string | undefined => {
271
+ const first = aliases[n].trim().split(/\s+/)[0];
272
+ return first !== '' && has(first) ? first : undefined;
273
+ };
274
+ const cmp = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0);
275
+
276
+ const done = new Set<string>();
277
+ const cycles: string[][] = [];
278
+ for (const start of Object.keys(aliases).sort(cmp)) {
279
+ if (done.has(start)) continue;
280
+ const pos = new Map<string, number>();
281
+ const walk: string[] = [];
282
+ let cur: string | undefined = start;
283
+ while (cur !== undefined && !done.has(cur)) {
284
+ const at = pos.get(cur);
285
+ if (at !== undefined) {
286
+ const members = walk.slice(at);
287
+ let min = 0;
288
+ members.forEach((m, i) => { if (m < members[min]) min = i; });
289
+ const path = [...members.slice(min), ...members.slice(0, min)];
290
+ cycles.push([...path, path[0]]);
291
+ break;
292
+ }
293
+ pos.set(cur, walk.length);
294
+ walk.push(cur);
295
+ cur = next(cur);
198
296
  }
297
+ for (const n of walk) done.add(n);
199
298
  }
299
+ return cycles.sort((a, b) => cmp(a[0], b[0]));
200
300
  }
201
301
 
202
302
  // ── Commander bridge ────────────────────────────────────────
@@ -215,22 +315,90 @@ export function findCommand(
215
315
  return cmd;
216
316
  }
217
317
 
318
+ /** Commander internal used for subcommand dispatch (promise-or-value). */
319
+ type Dispatcher = {
320
+ _parseCommand(operands: string[], unknown: string[]): void | Promise<void>;
321
+ };
322
+
323
+ /** Runs an alias proxy in place of its target; `cmd.args` holds every argument after the alias, unparsed. */
324
+ export type AliasDispatch = (
325
+ name: string, target: string, cmd: Command,
326
+ ) => void | Promise<void>;
327
+
328
+ /**
329
+ * Options for {@link bridgeAliases}. Setting any of them registers every
330
+ * alias as a proxy, a root command named after the alias, even for a
331
+ * single-word target that would otherwise take a Commander alias.
332
+ */
333
+ export interface BridgeOptions {
334
+ /** Hide proxies from help. Default true. */
335
+ hidden?: boolean;
336
+ /** A proxy's description, in place of `Alias for <target>`. */
337
+ describe?: (name: string, target: string) => string;
338
+ /**
339
+ * true: the proxy owns -h/--help and shows its own help. false (the
340
+ * default): --help reaches the target, or the dispatch handler.
341
+ */
342
+ helpOption?: boolean;
343
+ /**
344
+ * A handler run instead of the target, or false to register proxies
345
+ * that run nothing (register-only). Default: dispatch the target
346
+ * through the program, like a native subcommand.
347
+ */
348
+ dispatch?: AliasDispatch | false;
349
+ }
350
+
351
+ function hasBridgeOptions(opts?: BridgeOptions): opts is BridgeOptions {
352
+ return opts !== undefined &&
353
+ Object.values(opts).some(v => v !== undefined);
354
+ }
355
+
218
356
  /**
219
357
  * Register loaded aliases with Commander's native .alias() API.
220
358
  *
221
359
  * Simple single-command aliases use Commander's built-in .alias(),
222
360
  * giving free completion and help display. Multi-word or unresolved
223
- * targets get a hidden proxy command that re-parses with expanded args.
361
+ * targets get a hidden proxy command that dispatches the expanded
362
+ * args from the program, like a native subcommand. With any
363
+ * {@link BridgeOptions} set, every alias gets a proxy shaped by them.
364
+ *
365
+ * Completion offers each alias at most once. A native alias, or a hidden
366
+ * proxy that dispatches its target or runs nothing, is a stand-in:
367
+ * completion lists it as `alias for <target>` and offers a proxy only
368
+ * its help flag. A visible proxy, or one with a dispatch handler, is a
369
+ * real command and completes like any subcommand, with its own flags,
370
+ * including any added after bridging; a hidden one is not listed.
371
+ *
372
+ * `source` is an {@link AliasStore} or a plain alias map, so aliases
373
+ * can come from any storage.
374
+ *
375
+ * Dispatch reuses Commander's own subcommand dispatch rather than
376
+ * calling parse()/parseAsync() again: re-parsing resets program
377
+ * option values mid-parse and fixes the sync/async mode, whereas
378
+ * dispatch returns the target's result as-is. parseAsync() callers
379
+ * thus await async targets (rejections propagate), and parse()
380
+ * callers keep synchronous throws.
224
381
  */
225
382
  export function bridgeAliases(
226
383
  program: Command,
227
- store: AliasStore,
384
+ source: AliasStore | AliasMap,
385
+ opts?: BridgeOptions,
228
386
  ): void {
229
- const all = store.all();
387
+ const all = typeof (source as AliasStore).all === 'function'
388
+ ? (source as AliasStore).all()
389
+ : { ...(source as AliasMap) };
390
+ const proxyAll = hasBridgeOptions(opts);
391
+ // A visible or custom-dispatch proxy is a real command: completion
392
+ // offers it among the subcommands and walks it for its own flags. A
393
+ // root-alias entry would list it twice and complete it as a flagless
394
+ // stand-in.
395
+ const realProxy = proxyAll &&
396
+ (opts.hidden === false || typeof opts.dispatch === 'function');
230
397
  for (const [name, target] of Object.entries(all)) {
398
+ if (!realProxy) registerRootAlias(program, name, target);
231
399
  const parts = target.split(/\s+/);
232
400
  // simple alias: single word target that exists as a direct subcommand
233
- if (parts.length === 1) {
401
+ if (!proxyAll && parts.length === 1) {
234
402
  const targetCmd = findCommand(program, target);
235
403
  if (targetCmd) {
236
404
  targetCmd.alias(name);
@@ -238,19 +406,26 @@ export function bridgeAliases(
238
406
  }
239
407
  }
240
408
 
241
- // multi-word target or unknown command: hidden proxy
242
- const proxy = new Command(name)
243
- .description(`Alias for ${target}`)
409
+ // multi-word target, unknown command or options: proxy
410
+ const dispatch = opts?.dispatch;
411
+ const proxy = new Command(name);
412
+ // An options proxy behaves like a subcommand made with
413
+ // program.command(): it inherits exitOverride, output and help
414
+ // settings, which matter once it renders its own help.
415
+ if (proxyAll) proxy.copyInheritedSettings(program);
416
+ proxy
417
+ .description(opts?.describe?.(name, target) ?? `Alias for ${target}`)
244
418
  .allowUnknownOption(true)
245
419
  .allowExcessArguments(true)
246
420
  .action(function (this: Command) {
421
+ if (dispatch === false) return undefined;
422
+ if (dispatch) return dispatch(name, target, this);
247
423
  const expanded = target.split(/\s+/);
248
- program.parse([
249
- 'node', program.name(), ...expanded, ...this.args,
250
- ]);
424
+ return (program as unknown as Dispatcher)._parseCommand(
425
+ [], [...expanded, ...this.args],
426
+ );
251
427
  });
252
- proxy.helpOption(false);
253
- (proxy as any)._hidden = true;
254
- program.addCommand(proxy);
428
+ if (opts?.helpOption !== true) proxy.helpOption(false);
429
+ program.addCommand(proxy, { hidden: opts?.hidden ?? true });
255
430
  }
256
431
  }
package/src/cli.ts CHANGED
@@ -30,6 +30,7 @@ import { parity, type ParityData } from './tui/parity.js';
30
30
  import { registerOutputFlags } from './output/flags.js';
31
31
  import { EXIT_USAGE } from './output/error.js';
32
32
  import { install as installNetPolicy, setProcessOffline } from './netpolicy.js';
33
+ import { installCompletionRequest } from './completion.js';
33
34
  import './output/builtins.js';
34
35
  export { ErrOffline, OfflineError, guardFetch, isOffline, isOfflineError,
35
36
  withOffline } from './netpolicy.js';
@@ -881,6 +882,10 @@ export function createCLI(cfg: CLIConfig): CLIResult {
881
882
  program.option(flag, g.usage, g.default ?? '');
882
883
  }
883
884
 
885
+ // Shell completion scripts call back into `<name> __complete`; answer
886
+ // it ahead of commander's parse so no hook or action runs on tab.
887
+ installCompletionRequest(program);
888
+
884
889
  // Apply brand color scheme + section order to --help output.
885
890
  // noColor is read lazily at render time inside applyHelpTheme.
886
891
  applyHelpTheme(program, theme, false, cfg.help?.sectionOrder,
@@ -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;