Skip to content

Commit

Permalink
fix(command): optional arguments are validated also if they are not s…
Browse files Browse the repository at this point in the history
…pecified on the command line (#101)
  • Loading branch information
c4spar committed Oct 18, 2020
1 parent 5b30372 commit e3d61d7
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 8 deletions.
15 changes: 9 additions & 6 deletions command/command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1006,7 +1006,10 @@ export class Command<O = any, A extends Array<any> = any> {
}
} else {
for (const expectedArg of this.getArguments()) {
if (!expectedArg.optionalValue && !args.length) {
if (!args.length) {
if (expectedArg.optionalValue) {
break;
}
throw this.error(
new Error(`Missing argument: ${expectedArg.name}`),
);
Expand All @@ -1029,7 +1032,7 @@ export class Command<O = any, A extends Array<any> = any> {
label: "Argument",
type: expectedArg.type,
name: expectedArg.name,
value: args.shift() ?? "",
value: args.shift() as string,
});
}

Expand Down Expand Up @@ -1085,10 +1088,10 @@ export class Command<O = any, A extends Array<any> = any> {
}

/**
* Get parent command from global executed command.
* Be sure, to call this method only inside an action handler. Unless this or any child command was executed,
* this method returns always undefined.
*/
* Get parent command from global executed command.
* Be sure, to call this method only inside an action handler. Unless this or any child command was executed,
* this method returns always undefined.
*/
public getGlobalParent(): Command | undefined {
return this._globalParent;
}
Expand Down
15 changes: 13 additions & 2 deletions command/test/command/arguments_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,9 @@ function cmd() {
`${label} ${name} must be a valid ${type} but got: ${value}`,
);
}
return value;
})
.arguments("[foo:string] [bar:number] [baz:boolean] [color:color]");
.arguments("<foo:string> [bar:number] [baz:boolean] [color:color]");
}

Deno.test("'-' as argument", async () => {
Expand All @@ -24,7 +25,7 @@ Deno.test("'-' as argument", async () => {

Deno.test("valid command argument types", async () => {
const { args } = await cmd().parse(["abc", "123", "true", "red"]);
assertEquals(args, ["abc", 123, true]);
assertEquals(args, ["abc", 123, true, "red"]);
});

Deno.test("invalid number command argument type", async () => {
Expand All @@ -37,6 +38,16 @@ Deno.test("invalid number command argument type", async () => {
);
});

Deno.test("missing command arguments", async () => {
await assertThrowsAsync(
async () => {
await cmd().parse();
},
Error,
"Missing argument(s): foo",
);
});

Deno.test("invalid boolean command argument type", async () => {
await assertThrowsAsync(
async () => {
Expand Down

0 comments on commit e3d61d7

Please sign in to comment.