Skip to content

Commit f0d1e48

Browse files
fix(commander): match commander options scope behavior in different modes (#155)
* fix(commander): match commander options scope behavior in different modes * fix win tests * chore: simplify scanArguments (#156) * apply suggestions * pin ubunto - issue no.27388/powershell * add changeset --------- Co-authored-by: John Gee <john@ruru.gen.nz>
1 parent e907309 commit f0d1e48

6 files changed

Lines changed: 315 additions & 27 deletions

File tree

‎.changeset/long-months-refuse.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@bomb.sh/tab': patch
3+
---
4+
5+
Match Commander option scoping in default and positional-options modes.

‎.github/workflows/shell-completions.yml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ on:
1111
jobs:
1212
shell-argv-protocol:
1313
name: Shell argv protocol
14-
runs-on: ubuntu-latest
14+
runs-on: ubuntu-24.04
1515

1616
steps:
1717
- name: Checkout

‎src/commander.ts‎

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,28 @@
11
import type { Command as CommanderCommand } from 'commander';
2-
import t, { Command as TabCommand, type RootCommand, OptionHandler } from './t';
2+
import t, {
3+
type Command as TabCommand,
4+
type RootCommand,
5+
type OptionHandler,
6+
} from './t';
37

48
// rawArgs is available on (just) the Commander root command, but is not included in the TypeScript types.
59
interface CommandWithRawArgs extends CommanderCommand {
610
rawArgs: string[];
711
}
812

13+
// Commander does not expose a getter for this setting.
14+
interface CommandWithPositionalOptions extends CommanderCommand {
15+
_enablePositionalOptions: boolean;
16+
}
17+
918
export default function tab(
1019
instance: CommanderCommand,
1120
completionConfig?: { completionCommandName?: string }
1221
): RootCommand {
1322
const programName = instance.name();
23+
const positionalOptions = (instance as CommandWithPositionalOptions)
24+
._enablePositionalOptions;
25+
t.optionLookupMode = positionalOptions ? 'local' : 'parent-first';
1426

1527
// Make a `completion` command with a required command-argument.
1628
const completionCommandName =

‎src/t.ts‎

Lines changed: 130 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -140,18 +140,68 @@ export class RootCommand extends Command {
140140
commands = new Map<string, Command>();
141141
completions: Completion[] = [];
142142
directive = ShellCompDirective.ShellCompDirectiveDefault;
143+
optionLookupMode?: 'parent-first' | 'local';
143144

144145
constructor() {
145146
super('', '');
146147
}
147148

148149
command(value: string, description: string) {
149150
const c = new Command(value, description);
151+
const parentPath = value.split(' ').slice(0, -1).join(' ');
152+
c.parent = parentPath ? this.commands.get(parentPath) : this;
150153
this.commands.set(value, c);
151154
return c;
152155
}
153156

157+
private scanArguments(args: string[]): {
158+
command: Command;
159+
parts: string[];
160+
} {
161+
const parts: string[] = [];
162+
let matchedCommand: Command | undefined;
163+
let canMatchCommand = true;
164+
let i = 0;
165+
166+
while (i < args.length) {
167+
const arg = args[i];
168+
169+
if (arg.startsWith('-')) {
170+
i++;
171+
172+
const option = this.findOptionInScope(matchedCommand ?? this, arg);
173+
const isBoolean = option?.isBoolean ?? false;
174+
175+
// skip the next argument if this is not a boolean option and the next arg doesn't start with -
176+
if (!isBoolean && i < args.length && !args[i].startsWith('-')) {
177+
i++;
178+
}
179+
} else {
180+
parts.push(arg);
181+
182+
if (canMatchCommand) {
183+
const commandPath = parts.join(' ');
184+
const command = this.commands.get(commandPath);
185+
186+
if (command) {
187+
matchedCommand = command;
188+
} else {
189+
canMatchCommand = false;
190+
}
191+
}
192+
193+
i++;
194+
}
195+
}
196+
197+
return { command: matchedCommand ?? this, parts };
198+
}
199+
154200
private stripOptions(args: string[]): string[] {
201+
if (this.optionLookupMode) {
202+
return this.scanArguments(args).parts;
203+
}
204+
155205
const parts: string[] = [];
156206
let i = 0;
157207

@@ -191,6 +241,13 @@ export class RootCommand extends Command {
191241
}
192242

193243
private matchCommand(args: string[]): [Command, string[]] {
244+
if (this.optionLookupMode) {
245+
const { command, parts } = this.scanArguments(args);
246+
const commandPartCount =
247+
command === this ? 0 : command.value.split(' ').length;
248+
return [command, parts.slice(commandPartCount)];
249+
}
250+
194251
args = this.stripOptions(args);
195252
const parts: string[] = [];
196253
let remaining: string[] = [];
@@ -213,6 +270,7 @@ export class RootCommand extends Command {
213270
}
214271

215272
private shouldCompleteFlags(
273+
command: Command,
216274
lastPrevArg: string | undefined,
217275
toComplete: string
218276
): boolean {
@@ -222,12 +280,18 @@ export class RootCommand extends Command {
222280

223281
// previous argument was an option, check if it expects a value
224282
if (lastPrevArg?.startsWith('-')) {
225-
let option = this.findOption(this, lastPrevArg);
226-
if (!option) {
227-
// subcommand options
228-
for (const [, command] of this.commands) {
229-
option = this.findOption(command, lastPrevArg);
230-
if (option) break;
283+
let option: Option | undefined;
284+
285+
if (this.optionLookupMode) {
286+
option = this.findOptionInScope(command, lastPrevArg);
287+
} else {
288+
option = this.findOption(this, lastPrevArg);
289+
if (!option) {
290+
// subcommand options
291+
for (const [, candidate] of this.commands) {
292+
option = this.findOption(candidate, lastPrevArg);
293+
if (option) break;
294+
}
231295
}
232296
}
233297

@@ -261,21 +325,21 @@ export class RootCommand extends Command {
261325
const [flag] = toComplete.split('=');
262326
optionName = flag;
263327
} else if (lastPrevArg?.startsWith('-')) {
264-
const option = this.findOption(command, lastPrevArg);
328+
const option = this.findOptionForCompletion(command, lastPrevArg);
265329
if (option && !option.isBoolean) {
266330
optionName = lastPrevArg;
267331
}
268332
}
269333

270334
if (optionName) {
271-
const option = this.findOption(command, optionName);
335+
const option = this.findOptionForCompletion(command, optionName);
272336
if (option?.handler) {
273337
const suggestions: Completion[] = [];
274338
option.handler.call(
275339
option,
276340
(value: string, description: string) =>
277341
suggestions.push({ value, description }),
278-
command.options
342+
option.command.options
279343
);
280344

281345
this.completions = suggestions;
@@ -288,26 +352,67 @@ export class RootCommand extends Command {
288352
toComplete.startsWith('-') && !toComplete.startsWith('--');
289353
const cleanToComplete = toComplete.replace(/^-+/, '');
290354

291-
for (const [name, option] of command.options) {
292-
if (
293-
isShortFlag &&
294-
option.alias &&
295-
`-${option.alias}`.startsWith(toComplete)
296-
) {
297-
this.completions.push({
298-
value: `-${option.alias}`,
299-
description: option.description,
300-
});
301-
} else if (!isShortFlag && name.startsWith(cleanToComplete)) {
302-
this.completions.push({
303-
value: `--${name}`,
304-
description: option.description,
305-
});
355+
for (const optionCommand of this.optionCommandsFor(command)) {
356+
for (const [name, option] of optionCommand.options) {
357+
if (
358+
isShortFlag &&
359+
option.alias &&
360+
`-${option.alias}`.startsWith(toComplete)
361+
) {
362+
this.completions.push({
363+
value: `-${option.alias}`,
364+
description: option.description,
365+
});
366+
} else if (!isShortFlag && name.startsWith(cleanToComplete)) {
367+
this.completions.push({
368+
value: `--${name}`,
369+
description: option.description,
370+
});
371+
}
306372
}
307373
}
308374
}
309375
}
310376

377+
private optionCommandsFor(command: Command): Command[] {
378+
if (!this.optionLookupMode) {
379+
return [command];
380+
}
381+
382+
if (this.optionLookupMode === 'local') {
383+
return [command];
384+
}
385+
386+
const commands: Command[] = [];
387+
let candidate: Command | undefined = command;
388+
while (candidate) {
389+
commands.unshift(candidate);
390+
candidate = candidate.parent;
391+
}
392+
return commands;
393+
}
394+
395+
private findOptionInScope(
396+
command: Command,
397+
optionName: string
398+
): Option | undefined {
399+
for (const candidate of this.optionCommandsFor(command)) {
400+
const option = this.findOption(candidate, optionName);
401+
if (option) return option;
402+
}
403+
return undefined;
404+
}
405+
406+
private findOptionForCompletion(
407+
command: Command,
408+
optionName: string
409+
): Option | undefined {
410+
if (this.optionLookupMode) {
411+
return this.findOptionInScope(command, optionName);
412+
}
413+
return this.findOption(command, optionName);
414+
}
415+
311416
// find option by name or alias
312417
private findOption(command: Command, optionName: string): Option | undefined {
313418
let option = command.options.get(optionName);
@@ -432,7 +537,7 @@ export class RootCommand extends Command {
432537
const [matchedCommand] = this.matchCommand(previousArgs);
433538
const lastPrevArg = previousArgs[previousArgs.length - 1];
434539

435-
if (this.shouldCompleteFlags(lastPrevArg, toComplete)) {
540+
if (this.shouldCompleteFlags(matchedCommand, lastPrevArg, toComplete)) {
436541
this.handleFlagCompletion(
437542
matchedCommand,
438543
previousArgs,
Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
import { execFile } from 'node:child_process';
2+
import { createRequire } from 'node:module';
3+
import { promisify } from 'node:util';
4+
import { describe, expect, it } from 'vitest';
5+
6+
const execFileAsync = promisify(execFile);
7+
const require = createRequire(import.meta.url);
8+
const tsxCli = require.resolve('tsx/cli');
9+
const fixture = 'tests/fixtures/commander-option-scope.ts';
10+
11+
async function complete(
12+
args: string[],
13+
positionalOptions: boolean
14+
): Promise<string[]> {
15+
const { stdout } = await execFileAsync(
16+
process.execPath,
17+
[tsxCli, fixture, ...args],
18+
{
19+
cwd: process.cwd(),
20+
env: {
21+
...process.env,
22+
COMMANDER_POSITIONAL: positionalOptions ? '1' : '0',
23+
},
24+
}
25+
);
26+
27+
return stdout
28+
.split('\n')
29+
.filter((line) => line && !line.startsWith(':'))
30+
.map((line) => line.split('\t')[0]);
31+
}
32+
33+
describe('Commander option scope', () => {
34+
describe('default options', () => {
35+
it('uses the root option when a subcommand reuses its short flag', async () => {
36+
await expect(complete(['serve', '-c', ''], false)).resolves.toEqual([
37+
'top',
38+
'global',
39+
]);
40+
});
41+
42+
it('keeps a non-conflicting serve long option available', async () => {
43+
await expect(
44+
complete(['serve', '--serve-choice', ''], false)
45+
).resolves.toEqual(['serve', 'local']);
46+
});
47+
48+
it('keeps root option values available after a subcommand', async () => {
49+
await expect(
50+
complete(['serve', '--root-choice', ''], false)
51+
).resolves.toEqual(['top', 'global']);
52+
});
53+
54+
it('suggests root option names after a subcommand', async () => {
55+
await expect(complete(['serve', '--root-c'], false)).resolves.toEqual([
56+
'--root-choice',
57+
]);
58+
});
59+
60+
it('uses root option arity for a colliding short flag', async () => {
61+
const values = await complete(['serve', '-b', ''], false);
62+
63+
expect(values).toEqual(expect.arrayContaining(['prod', 'staging']));
64+
expect(values).not.toEqual(expect.arrayContaining(['blue', 'green']));
65+
});
66+
67+
it('uses an ancestor option before a nested command option', async () => {
68+
await expect(
69+
complete(['serve', 'nested', '-a', ''], false)
70+
).resolves.toEqual(['parent', 'ancestor']);
71+
});
72+
});
73+
74+
describe('positional options', () => {
75+
it('uses the subcommand option when it reuses a root short flag', async () => {
76+
await expect(complete(['serve', '-c', ''], true)).resolves.toEqual([
77+
'serve',
78+
'local',
79+
]);
80+
});
81+
82+
it('does not complete root option values after a subcommand', async () => {
83+
await expect(
84+
complete(['serve', '--root-choice', ''], true)
85+
).resolves.toEqual([]);
86+
});
87+
88+
it('does not suggest root option names after a subcommand', async () => {
89+
await expect(complete(['serve', '--root-c'], true)).resolves.toEqual([]);
90+
});
91+
92+
it('still accepts root options before the subcommand', async () => {
93+
await expect(
94+
complete(['--root-choice', 'top', 'serve', '-c', ''], true)
95+
).resolves.toEqual(['serve', 'local']);
96+
});
97+
98+
it('uses serve option arity for a colliding short flag', async () => {
99+
await expect(complete(['serve', '-b', ''], true)).resolves.toEqual([
100+
'blue',
101+
'green',
102+
]);
103+
});
104+
105+
it('limits nested lookup to the matched command', async () => {
106+
await expect(
107+
complete(['serve', 'nested', '-a', ''], true)
108+
).resolves.toEqual(['deep', 'nested']);
109+
});
110+
});
111+
});

0 commit comments

Comments
 (0)