From 632e55d3ffd6152603df2e00e16af70edcdd4998 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=8B=8F=E5=90=91=E5=A4=9C?= Date: Fri, 5 Jul 2024 22:54:34 +0800 Subject: [PATCH 1/2] feat(args): support shared args (#154) --- src/command.ts | 16 ++++++++++++---- src/types.ts | 1 + src/usage.ts | 5 ++++- 3 files changed, 17 insertions(+), 5 deletions(-) diff --git a/src/command.ts b/src/command.ts index 1abfe44..b986fc9 100644 --- a/src/command.ts +++ b/src/command.ts @@ -17,8 +17,12 @@ export interface RunCommandOptions { export async function runCommand( cmd: CommandDef, 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(opts.rawArgs, cmdArgs); const context: CommandContext = { @@ -51,9 +55,13 @@ export async function runCommand( } 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"); diff --git a/src/types.ts b/src/types.ts index a622922..a0475c3 100644 --- a/src/types.ts +++ b/src/types.ts @@ -90,6 +90,7 @@ export type SubCommandsDef = Record>>; export type CommandDef = { meta?: Resolvable; args?: Resolvable; + sharedArgs?: Resolvable; subCommands?: Resolvable; setup?: (context: CommandContext) => any | Promise; cleanup?: (context: CommandContext) => any | Promise; diff --git a/src/usage.ts b/src/usage.ts index cb4a794..ef6d409 100644 --- a/src/usage.ts +++ b/src/usage.ts @@ -20,7 +20,10 @@ export async function renderUsage( parent?: CommandDef, ) { 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 = From 57e3c43821be64938355beb5e23f189c30532a11 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=8B=8F=E5=90=91=E5=A4=9C?= Date: Fri, 5 Jul 2024 23:00:16 +0800 Subject: [PATCH 2/2] fix(args): pass shared args --- src/command.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/command.ts b/src/command.ts index b986fc9..8dec8be 100644 --- a/src/command.ts +++ b/src/command.ts @@ -60,7 +60,7 @@ export async function runCommand( { rawArgs: opts.rawArgs.slice(subCommandArgIndex + 1), }, - cmd.sharedArgs, + { ...(await resolveValue(cmd.sharedArgs)), ...sharedArgs }, ); } } else if (!cmd.run) {