Skip to content

Commit 09dfb67

Browse files
authored
Add support for variadic to choices (#1454)
1 parent 02b40ec commit 09dfb67

File tree

2 files changed

+35
-6
lines changed

2 files changed

+35
-6
lines changed

index.js

+17-6
Original file line numberDiff line numberDiff line change
@@ -425,6 +425,18 @@ class Option {
425425
return this;
426426
};
427427

428+
/**
429+
* @api private
430+
*/
431+
432+
_concatValue(value, previous) {
433+
if (previous === this.defaultValue || !Array.isArray(previous)) {
434+
return [value];
435+
}
436+
437+
return previous.concat(value);
438+
}
439+
428440
/**
429441
* Only allow option value to be one of choices.
430442
*
@@ -434,10 +446,13 @@ class Option {
434446

435447
choices(values) {
436448
this.argChoices = values;
437-
this.parseArg = (arg) => {
449+
this.parseArg = (arg, previous) => {
438450
if (!values.includes(arg)) {
439451
throw new InvalidOptionArgumentError(`Allowed choices are ${values.join(', ')}.`);
440452
}
453+
if (this.variadic) {
454+
return this._concatValue(arg, previous);
455+
}
441456
return arg;
442457
};
443458
return this;
@@ -976,11 +991,7 @@ class Command extends EventEmitter {
976991
throw err;
977992
}
978993
} else if (val !== null && option.variadic) {
979-
if (oldValue === defaultValue || !Array.isArray(oldValue)) {
980-
val = [val];
981-
} else {
982-
val = oldValue.concat(val);
983-
}
994+
val = option._concatValue(val, oldValue);
984995
}
985996

986997
// unassigned or boolean value

tests/options.variadic.test.js

+18
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,24 @@ describe('variadic option with required value', () => {
4040
expect(program.opts().required).toEqual(['one', 'two']);
4141
});
4242

43+
test('when variadic used with choices and one value then set in array', () => {
44+
const program = new commander.Command();
45+
program
46+
.addOption(new commander.Option('-r,--required <value...>').choices(['one', 'two']));
47+
48+
program.parse(['--required', 'one'], { from: 'user' });
49+
expect(program.opts().required).toEqual(['one']);
50+
});
51+
52+
test('when variadic used with choices and two values then set in array', () => {
53+
const program = new commander.Command();
54+
program
55+
.addOption(new commander.Option('-r,--required <value...>').choices(['one', 'two']));
56+
57+
program.parse(['--required', 'one', 'two'], { from: 'user' });
58+
expect(program.opts().required).toEqual(['one', 'two']);
59+
});
60+
4361
test('when variadic with short combined argument then not variadic', () => {
4462
const program = new commander.Command();
4563
program

0 commit comments

Comments
 (0)