@@ -535,6 +535,25 @@ Expecting one of '${allowedValues.join("', '")}'`);
535
535
throw err ;
536
536
}
537
537
}
538
+ /**
539
+ * Check for option flag conflicts.
540
+ * Register option if no conflicts found.
541
+ * Throw otherwise.
542
+ *
543
+ * @param {Option } option
544
+ * @api private
545
+ */
546
+
547
+ _registerOption ( option ) {
548
+ const matchingOption = ( option . short && this . _findOption ( option . short ) ) ||
549
+ ( option . long && this . _findOption ( option . long ) ) ;
550
+ if ( matchingOption ) {
551
+ const matchingFlag = ( option . long && this . _findOption ( option . long ) ) ? option . long : option . short ;
552
+ throw new Error ( `Cannot add option '${ option . flags } '${ this . _name && ` to command '${ this . _name } '` } due to conflicting flag '${ matchingFlag } '
553
+ - already used by option '${ matchingOption . flags } '` ) ;
554
+ }
555
+ this . options . push ( option ) ;
556
+ }
538
557
539
558
/**
540
559
* Add an option.
@@ -543,6 +562,8 @@ Expecting one of '${allowedValues.join("', '")}'`);
543
562
* @return {Command } `this` command for chaining
544
563
*/
545
564
addOption ( option ) {
565
+ this . _registerOption ( option ) ;
566
+
546
567
const oname = option . name ( ) ;
547
568
const name = option . attributeName ( ) ;
548
569
@@ -557,9 +578,6 @@ Expecting one of '${allowedValues.join("', '")}'`);
557
578
this . setOptionValueWithSource ( name , option . defaultValue , 'default' ) ;
558
579
}
559
580
560
- // register the option
561
- this . options . push ( option ) ;
562
-
563
581
// handler for cli and env supplied values
564
582
const handleOptionValue = ( val , invalidValueMessage , valueSource ) => {
565
583
// val is null for optional option used without an optional-argument.
@@ -1824,8 +1842,9 @@ Expecting one of '${allowedValues.join("', '")}'`);
1824
1842
flags = flags || '-V, --version' ;
1825
1843
description = description || 'output the version number' ;
1826
1844
const versionOption = this . createOption ( flags , description ) ;
1827
- this . _versionOptionName = versionOption . attributeName ( ) ; // [sic] not defined in constructor, partly legacy, partly only needed at root
1828
- this . options . push ( versionOption ) ;
1845
+ this . _versionOptionName = versionOption . attributeName ( ) ;
1846
+ this . _registerOption ( versionOption ) ;
1847
+
1829
1848
this . on ( 'option:' + versionOption . name ( ) , ( ) => {
1830
1849
this . _outputConfiguration . writeOut ( `${ str } \n` ) ;
1831
1850
this . _exit ( 0 , 'commander.version' , str ) ;
0 commit comments