Skip to content

Commit

Permalink
Improve backwards compatibility for command events (#1403)
Browse files Browse the repository at this point in the history
* Improve backwards compatibility for command events

* Implement tests for legacy command event
  • Loading branch information
shadowspawn committed Dec 1, 2020
1 parent 9b087c8 commit bd538aa
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 2 deletions.
7 changes: 5 additions & 2 deletions index.js
Expand Up @@ -1490,6 +1490,7 @@ Read more on https://git.io/JJc0W`);
this.unknownOption(parsed.unknown[0]);
}

const commandEvent = `command:${this.name()}`;
if (this._actionHandler) {
const args = this.args.slice();
this._args.forEach((arg, i) => {
Expand All @@ -1501,9 +1502,11 @@ Read more on https://git.io/JJc0W`);
});

this._actionHandler(args);
this.emit('command:' + this.name(), operands, unknown);
if (this.parent) this.parent.emit(commandEvent, operands, unknown); // legacy
} else if (this.parent && this.parent.listenerCount(commandEvent)) {
this.parent.emit(commandEvent, operands, unknown); // legacy
} else if (operands.length) {
if (this._findCommand('*')) {
if (this._findCommand('*')) { // legacy
this._dispatchSubcommand('*', operands, unknown);
} else if (this.listenerCount('command:*')) {
this.emit('command:*', operands, unknown);
Expand Down
38 changes: 38 additions & 0 deletions tests/command.onCommand.test.js
@@ -0,0 +1,38 @@
const commander = require('../');

// The action handler used to be implemented using command events and listeners.
// Now, this is mostly just for backwards compatibility.

describe(".command('*')", () => {
test('when action handler for subcommand then emit command:subcommand', () => {
const mockListener = jest.fn();
const program = new commander.Command();
program
.command('sub')
.action(() => {});
program.on('command:sub', mockListener);
program.parse(['sub'], { from: 'user' });
expect(mockListener).toHaveBeenCalled();
});

test('when no action handler for subcommand then still emit command:subcommand', () => {
const mockListener = jest.fn();
const program = new commander.Command();
program
.command('sub');
program.on('command:sub', mockListener);
program.parse(['sub'], { from: 'user' });
expect(mockListener).toHaveBeenCalled();
});

test('when subcommand has argument then emit command:subcommand with argument', () => {
const mockListener = jest.fn();
const program = new commander.Command();
program
.command('sub <file>')
.action(() => {});
program.on('command:sub', mockListener);
program.parse(['sub', 'file'], { from: 'user' });
expect(mockListener).toHaveBeenCalledWith(['file'], []);
});
});

0 comments on commit bd538aa

Please sign in to comment.