Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Run default command if it's not just * #1062

Merged
merged 12 commits into from Dec 11, 2019
Merged
23 changes: 15 additions & 8 deletions index.js
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) {
shadowspawn marked this conversation as resolved.
Show resolved Hide resolved
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 {
shadowspawn marked this conversation as resolved.
Show resolved Hide resolved
} 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');
shadowspawn marked this conversation as resolved.
Show resolved Hide resolved
}

return this;
Expand Down
10 changes: 10 additions & 0 deletions tests/command.asterisk.test.js
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', () => {
shadowspawn marked this conversation as resolved.
Show resolved Hide resolved
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