Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 46 additions & 1 deletion lib/command.js
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,44 @@ class Command extends EventEmitter {
return this;
}

/**
* @param {string} names
* @param {string[]} aliases
* @param {Command} matchingCommand
* @return {string}
* @api private
*/

_getConflictingCommandNamesMessageDetail(name, aliases, matchingCommand) {
const matchingCommandNames = matchingCommand._aliases.concat(
matchingCommand._name
);
if (matchingCommandNames.includes(name)) return 'same name';
const matchingAlias = aliases.find(
alias => matchingCommandNames.includes(alias)
);
return `alias '${matchingAlias}'`;
}

/**
* @param {string} names
* @param {string[]} aliases
* @api private
*/

_checkForConflictingCommandNames(name, aliases = []) {
const names = aliases.concat(name);
const matchingCommand = names
.map(name => this._findCommand(name))
.filter(found => found)[0];
if (matchingCommand) {
const messageDetail = this._getConflictingCommandNamesMessageDetail(
name, aliases, matchingCommand
);
throw new Error(`Cannot add command '${name}'${this._name && ` to '${this._name}'`} since a command using the ${messageDetail} has already been added`);
}
}

/**
* Define a command.
*
Expand Down Expand Up @@ -143,6 +181,7 @@ class Command extends EventEmitter {
}
opts = opts || {};
const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
this._checkForConflictingCommandNames(name);

const cmd = this.createCommand(name);
if (desc) {
Expand Down Expand Up @@ -265,6 +304,7 @@ class Command extends EventEmitter {
throw new Error(`Command passed to .addCommand() must have a name
- specify the name in Command constructor or using .name()`);
}
this._checkForConflictingCommandNames(cmd._name, cmd._aliases);

opts = opts || {};
if (opts.isDefault) this._defaultCommandName = cmd._name;
Expand Down Expand Up @@ -1875,7 +1915,12 @@ Expecting one of '${allowedValues.join("', '")}'`);
command = this.commands[this.commands.length - 1];
}

if (alias === command._name) throw new Error('Command alias can\'t be the same as its name');
if (alias === command._name) {
throw new Error('Command alias can\'t be the same as its name');
}
if (command.parent?._findCommand(alias)) {
throw new Error(`Cannot add alias '${alias}' for subcommand '${command._name}'${command.parent._name && ` of '${command.parent._name}'`} since a subcommand with the same name or alias has already been added`);
}

command._aliases.push(alias);
return this;
Expand Down