Skip to content

Commit

Permalink
fix(command): option action not executed for options with no value (#148
Browse files Browse the repository at this point in the history
)
  • Loading branch information
c4spar committed Feb 7, 2021
1 parent 246035c commit c436221
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 19 deletions.
24 changes: 5 additions & 19 deletions command/command.ts
Expand Up @@ -4,7 +4,7 @@ import {
ValidationError,
} from "../flags/_errors.ts";
import { parseFlags } from "../flags/flags.ts";
import type { IFlagsResult } from "../flags/types.ts";
import type { IFlagOptions, IFlagsResult } from "../flags/types.ts";
import {
getPermissions,
hasPermission,
Expand Down Expand Up @@ -908,11 +908,11 @@ export class Command<O = any, A extends Array<any> = any> {
stopEarly: this._stopEarly,
allowEmpty: this._allowEmpty,
flags: this.getOptions(true),
parse: (type: ITypeInfo) => {
if (!action) {
action = this.getOptionAction(type.name);
parse: (type: ITypeInfo) => this.parseType(type),
option: (option: IFlagOptions) => {
if (!action && (option as IOption).action) {
action = (option as IOption).action;
}
return this.parseType(type);
},
});
return { ...result, action };
Expand Down Expand Up @@ -1038,20 +1038,6 @@ export class Command<O = any, A extends Array<any> = any> {
return params as A;
}

/**
* Returns the action or undefined of the given option.
* @param name Option name.
*/
private getOptionAction(name: string): IAction<O, A> | undefined {
const option: IOption<O, A> | undefined = this.getOption(
name.replace(/^(-)+/, ""),
true,
);
if (option?.action) {
return option?.action;
}
}

/**
* Handle error. If `throwErrors` is enabled the error will be returned,
* otherwise a formatted error message will be printed and `Deno.exit(1)`
Expand Down
24 changes: 24 additions & 0 deletions command/test/option/action_test.ts
Expand Up @@ -63,6 +63,30 @@ Deno.test("sub-command option action", async () => {
Deno.test("option action with dashed option name", async () => {
const stats: IStats = {};

const cmd = new Command()
.throwErrors()
.arguments("[beep:string] [boop:string]")
.option("-f, --foo-bar", "action ...", {
action: function (options, ...args) {
stats.context = this;
stats.options = options;
stats.args = args;
},
});

const { options, args } = await cmd.parse(["-f", "beep", "boop"]);

assert(stats.context, "option action not executed");
assertEquals(stats.context, cmd);
assertEquals(stats.options, { fooBar: true });
assertEquals(stats.args, ["beep", "boop"]);
assertEquals(stats.options, options);
assertEquals(stats.args, args);
});

Deno.test("option action with dashed option name and value", async () => {
const stats: IStats = {};

const cmd = new Command()
.throwErrors()
.arguments("[beep:string]")
Expand Down

0 comments on commit c436221

Please sign in to comment.