Skip to content

Commit

Permalink
feat(args): support shared args (unjs#154)
Browse files Browse the repository at this point in the history
  • Loading branch information
fu050409 committed Jul 5, 2024
1 parent 53cd585 commit 632e55d
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 5 deletions.
16 changes: 12 additions & 4 deletions src/command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,12 @@ export interface RunCommandOptions {
export async function runCommand<T extends ArgsDef = ArgsDef>(
cmd: CommandDef<T>,
opts: RunCommandOptions,
sharedArgs?: T,
): Promise<{ result: unknown }> {
const cmdArgs = await resolveValue(cmd.args || {});
const cmdArgs = await resolveValue({
...(cmd.args || ({} as T)),
...sharedArgs,
});
const parsedArgs = parseArgs<T>(opts.rawArgs, cmdArgs);

const context: CommandContext<T> = {
Expand Down Expand Up @@ -51,9 +55,13 @@ export async function runCommand<T extends ArgsDef = ArgsDef>(
}
const subCommand = await resolveValue(subCommands[subCommandName]);
if (subCommand) {
await runCommand(subCommand, {
rawArgs: opts.rawArgs.slice(subCommandArgIndex + 1),
});
await runCommand(
subCommand,
{
rawArgs: opts.rawArgs.slice(subCommandArgIndex + 1),
},
cmd.sharedArgs,
);
}
} else if (!cmd.run) {
throw new CLIError(`No command specified.`, "E_NO_COMMAND");
Expand Down
1 change: 1 addition & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ export type SubCommandsDef = Record<string, Resolvable<CommandDef<any>>>;
export type CommandDef<T extends ArgsDef = ArgsDef> = {
meta?: Resolvable<CommandMeta>;
args?: Resolvable<T>;
sharedArgs?: Resolvable<T>;
subCommands?: Resolvable<SubCommandsDef>;
setup?: (context: CommandContext<T>) => any | Promise<any>;
cleanup?: (context: CommandContext<T>) => any | Promise<any>;
Expand Down
5 changes: 4 additions & 1 deletion src/usage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,10 @@ export async function renderUsage<T extends ArgsDef = ArgsDef>(
parent?: CommandDef<T>,
) {
const cmdMeta = await resolveValue(cmd.meta || {});
const cmdArgs = resolveArgs(await resolveValue(cmd.args || {}));
const cmdArgs = [
...resolveArgs(await resolveValue(cmd.args || {})),
...resolveArgs(await resolveValue(cmd.sharedArgs || {})),
];
const parentMeta = await resolveValue(parent?.meta || {});

const commandName =
Expand Down

0 comments on commit 632e55d

Please sign in to comment.