Skip to content
Closed
Show file tree
Hide file tree
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
11 changes: 11 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down
35 changes: 35 additions & 0 deletions tests/command.default.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
});
});
5 changes: 5 additions & 0 deletions typings/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.)
*
Expand Down