Skip to content

Commit

Permalink
Prevent adding version option with flags already in use
Browse files Browse the repository at this point in the history
  • Loading branch information
aweebit committed Aug 3, 2023
1 parent 5c87223 commit deb3bdf
Showing 1 changed file with 18 additions and 7 deletions.
25 changes: 18 additions & 7 deletions lib/command.js
Original file line number Diff line number Diff line change
Expand Up @@ -501,18 +501,32 @@ Expecting one of '${allowedValues.join("', '")}'`);
}

/**
* Add an option.
* Check for option flag conflicts.
* Register option if no conflicts found.
* Throw otherwise.
*
* @param {Option} option
* @return {Command} `this` command for chaining
* @api private
*/
addOption(option) {

_registerOption(option) {
const matchingOption = (option.short && this._findOption(option.short)) ||
(option.long && this._findOption(option.long));
if (matchingOption) {
throw new Error(`Cannot add option '${option.flags}'${this._name && ` to '${this._name}'`} since an option using same flag has already been added
- conflicts with option '${matchingOption.flags}'`);
}
this.options.push(option);
}

/**
* Add an option.
*
* @param {Option} option
* @return {Command} `this` command for chaining
*/
addOption(option) {
this._registerOption(option);

const oname = option.name();
const name = option.attributeName();
Expand All @@ -528,9 +542,6 @@ Expecting one of '${allowedValues.join("', '")}'`);
this.setOptionValueWithSource(name, option.defaultValue, 'default');
}

// register the option
this.options.push(option);

// handler for cli and env supplied values
const handleOptionValue = (val, invalidValueMessage, valueSource) => {
// val is null for optional option used without an optional-argument.
Expand Down Expand Up @@ -1827,7 +1838,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
description = description || 'output the version number';
const versionOption = this.createOption(flags, description);
this._versionOptionName = versionOption.attributeName();
this.options.push(versionOption);
this._registerOption(versionOption);
this.on('option:' + versionOption.name(), () => {
this._outputConfiguration.writeOut(`${str}\n`);
this._exit(0, 'commander.version', str);
Expand Down

0 comments on commit deb3bdf

Please sign in to comment.