Skip to content

Commit 308af85

Browse files
committed
fix(cli): harden generated completions
1 parent 459cee5 commit 308af85

2 files changed

Lines changed: 94 additions & 13 deletions

File tree

‎src/cli/completion-cli.test.ts‎

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ function createCompletionProgram(): Command {
1414

1515
const gateway = program.command("gateway").description("Gateway commands");
1616
gateway.option("--force", "Force the action");
17+
gateway.option("-t, --token <token>", "Gateway token");
1718

1819
gateway.command("status").description("Show gateway status").option("--json", "JSON output");
1920
gateway.command("restart").description("Restart gateway");
@@ -90,7 +91,8 @@ describe("completion-cli", () => {
9091
expect(script).toContain("if ($commandPath -eq 'gateway') {");
9192
expect(script).toContain("if ($commandPath -eq 'gateway status') {");
9293
expect(script).not.toContain("if ($commandPath -eq 'openclaw gateway') {");
93-
expect(script).toContain("$completions = @('status','restart','--force')");
94+
expect(script).toContain("$completions = @('status','restart','--force','--token')");
95+
expect(script).not.toContain("'-t,'");
9496
});
9597

9698
it("generates fish completions for root and nested command contexts", () => {
@@ -100,10 +102,21 @@ describe("completion-cli", () => {
100102
'complete -c openclaw -n "__fish_use_subcommand" -a "gateway" -d \'Gateway commands\'',
101103
);
102104
expect(script).toContain(
103-
'complete -c openclaw -n "__fish_seen_subcommand_from gateway" -a "status" -d \'Show gateway status\'',
105+
'complete -c openclaw -n "__openclaw_command_path_matches gateway" -a "status" -d \'Show gateway status\'',
104106
);
105107
expect(script).toContain(
106-
"complete -c openclaw -n \"__fish_seen_subcommand_from gateway\" -l force -d 'Force the action'",
108+
"complete -c openclaw -n \"__openclaw_command_path_matches gateway\" -l force -d 'Force the action'",
107109
);
110+
expect(script).toContain(
111+
"complete -c openclaw -n \"__openclaw_command_path_matches gateway status\" -l json -d 'JSON output'",
112+
);
113+
expect(script).toContain("set -l root_boolean_options -v --verbose");
114+
});
115+
116+
it("generates Bash completions without comma-suffixed short flags", () => {
117+
const script = getCompletionScript("bash", createCompletionProgram());
118+
119+
expect(script).toContain("--token");
120+
expect(script).not.toContain("-t,");
108121
});
109122
});

‎src/cli/completion-cli.ts‎

Lines changed: 78 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,75 @@ export function getCompletionScript(shell: CompletionShell, program: Command): s
3434
return generateFishCompletion(program);
3535
}
3636

37+
function splitOptionFlags(flags: string): string[] {
38+
return flags.split(/[ ,|]+/u).filter(Boolean);
39+
}
40+
41+
function preferredCompletionFlag(flags: string): string {
42+
const parts = splitOptionFlags(flags);
43+
return parts.find((flag) => flag.startsWith("--")) ?? parts[0] ?? flags;
44+
}
45+
46+
function fishWords(values: readonly string[]): string {
47+
return values.join(" ");
48+
}
49+
50+
function fishOptionFlags(options: Command["options"], wantsValue: boolean): string[] {
51+
return options.flatMap((option) => {
52+
if (Boolean(option.required || option.optional) !== wantsValue) {
53+
return [];
54+
}
55+
return splitOptionFlags(option.flags).filter((flag) => flag.startsWith("-"));
56+
});
57+
}
58+
59+
function generateFishPathHelper(program: Command, rootCmd: string): string {
60+
const rootValueOptions = fishOptionFlags(program.options, true);
61+
const rootBooleanOptions = fishOptionFlags(program.options, false);
62+
return `
63+
function __${rootCmd}_command_path_matches
64+
set -l tokens (commandline -opc)
65+
set -e tokens[1]
66+
set -l root_value_options ${fishWords(rootValueOptions)}
67+
set -l root_boolean_options ${fishWords(rootBooleanOptions)}
68+
set -l command_tokens
69+
set -l skip_next 0
70+
for token in $tokens
71+
if test $skip_next -eq 1
72+
set skip_next 0
73+
continue
74+
end
75+
if test (count $command_tokens) -eq 0
76+
set -l flag (string split -m1 "=" -- $token)[1]
77+
if contains -- $flag $root_boolean_options
78+
continue
79+
end
80+
if contains -- $flag $root_value_options
81+
if not string match -q -- "*=*" $token
82+
set skip_next 1
83+
end
84+
continue
85+
end
86+
end
87+
if string match -q -- "-*" $token
88+
continue
89+
end
90+
set -a command_tokens $token
91+
end
92+
for i in (seq (count $argv))
93+
if test "$command_tokens[$i]" != "$argv[$i]"
94+
return 1
95+
end
96+
end
97+
return 0
98+
end
99+
`;
100+
}
101+
102+
function fishCommandPathCondition(rootCmd: string, parents: readonly string[]): string {
103+
return `__${rootCmd}_command_path_matches ${parents.join(" ")}`;
104+
}
105+
37106
async function writeCompletionCache(params: {
38107
program: Command;
39108
shells: CompletionShell[];
@@ -285,7 +354,7 @@ _${rootCmd}_completion() {
285354
prev="\${COMP_WORDS[COMP_CWORD-1]}"
286355
287356
# Simple top-level completion for now
288-
opts="${program.commands.map((c) => c.name()).join(" ")} ${program.options.map((o) => o.flags.split(" ")[0]).join(" ")}"
357+
opts="${program.commands.map((c) => c.name()).join(" ")} ${program.options.map((o) => preferredCompletionFlag(o.flags)).join(" ")}"
289358
290359
case "\${prev}" in
291360
${program.commands.map((cmd) => generateBashSubcommand(cmd)).join("\n ")}
@@ -307,7 +376,7 @@ function generateBashSubcommand(cmd: Command): string {
307376
// This is a naive implementation; fully recursive bash completion is complex to generate as a single string without improved state tracking.
308377
// For now, let's provide top-level command recognition.
309378
return `${cmd.name()})
310-
opts="${cmd.commands.map((c) => c.name()).join(" ")} ${cmd.options.map((o) => o.flags.split(" ")[0]).join(" ")}"
379+
opts="${cmd.commands.map((c) => c.name()).join(" ")} ${cmd.options.map((o) => preferredCompletionFlag(o.flags)).join(" ")}"
311380
COMPREPLY=( $(compgen -W "\${opts}" -- \${cur}) )
312381
return 0
313382
;;`;
@@ -322,7 +391,7 @@ function generatePowerShellCompletion(program: Command): string {
322391

323392
// Command completion for this level
324393
const subCommands = cmd.commands.map((c) => c.name());
325-
const options = cmd.options.map((o) => o.flags.split(/[ ,|]+/)[0]); // Take first flag
394+
const options = cmd.options.map((o) => preferredCompletionFlag(o.flags));
326395
const allCompletions = [...subCommands, ...options].map((s) => `'${s}'`).join(",");
327396

328397
if (fullPath.length > 0 && allCompletions.length > 0) {
@@ -363,7 +432,7 @@ Register-ArgumentCompleter -Native -CommandName ${rootCmd} -ScriptBlock {
363432
364433
# Root command
365434
if ($commandPath -eq "") {
366-
$completions = @(${program.commands.map((c) => `'${c.name()}'`).join(",")}, ${program.options.map((o) => `'${o.flags.split(" ")[0]}'`).join(",")})
435+
$completions = @(${program.commands.map((c) => `'${c.name()}'`).join(",")}, ${program.options.map((o) => `'${preferredCompletionFlag(o.flags)}'`).join(",")})
367436
$completions | Where-Object { $_ -like "$wordToComplete*" } | ForEach-Object {
368437
[System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterName', $_)
369438
}
@@ -376,11 +445,9 @@ Register-ArgumentCompleter -Native -CommandName ${rootCmd} -ScriptBlock {
376445

377446
function generateFishCompletion(program: Command): string {
378447
const rootCmd = program.name();
379-
const segments: string[] = [];
448+
const segments: string[] = [generateFishPathHelper(program, rootCmd)];
380449

381450
const visit = (cmd: Command, parents: string[]) => {
382-
const cmdName = cmd.name();
383-
384451
// Root logic
385452
if (parents.length === 0) {
386453
// Subcommands of root
@@ -406,12 +473,13 @@ function generateFishCompletion(program: Command): string {
406473
);
407474
}
408475
} else {
476+
const condition = fishCommandPathCondition(rootCmd, parents);
409477
// Subcommands
410478
for (const sub of cmd.commands) {
411479
segments.push(
412480
buildFishSubcommandCompletionLine({
413481
rootCmd,
414-
condition: `__fish_seen_subcommand_from ${cmdName}`,
482+
condition,
415483
name: sub.name(),
416484
description: sub.description(),
417485
}),
@@ -422,7 +490,7 @@ function generateFishCompletion(program: Command): string {
422490
segments.push(
423491
buildFishOptionCompletionLine({
424492
rootCmd,
425-
condition: `__fish_seen_subcommand_from ${cmdName}`,
493+
condition,
426494
flags: opt.flags,
427495
description: opt.description,
428496
}),
@@ -431,7 +499,7 @@ function generateFishCompletion(program: Command): string {
431499
}
432500

433501
for (const sub of cmd.commands) {
434-
visit(sub, [...parents, cmdName]);
502+
visit(sub, parents.length === 0 ? [sub.name()] : [...parents, sub.name()]);
435503
}
436504
};
437505

0 commit comments

Comments
 (0)