diff --git a/lib/command.js b/lib/command.js index 53e3d736d..080b84d7c 100644 --- a/lib/command.js +++ b/lib/command.js @@ -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(); @@ -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. @@ -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);