Add support for variadic to choices (#1454)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by John Gee · committed by GitHub · parent 02b40ec · Browse files · 2 files·+35 added−6 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+35 added−6 removed
- tests:+18 added−0 removed
- other:+17 added−6 removed
Provenance
- Commit
09dfb67- Tree
77fa36a- Author
John Gee <john@ruru.gen.nz>- Committer
GitHub <noreply@github.com>- Parent
02b40ec
2 files changed+35 added−6 removed
modified:tests/options.variadic.test.js+18 added
38 unmodified lines3940414243444546474849505152535455565758596061626364106 unmodified linesExpand all38 unmodified lines program.parse(['--required', 'one', '--required', 'two'], { from: 'user' }); expect(program.opts().required).toEqual(['one', 'two']); });
test('when variadic used with choices and one value then set in array', () => { const program = new commander.Command(); program .addOption(new commander.Option('-r,--required <value...>').choices(['one', 'two']));
program.parse(['--required', 'one'], { from: 'user' }); expect(program.opts().required).toEqual(['one']); });
test('when variadic used with choices and two values then set in array', () => { const program = new commander.Command(); program .addOption(new commander.Option('-r,--required <value...>').choices(['one', 'two']));
program.parse(['--required', 'one', 'two'], { from: 'user' }); expect(program.opts().required).toEqual(['one', 'two']); });
test('when variadic with short combined argument then not variadic', () => { const program = new commander.Command(); program .option('-r,--required <value...>')106 unmodified linesExpand allmodified:index.js+17 added-6 removed
424 unmodified lines425 return this;426 };427 428 /**429+ * @api private430+ */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+440+ /**441 * Only allow option value to be one of choices.442 *443 * @param {string[]} values444 * @return {Option}445 */446 447 choices(values) {448 this.argChoices = values;437- this.parseArg = (arg) => {449+ this.parseArg = (arg, previous) => {450 if (!values.includes(arg)) {451 throw new InvalidOptionArgumentError(`Allowed choices are ${values.join(', ')}.`);452 }453+ if (this.variadic) {454+ return this._concatValue(arg, previous);455+ }456 return arg;457 };458 return this;459 };530 unmodified lines990 }991 throw err;992 }993 } 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);995 }996 997 // unassigned or boolean value998 if (typeof oldValue === 'boolean' || typeof oldValue === 'undefined') {1209 unmodified lines