diff --git a/index.js b/index.js index c85f72552..055afa8f9 100644 --- a/index.js +++ b/index.js @@ -1679,6 +1679,17 @@ Read more on https://git.io/JJc0W`); this._exit(process.exitCode || 0, 'commander.help', '(outputHelp)'); }; + /** + * Sets the default command for the program. + * + * @param {string} command The name of the command + * @api public + */ + default(name) { + this._defaultCommandName = name; + return this; + } + /** * Output help information and exit. Display for error situations. * diff --git a/tests/command.default.test.js b/tests/command.default.test.js index cd9b93c0f..ce06e6802 100644 --- a/tests/command.default.test.js +++ b/tests/command.default.test.js @@ -90,3 +90,38 @@ describe('default added command', () => { expect(actionMock).toHaveBeenCalled(); }); }); + +describe('default set command', () => { + function makeProgram() { + const actionMock = jest.fn(); + const defaultCmd = new commander.Command('default') + .allowUnknownOption() + .action(actionMock); + + const program = new commander.Command(); + program + .command('other'); + program + .addCommand(defaultCmd); + program.default('default'); + return { program, actionMock }; + } + + test('when default subcommand and no command then call default', () => { + const { program, actionMock } = makeProgram(); + program.parse('node test.js'.split(' ')); + expect(actionMock).toHaveBeenCalled(); + }); + + test('when default subcommand and unrecognised argument then call default', () => { + const { program, actionMock } = makeProgram(); + program.parse('node test.js an-argument'.split(' ')); + expect(actionMock).toHaveBeenCalled(); + }); + + test('when default subcommand and unrecognised option then call default', () => { + const { program, actionMock } = makeProgram(); + program.parse('node test.js --an-option'.split(' ')); + expect(actionMock).toHaveBeenCalled(); + }); +}); diff --git a/typings/index.d.ts b/typings/index.d.ts index 479446d38..a3026d392 100644 --- a/typings/index.d.ts +++ b/typings/index.d.ts @@ -368,6 +368,11 @@ declare namespace commander { */ help(cb?: (str: string) => string): never; + /** + * Set the default command for a program. + */ + default(name: string): void; + /** * Add a listener (callback) for when events occur. (Implemented using EventEmitter.) *