Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(args): support shared args #157

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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),
},
{ ...(await resolveValue(cmd.sharedArgs)), ...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