Files
openclaw/src/cli/program/action-reparse.ts
huangjianxiong 68e234f9e2 fix(cli): preserve usage-error exits for lazy reparses
Reparse nested lazy commands from the Commander root so unknown options keep the original argv and exit non-zero. Adds nested lazy-command coverage for the root rawArgs path. Fixes #92069.
2026-06-13 21:33:30 +08:00

43 lines
1.7 KiB
TypeScript

// Reparse support for lazy commands after their placeholder has been replaced.
import type { Command } from "commander";
import { buildParseArgv } from "../argv.js";
import { resolveActionArgs, resolveCommandOptionArgs } from "./helpers.js";
function buildFallbackArgv(program: Command, actionCommand: Command | undefined): string[] {
const actionArgsList = resolveActionArgs(actionCommand);
const parentOptionArgs =
actionCommand?.parent === program ? resolveCommandOptionArgs(program) : [];
return actionCommand?.name()
? [...parentOptionArgs, actionCommand.name(), ...actionArgsList]
: [...parentOptionArgs, ...actionArgsList];
}
function findRootCommand(cmd: Command): Command {
let current: Command = cmd;
while (current.parent) {
current = current.parent;
}
return current;
}
/** Rebuild argv from Commander action args and re-run parsing after lazy registration. */
export async function reparseProgramFromActionArgs(
program: Command,
actionArgs: unknown[],
): Promise<void> {
const actionCommand = actionArgs.at(-1) as Command | undefined;
// Use the true root program for argv reconstruction and parsing.
// For nested lazy commands (e.g. workspaces → audit), `program` is a sub-command
// whose rawArgs is cleared by Commander's restoreStateBeforeParse(). Only the
// root program retains the rawArgs set by _prepareUserArgs.
const rootProgram = findRootCommand(actionCommand ?? program);
const rawArgs = (rootProgram as Command & { rawArgs?: string[] }).rawArgs;
const fallbackArgv = buildFallbackArgv(program, actionCommand);
const parseArgv = buildParseArgv({
programName: rootProgram.name(),
rawArgs,
fallbackArgv,
});
await rootProgram.parseAsync(parseArgv);
}