File tree 2 files changed +35
-6
lines changed
2 files changed +35
-6
lines changed Original file line number Diff line number Diff line change @@ -425,6 +425,18 @@ class Option {
425
425
return this ;
426
426
} ;
427
427
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
+
428
440
/**
429
441
* Only allow option value to be one of choices.
430
442
*
@@ -434,10 +446,13 @@ class Option {
434
446
435
447
choices ( values ) {
436
448
this . argChoices = values ;
437
- this . parseArg = ( arg ) => {
449
+ this . parseArg = ( arg , previous ) => {
438
450
if ( ! values . includes ( arg ) ) {
439
451
throw new InvalidOptionArgumentError ( `Allowed choices are ${ values . join ( ', ' ) } .` ) ;
440
452
}
453
+ if ( this . variadic ) {
454
+ return this . _concatValue ( arg , previous ) ;
455
+ }
441
456
return arg ;
442
457
} ;
443
458
return this ;
@@ -976,11 +991,7 @@ class Command extends EventEmitter {
976
991
throw err ;
977
992
}
978
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 ) ;
984
995
}
985
996
986
997
// unassigned or boolean value
Original file line number Diff line number Diff line change @@ -40,6 +40,24 @@ describe('variadic option with required value', () => {
40
40
expect ( program . opts ( ) . required ) . toEqual ( [ 'one' , 'two' ] ) ;
41
41
} ) ;
42
42
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
+
43
61
test ( 'when variadic with short combined argument then not variadic' , ( ) => {
44
62
const program = new commander . Command ( ) ;
45
63
program
You can’t perform that action at this time.
0 commit comments