From 4e6386290ad486de56b5bdd62f1af385331a4be7 Mon Sep 17 00:00:00 2001 From: Benjamin Fischer <61995275+c4spar@users.noreply.github.com> Date: Sat, 5 Aug 2023 19:51:06 +0200 Subject: [PATCH] fix(command): command action not triggered for standalone options without action handler (#654) --- command/command.ts | 16 +++---- command/test/command/standalone_test.ts | 63 +++++++++++++++++++++++++ 2 files changed, 71 insertions(+), 8 deletions(-) create mode 100644 command/test/command/standalone_test.ts diff --git a/command/command.ts b/command/command.ts index 22546080..6c55bcde 100644 --- a/command/command.ts +++ b/command/command.ts @@ -1766,15 +1766,15 @@ export class Command< await Promise.all( ctx.actions.map((action) => action.call(this, options, ...args)), ); - } - if (ctx.standalone) { - return { - options, - args, - cmd: this, - literal: this.literalArgs, - }; + if (ctx.standalone) { + return { + options, + args, + cmd: this, + literal: this.literalArgs, + }; + } } return await this.execute(options, args); diff --git a/command/test/command/standalone_test.ts b/command/test/command/standalone_test.ts new file mode 100644 index 00000000..071eb759 --- /dev/null +++ b/command/test/command/standalone_test.ts @@ -0,0 +1,63 @@ +import { + assertEquals, + assertRejects, + assertSpyCalls, + spy, +} from "../../../dev_deps.ts"; +import { Command } from "../../command.ts"; + +Deno.test("[command] should execute standalone option action", async () => { + const actionSpy = spy(); + const optionActionSpy = spy(); + + const cmd = new Command() + .throwErrors() + .option("--standalone", "description ...", { + action: optionActionSpy, + standalone: true, + }) + .action(actionSpy); + + const { options } = await cmd.parse(["--standalone"]); + + assertSpyCalls(optionActionSpy, 1); + assertSpyCalls(actionSpy, 0); + assertEquals(options, { standalone: true }); +}); + +Deno.test("[command] should execute main action with standalone option", async () => { + const actionSpy = spy(); + + const cmd = new Command() + .throwErrors() + .option("--standalone", "description ...", { + standalone: true, + }) + .action(actionSpy); + + const { options } = await cmd.parse(["--standalone"]); + + assertSpyCalls(actionSpy, 1); + assertEquals(options, { standalone: true }); +}); + +Deno.test("[command] should throw an error if standalone option is combined with other options", async () => { + const actionSpy = spy(); + + const cmd = new Command() + .throwErrors() + .option("--standalone", "description ...", { + standalone: true, + }) + .option("--foo", "description ...") + .action(actionSpy); + + await assertRejects( + () => + cmd.parse( + ["--standalone", "--foo"], + ), + Error, + 'Option "--standalone" cannot be combined with other options.', + ); +});