Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
23 changes: 15 additions & 8 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -360,8 +360,12 @@ Command.prototype.action = function(fn) {
fn.apply(self, actionArgs);
};
var parent = this.parent || this;
var name = parent === this ? '*' : this._name;
parent.on('command:' + name, listener);
if (parent === this) {
parent.on('program-action', listener);
} else {
parent.on('command:' + this._name, listener);
}

if (this._alias) parent.on('command:' + this._alias, listener);
return this;
};
Expand Down Expand Up @@ -793,25 +797,28 @@ Command.prototype.normalize = function(args) {
Command.prototype.parseArgs = function(args, unknown) {
var name;

if (this.listeners('program-action').length && this.listeners('command:*').length) {
console.error("Can't have listeners for both command:* and for the main program");
this._exit(1);
}

if (args.length) {
name = args[0];
if (this.listeners('command:' + name).length) {
this.emit('command:' + args.shift(), args, unknown);
} else {
} else if (this.listeners('command:*').length) {
this.emit('command:*', args, unknown);
} else {
this.emit('program-action', args, unknown);
}
} else {
outputHelpIfNecessary(this, unknown);

// If there were no args and we have unknown options,
// then they are extraneous and we need to error.
if (unknown.length > 0 && !this.defaultExecutable) {
this.unknownOption(unknown[0]);
}
if (this.commands.length === 0 &&
this._args.filter(function(a) { return a.required; }).length === 0) {
this.emit('command:*');
}
this.emit('program-action');
}

return this;
Expand Down
10 changes: 10 additions & 0 deletions tests/command.asterisk.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,16 @@ test('when no arguments then asterisk action not called', () => {
expect(mockAction).not.toHaveBeenCalled();
});

test('when no arguments with asterisk handler then asterisk action not called', () => {
const mockAction = jest.fn();
const program = new commander.Command();
program
.command('*')
.action(mockAction);
program.parse(['node', 'test']);
expect(mockAction).not.toHaveBeenCalled();
});

test('when recognised command then asterisk action not called', () => {
const mockAction = jest.fn();
const program = new commander.Command();
Expand Down