Parse rework for nested commands (#1149)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* First cut at parse rework - skip asterisk tests - other tests runnning - nested commands untested - lots of details to check * Add check for requiredOption when calling executable subcommand * Set program name using supported approach * Add .addCommand, easy after previous work * Add support for default command using action handler - and remove stale _execs * Add implicitHelpCommand and change help flags description * Add implicit help command to help * Turn off implicit help command for most help tests * .addHelpCommand * Remove addHelpCommand from tests and make match more narrow * Use test of complete default help output * Add tests for whether implicit help appears in help * Add tests that help command dispatched to correct command * Add simple nested subcommand test * Add default command tests for action based subcommand * Remove mainModule, out of scope for current PR * Add legacy asterisk handling and tests * Add more initialisation so object in known state * Tests for addCommand * Add first cut at enhanced default error detection * Add test that addCommand requires name * Add block on automatic name generation for deeply nested executables * Add block on automatic name generation for deeply nested executables * Fix describe name for tests * Refine unknownCommand handling and add tests * Add suggestion to try help, when appropriate * Fix typo * Move common command configuration options in README, and add isDefault example program * Add isDefault and example to README * Add nested commands * Document .addHelpCommand, and tweaks * Remove old default command, and rework command:* example * Document .addCommand * Remove comment referring to removed code. * Revert the error tip "try --help", not happy with the wording * Say "unknown command", like "unknown option" * Set properties to null rather than undefined in constructor
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
27 files+763 added−338 removed
- tests:+363 added−51 removed
- other:+400 added−287 removed
Provenance
- Commit
1345f98- Tree
e84b5ac- Author
John Gee <john@ruru.gen.nz>- Committer
GitHub <noreply@github.com>- Parent
1691344
27 files changed+763 added−338 removed
modified:examples/custom-help+1 added-3 removed
7 unmodified lines8 .option('-f, --foo', 'enable some foo')9 .option('-b, --bar', 'enable some bar')10 .option('-B, --baz', 'enable some baz');11 12-// must be before .parse() since13-// node's emit() is immediate14-12+// must be before .parse()13 program.on('--help', function() {14 console.log('');15 console.log('Examples:');16 console.log('');7 unmodified linesadded:examples/defaultCommand.js+36 added
123456789101112131415161718192021222324252627282930313233343536// const commander = require('commander'); // (normal include)const commander = require('../'); // include commander in git clone of commander repoconst program = new commander.Command();
// Example program using the command configuration option isDefault to specify the default command.//// $ node defaultCommand.js build// build// $ node defaultCommand.js serve -p 8080// server on port 8080// $ node defaultCommand.js -p 443// server on port 443
program .command('build') .description('build web site for deployment') .action(() => { console.log('build'); });
program .command('deploy') .description('deploy web site to production') .action(() => { console.log('deploy'); });
program .command('serve', { isDefault: true }) .description('launch web server') .option('-p,--port <port_number>', 'web port') .action((opts) => { console.log(`server on port ${opts.port}`); });
program.parse(process.argv);modified:examples/deploy-6 removed
32 unmodified lines33 console.log(' $ deploy exec async');34 console.log();35 });36 37-program38- .command('*')39- .action(function(env) {40- console.log('deploying "%s"', env);41- });42-37 program.parse(process.argv);added:examples/nestedCommands.js+47 added
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647// const commander = require('commander'); // (normal include)const commander = require('../'); // include commander in git clone of commander repoconst program = new commander.Command();
// Commander supports nested subcommands.// .command() can add a subcommand with an action handler or an executable.// .addCommand() adds a prepared command with an actiomn handler.
// Example output://// $ node nestedCommands.js brew tea// brew tea// $ node nestedCommands.js heat jug// heat jug
// Add nested commands using `.command()`.const brew = program.command('brew');brew .command('tea') .action(() => { console.log('brew tea'); });brew .command('tea') .action(() => { console.log('brew tea'); });
// Add nested commands using `.addCommand().// The command could be created separately in another module.function makeHeatCommand() { const heat = new commander.Command('heat'); heat .command('jug') .action(() => { console.log('heat jug'); }); heat .command('pot') .action(() => { console.log('heat pot'); }); return heat;}program.addCommand(makeHeatCommand());
program.parse(process.argv);modified:tests/args.variadic.test.js+1 added-1 removed
123455678985 unmodified linesconst commander = require('../');
// Testing variadic arguments. Testing all the action arguments, but could test just variadicArg.
describe('.version', () => {describe('variadic argument', () => { // Optional. Use internal knowledge to suppress output to keep test output clean. let consoleErrorSpy;
beforeAll(() => {85 unmodified linesmodified:tests/command.action.test.js+7 added-1 removed
44 unmodified lines45 expect(actionMock).toHaveBeenCalledWith('my-file', program);46 });47 48 test('when .action on program with required argument and argument not supplied then action not called', () => {49+ // Optional. Use internal knowledge to suppress output to keep test output clean.50+ const consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => { });51 const actionMock = jest.fn();52 const program = new commander.Command();53 program54+ .exitOverride()55 .arguments('<file>')56 .action(actionMock);57+ expect(() => {54- program.parse(['node', 'test']);58+ program.parse(['node', 'test']);59+ }).toThrow();60 expect(actionMock).not.toHaveBeenCalled();61+ consoleErrorSpy.mockRestore();62 });63 64 // Changes made in #729 to call program action handler65 test('when .action on program and no arguments then action called', () => {72 unmodified linesadded:tests/command.addCommand.test.js+69 added
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869const commander = require('../');
// simple sanity check subcommand workstest('when addCommand and specify subcommand then called', () => { const program = new commander.Command(); const leafAction = jest.fn(); const sub = new commander.Command(); sub .name('sub') .action(leafAction); program .addCommand(sub);
program.parse('node test.js sub'.split(' ')); expect(leafAction).toHaveBeenCalled();});
test('when commands added using .addCommand and .command then internals similar', () => { const program1 = new commander.Command(); program1.command('sub'); const program2 = new commander.Command(); program2.addCommand(new commander.Command('sub'));
// This is a bit of a cheat to check using .addCommand() produces similar result to .command(), // since .command() is well tested and understood.
const cmd1 = program1.commands[0]; const cmd2 = program2.commands[0]; expect(cmd1.parent).toBe(program1); expect(cmd2.parent).toBe(program2);
for (const key of Object.keys(cmd1)) { switch (typeof cmd1[key]) { case 'string': case 'boolean': case 'number': case 'undefined': // Compare vaues in a way that will be readable in test failure message. expect(`${key}:${cmd1[key]}`).toEqual(`${key}:${cmd2[key]}`); break; } }});
test('when command without name passed to .addCommand then throw', () => { const program = new commander.Command(); const cmd = new commander.Command(); expect(() => { program.addCommand(cmd); }).toThrow();});
test('when executable command without custom executableFile passed to .addCommand then throw', () => { const program = new commander.Command(); const cmd = new commander.Command('sub'); cmd.command('exec', 'exec description'); expect(() => { program.addCommand(cmd); }).toThrow();});
test('when executable command with custom executableFile passed to .addCommand then ok', () => { const program = new commander.Command(); const cmd = new commander.Command('sub'); cmd.command('exec', 'exec description', { executableFile: 'custom' }); expect(() => { program.addCommand(cmd); }).not.toThrow();});modified:tests/command.allowUnknownOptions.test.js+1 added-1 removed
1 const commander = require('../');2 3 // Not testing output, just testing whether an error is detected.4 5-describe('.version', () => {5+describe('allowUnknownOption', () => {6 // Optional. Use internal knowledge to suppress output to keep test output clean.7 let consoleErrorSpy;8 9 beforeAll(() => {61 unmodified linesmodified:tests/command.asterisk.test.js+17 added-1 removed
9 unmodified lines10 //11 // Historical: the event 'command:*' used to also be shared by the action handler on the program.12 13 describe(".command('*')", () => {14+ // Use internal knowledge to suppress output to keep test output clean.15+ let writeMock;16+17+ beforeAll(() => {18+ writeMock = jest.spyOn(process.stdout, 'write').mockImplementation(() => { });19+ });20+21+ afterAll(() => {22+ writeMock.mockRestore();23+ });24+25 test('when no arguments then asterisk action not called', () => {26 const mockAction = jest.fn();27 const program = new commander.Command();28 program29+ .exitOverride() // to catch help30 .command('*')31 .action(mockAction);32+ try {20- program.parse(['node', 'test']);33+ program.parse(['node', 'test']);34+ } catch (err) {35+ ;36+ }37 expect(mockAction).not.toHaveBeenCalled();38 });39 40 test('when unrecognised argument then asterisk action called', () => {78 unmodified linesmodified:tests/command.commandHelp.test.js+2 added-2 removed
5 unmodified lines6 const program = new commander.Command();7 program8 .command('bare');9 const commandHelp = program.commandHelp();10- expect(commandHelp).toBe('Commands:\n bare\n');10+ expect(commandHelp).toMatch(/Commands:\n +bare\n/);11 });12 13 test('when program has command with optional arg then appears in commandHelp', () => {14 const program = new commander.Command();15 program16 .command('bare [bare-arg]');17 const commandHelp = program.commandHelp();18- expect(commandHelp).toEqual('Commands:\n bare [bare-arg]\n');18+ expect(commandHelp).toMatch(/Commands:\n +bare \[bare-arg\]\n/);19 });added:tests/command.default.test.js+61 added
1+const childProcess = require('child_process');2+const path = require('path');3+const commander = require('../');4+5+describe('default executable command', () => {6+ // Calling node explicitly so pm works without file suffix cross-platform.7+ const pm = path.join(__dirname, './fixtures/pm');8+9+ test('when default subcommand and no command then call default', (done) => {10+ childProcess.exec(`node ${pm}`, function(_error, stdout, stderr) {11+ expect(stdout).toBe('default\n');12+ done();13+ });14+ });15+16+ test('when default subcommand and unrecognised argument then call default with argument', (done) => {17+ childProcess.exec(`node ${pm} an-argument`, function(_error, stdout, stderr) {18+ expect(stdout).toBe("default\n[ 'an-argument' ]\n");19+ done();20+ });21+ });22+23+ test('when default subcommand and unrecognised option then call default with option', (done) => {24+ childProcess.exec(`node ${pm} --an-option`, function(_error, stdout, stderr) {25+ expect(stdout).toBe("default\n[ '--an-option' ]\n");26+ done();27+ });28+ });29+});30+31+describe('default action command', () => {32+ function makeProgram() {33+ const program = new commander.Command();34+ const actionMock = jest.fn();35+ program36+ .command('other');37+ program38+ .command('default', { isDefault: true })39+ .allowUnknownOption()40+ .action(actionMock);41+ return { program, actionMock };42+ }43+44+ test('when default subcommand and no command then call default', () => {45+ const { program, actionMock } = makeProgram();46+ program.parse('node test.js'.split(' '));47+ expect(actionMock).toHaveBeenCalled();48+ });49+50+ test('when default subcommand and unrecognised argument then call default with argument', () => {51+ const { program, actionMock } = makeProgram();52+ program.parse('node test.js an-argument'.split(' '));53+ expect(actionMock).toHaveBeenCalled();54+ });55+56+ test('when default subcommand and unrecognised option then call default with option', () => {57+ const { program, actionMock } = makeProgram();58+ program.parse('node test.js --an-option'.split(' '));59+ expect(actionMock).toHaveBeenCalled();60+ });61+});deleted:tests/command.executableSubcommand.default.test.js-27 removed
1-const childProcess = require('child_process');2-const path = require('path');3-4-// Calling node explicitly so pm works without file suffix cross-platform.5-6-const pm = path.join(__dirname, './fixtures/pm');7-8-test('when default subcommand and no command then call default', (done) => {9- childProcess.exec(`node ${pm}`, function(_error, stdout, stderr) {10- expect(stdout).toBe('default\n');11- done();12- });13-});14-15-test('when default subcommand and unrecognised argument then call default with argument', (done) => {16- childProcess.exec(`node ${pm} an-argument`, function(_error, stdout, stderr) {17- expect(stdout).toBe("default\n[ 'an-argument' ]\n");18- done();19- });20-});21-22-test('when default subcommand and unrecognised option then call default with option', (done) => {23- childProcess.exec(`node ${pm} --an-option`, function(_error, stdout, stderr) {24- expect(stdout).toBe("default\n[ '--an-option' ]\n");25- done();26- });27-});modified:tests/command.executableSubcommand.lookup.test.js+2 added-2 removed
10 unmodified lines11 if (process.platform === 'win32') {12 // Get uncaught thrown error on Windows13 expect(stderr.length).toBeGreaterThan(0);14 } else {15- expect(stderr).toBe('error: pm-list(1) does not exist, try --help\n');15+ expect(stderr).toBe('error: pm-list(1) does not exist\n');16 }17 done();18 });19 });3 unmodified lines23 if (process.platform === 'win32') {24 // Get uncaught thrown error on Windows25 expect(stderr.length).toBeGreaterThan(0);26 } else {27- expect(stderr).toBe('error: pm-list(1) does not exist, try --help\n');27+ expect(stderr).toBe('error: pm-list(1) does not exist\n');28 }29 done();30 });31 });76 unmodified linesmodified:tests/command.exitOverride.test.js+18 added-2 removed
49 unmodified lines50 expect(consoleErrorSpy).toHaveBeenCalled();51 expectCommanderError(caughtErr, 1, 'commander.unknownOption', "error: unknown option '-m'");52 });53 54+ test('when specify unknown command then throw CommanderError', () => {55+ const program = new commander.Command();56+ program57+ .exitOverride()58+ .command('sub');59+60+ let caughtErr;61+ try {62+ program.parse(['node', 'test', 'oops']);63+ } catch (err) {64+ caughtErr = err;65+ }66+67+ expect(consoleErrorSpy).toHaveBeenCalled();68+ expectCommanderError(caughtErr, 1, 'commander.unknownCommand', "error: unknown command 'oops'");69+ });70+71 // Same error as above, but with custom handler.72 test('when supply custom handler then throw custom error', () => {73 const customError = new commander.CommanderError(123, 'custom-code', 'custom-message');74 const program = new commander.Command();76 unmodified lines151 } catch (err) {152 caughtErr = err;153 }154 138- // This is effectively treated as a deliberate request for help, rather than an error.155 expect(writeSpy).toHaveBeenCalled();140- expectCommanderError(caughtErr, 0, 'commander.helpDisplayed', '(outputHelp)');156+ expectCommanderError(caughtErr, 1, 'commander.help', '(outputHelp)');157 });158 159 test('when specify --version then throw CommanderError', () => {160 const myVersion = '1.2.3';86 unmodified linesmodified:tests/command.help.test.js+4 added-3 removed
12 unmodified lines13 const expectedHelpInformation =14 `Usage: test [options] [command]15 16 Options:17- -h, --help output usage information17+ -h, --help display help for command18 19 Commands:20 my-command <file>21+ help [command] display help for command22 `;23 23- program.parse(['node', 'test']);24+ program.name('test');25 const helpInformation = program.helpInformation();26 expect(helpInformation).toBe(expectedHelpInformation);27 });28 1 unmodified line30 const program = new commander.Command();31 program32 .command('simple-command')33 .description('custom-description');33- program.parse(['node', 'test']);34+ program._help = 'test';35 const helpInformation = program.helpInformation();36 expect(helpInformation).toMatch(/simple-command +custom-description/);37 });38 59 unmodified linesadded:tests/command.helpCommand.test.js+100 added
1+const commander = require('../');2+3+describe('help command listed in helpInformation', () => {4+ test('when program has no subcommands then no automatic help command', () => {5+ const program = new commander.Command();6+ const helpInformation = program.helpInformation();7+ expect(helpInformation).not.toMatch(/help \[command\]/);8+ });9+10+ test('when program has no subcommands and add help command then has help command', () => {11+ const program = new commander.Command();12+ program.addHelpCommand(true);13+ const helpInformation = program.helpInformation();14+ expect(helpInformation).toMatch(/help \[command\]/);15+ });16+17+ test('when program has subcommands then has automatic help command', () => {18+ const program = new commander.Command();19+ program.command('foo');20+ const helpInformation = program.helpInformation();21+ expect(helpInformation).toMatch(/help \[command\]/);22+ });23+24+ test('when program has subcommands and suppress help command then no help command', () => {25+ const program = new commander.Command();26+ program.addHelpCommand(false);27+ program.command('foo');28+ const helpInformation = program.helpInformation();29+ expect(helpInformation).not.toMatch(/help \[command\]/);30+ });31+32+ test('when add custom help command then custom help command', () => {33+ const program = new commander.Command();34+ program.addHelpCommand('help command', 'help description');35+ const helpInformation = program.helpInformation();36+ expect(helpInformation).toMatch(/help command +help description/);37+ });38+});39+40+describe('help command processed on correct command', () => {41+ // Use internal knowledge to suppress output to keep test output clean.42+ let consoleErrorSpy;43+ let writeSpy;44+45+ beforeAll(() => {46+ consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => { });47+ writeSpy = jest.spyOn(process.stdout, 'write').mockImplementation(() => { });48+ });49+50+ afterEach(() => {51+ consoleErrorSpy.mockClear();52+ writeSpy.mockClear();53+ });54+55+ afterAll(() => {56+ consoleErrorSpy.mockRestore();57+ writeSpy.mockRestore();58+ });59+60+ test('when "program help" then program', () => {61+ const program = new commander.Command();62+ program.exitOverride();63+ program.command('sub1');64+ program.exitOverride(() => { throw new Error('program'); });65+ expect(() => {66+ program.parse('node test.js help'.split(' '));67+ }).toThrow('program');68+ });69+70+ test('when "program help sub1" then sub1', () => {71+ const program = new commander.Command();72+ program.exitOverride();73+ const sub1 = program.command('sub1');74+ sub1.exitOverride(() => { throw new Error('sub1'); });75+ expect(() => {76+ program.parse('node test.js help sub1'.split(' '));77+ }).toThrow('sub1');78+ });79+80+ test('when "program sub1 help sub2" then sub2', () => {81+ const program = new commander.Command();82+ program.exitOverride();83+ const sub1 = program.command('sub1');84+ const sub2 = sub1.command('sub2');85+ sub2.exitOverride(() => { throw new Error('sub2'); });86+ expect(() => {87+ program.parse('node test.js sub1 help sub2'.split(' '));88+ }).toThrow('sub2');89+ });90+91+ test('when default command and "program help" then program', () => {92+ const program = new commander.Command();93+ program.exitOverride();94+ program.command('sub1', { isDefault: true });95+ program.exitOverride(() => { throw new Error('program'); });96+ expect(() => {97+ program.parse('node test.js help'.split(' '));98+ }).toThrow('program');99+ });100+});added:tests/command.nested.test.js+12 added
1+const commander = require('../');2+3+test('when call nested subcommand then runs', () => {4+ const program = new commander.Command();5+ const leafAction = jest.fn();6+ program7+ .command('sub1')8+ .command('sub2')9+ .action(leafAction);10+ program.parse('node test.js sub1 sub2'.split(' '));11+ expect(leafAction).toHaveBeenCalled();12+});added:tests/command.unknownCommand.test.js+53 added
1+const commander = require('../');2+3+describe('unknownOption', () => {4+ // Optional. Use internal knowledge to suppress output to keep test output clean.5+ let consoleErrorSpy;6+7+ beforeAll(() => {8+ consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => { });9+ });10+11+ afterEach(() => {12+ consoleErrorSpy.mockClear();13+ });14+15+ afterAll(() => {16+ consoleErrorSpy.mockRestore();17+ });18+19+ test('when unknown argument in simple program then no error', () => {20+ const program = new commander.Command();21+ program.parse('node test.js unknown'.split(' '));22+ });23+24+ test('when unknown command but action handler then no error', () => {25+ const program = new commander.Command();26+ program.command('sub');27+ program28+ .action(() => { });29+ program.parse('node test.js unknown'.split(' '));30+ });31+32+ test('when unknown command but listener then no error', () => {33+ const program = new commander.Command();34+ program.command('sub');35+ program36+ .on('command:*', () => { });37+ program.parse('node test.js unknown'.split(' '));38+ });39+40+ test('when unknown command then error', () => {41+ const program = new commander.Command();42+ program43+ .exitOverride()44+ .command('sub');45+ let caughtErr;46+ try {47+ program.parse('node test.js unknown'.split(' '));48+ } catch (err) {49+ caughtErr = err;50+ }51+ expect(caughtErr.code).toBe('commander.unknownCommand');52+ });53+});modified:tests/command.unknownOption.test.js+1 added-1 removed
1 const commander = require('../');2 3 // Checking for detection of unknown options, including regression tests for some past issues.4 5-describe('.version', () => {5+describe('unknownOption', () => {6 // Optional. Use internal knowledge to suppress output to keep test output clean.7 let consoleErrorSpy;8 9 beforeAll(() => {76 unmodified linesmodified:tests/command.usage.test.js+4 added-4 removed
1 unmodified line2 3 test('when default usage and check program help then starts with default usage', () => {4 const program = new commander.Command();5 6- program.parse(['node', 'test']);6+ program.name('test');7 const helpInformation = program.helpInformation();8 9 expect(helpInformation).toMatch(new RegExp('^Usage: test \\[options\\]'));10 });3 unmodified lines14 const program = new commander.Command();15 program16 .usage(myUsage);17 18- program.parse(['node', 'test']);18+ program.name('test');19 const helpInformation = program.helpInformation();20 21 expect(helpInformation).toMatch(new RegExp(`^Usage: test ${myUsage}`));22 });2 unmodified lines25 const program = new commander.Command();26 const subCommand = program27 .command('info');28 29- program.parse(['node', 'test']);29+ program.name('test');30 const helpInformation = subCommand.helpInformation();31 32 expect(helpInformation).toMatch(new RegExp('^Usage: test info \\[options\\]'));33 });4 unmodified lines38 const subCommand = program39 .command('info')40 .usage(myUsage);41 42- program.parse(['node', 'test']);42+ program.name('test');43 const helpInformation = subCommand.helpInformation();44 45 expect(helpInformation).toMatch(new RegExp(`^Usage: test info ${myUsage}`));46 });modified:tests/helpwrap.test.js+8 added-5 removed
1 const commander = require('../');2 3 // Test auto wrap and indent with some manual strings.4+// Fragile tests with complete help output.5 6 test('when long option description then wrap and indent', () => {7 const oldColumns = process.stdout.columns;8 process.stdout.columns = 80;7 unmodified lines16 Options:17 -x -extra-long-option-switch kjsahdkajshkahd kajhsd akhds kashd kajhs dkha18 dkh aksd ka dkha kdh kasd ka kahs dkh sdkh19 askdh aksd kashdk ahsd kahs dkha skdh19- -h, --help output usage information20+ -h, --help display help for command21 `;22 23 expect(program.helpInformation()).toBe(expectedOutput);24 process.stdout.columns = oldColumns;11 unmodified lines36 37 Options:38 -x -extra-long-option <value> kjsahdkajshkahd kajhsd akhds (default: "aaa39 bbb ccc ddd eee fff ggg")39- -h, --help output usage information40+ -h, --help display help for command41 `;42 43 expect(program.helpInformation()).toBe(expectedOutput);44 process.stdout.columns = oldColumns;11 unmodified lines56 `Usage: [options] [command]57 58 Options:59 -x -extra-long-option-switch x59- -h, --help output usage information60+ -h, --help display help for command61 62 Commands:63 alpha Lorem mollit quis dolor ex do eu quis ad insa64 a commodo esse.65+ help [command] display help for command66 `;67 68 expect(program.helpInformation()).toBe(expectedOutput);69 process.stdout.columns = oldColumns;11 unmodified lines81 const expectedOutput =82 `Usage: [options] [command]83 84 Options:83- -h, --help output usage information85+ -h, --help display help for command86 87 Commands:88 1234567801234567890x ${commandDescription}89+ help [command] display help for command90 `;91 92 expect(program.helpInformation()).toBe(expectedOutput);93 process.stdout.columns = oldColumns;20 unmodified lines114 115 Time can also be specified using special values:116 "dawn" - From night to sunrise.117 115- -h, --help output usage information118+ -h, --help display help for command119 `;120 121 expect(program.helpInformation()).toBe(expectedOutput);122 process.stdout.columns = oldColumns;3 unmodified linesmodified:tests/options.mandatory.test.js+3 added-1 removed
217 unmodified lines218 .exitOverride()219 .command('sub')220 .requiredOption('--subby <type>', 'description')221 .action((cmd) => {});222+ program223+ .command('sub2');224 225 expect(() => {224- program.parse(['node', 'test']);226+ program.parse(['node', 'test', 'sub2']);227 }).not.toThrow();228 });229 });230 50 unmodified linesmodified:typings/commander-tests.ts+4 added-3 removed
71 unmodified lines72 .option('-f, --foo', 'enable some foo')73 .option('-b, --bar', 'enable some bar')74 .option('-B, --baz', 'enable some baz');75 76-// must be before .parse() since77-// node's emit() is immediate78-76+// must be before .parse()77 program.on('--help', () => {78 console.log(' Examples:');79 console.log('');80 console.log(' $ custom-help --help');29 unmodified lines110 program111 .command("name1", "description")112 .command("name2", "description", { isDefault:true })113 114+const preparedCommand = new program.Command('prepared');115+program.addCommand(preparedCommand);116+117 program118 .exitOverride();119 120 program.exitOverride((err):never => {23 unmodified linesmodified:typings/index.d.ts+6 added-8 removed
78 unmodified lines79 */80 command(nameAndArgs: string, description: string, opts?: commander.CommandOptions): Command;81 82 /**83- * Define argument syntax for the top-level command.84- *85- * @returns Command for chaining83+ * Add a prepared subcommand.84+ * 85+ * @returns parent command for chaining86 */87- arguments(desc: string): Command;87+ addCommand(cmd: Command): Command;88 89 /**90- * Parse expected `args`.90+ * Define argument syntax for the top-level command.91 *92- * For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`.93- *92 * @returns Command for chaining93 */96- parseExpectedArgs(args: string[]): Command;94+ arguments(desc: string): Command;95 96 /**97 * Register callback to use as replacement for calling process.exit.98 */230 unmodified linesmodified:index.js+248 added-220 removed
3 unmodified lines4 5 var EventEmitter = require('events').EventEmitter;6 var spawn = require('child_process').spawn;7 var path = require('path');8-var dirname = path.dirname;9-var basename = path.basename;8 var fs = require('fs');9 10 /**11 * Inherit `Command` from `EventEmitter.prototype`.109 unmodified lines121 122 function Command(name) {123 this.commands = [];124 this.options = [];127- this._execs = new Set();125 this._allowUnknownOption = false;126 this._args = [];127 this._name = name || '';128 this._optionValues = {};129 this._storeOptionsAsProperties = true; // backwards compatible by default130 this._passCommandToAction = true; // backwards compatible by default131 this._actionResults = [];132+ this._actionHandler = null;133+ this._executableHandler = false;134+ this._executableFile = null; // custom name for executable135+ this._defaultCommandName = null;136+ this._exitCallback = null;137 138+ this._noHelp = false;139 this._helpFlags = '-h, --help';137- this._helpDescription = 'output usage information';140+ this._helpDescription = 'display help for command';141 this._helpShortFlag = '-h';142 this._helpLongFlag = '--help';143+ this._hasImplicitHelpCommand = undefined; // Deliberately undefined, not decided whether true or false144+ this._helpCommandName = 'help';145+ this._helpCommandnameAndArgs = 'help [command]';146+ this._helpCommandDescription = 'display help for command';147 }148 149 /**150 * Define a command.34 unmodified lines185 var cmd = new Command(args.shift());186 187 if (desc) {188 cmd.description(desc);182- this.executables = true;183- this._execs.add(cmd._name);184- if (opts.isDefault) this.defaultExecutable = cmd._name;189+ cmd._executableHandler = true;190 }191+ if (opts.isDefault) this._defaultCommandName = cmd._name;192+193 cmd._noHelp = !!opts.noHelp;194 cmd._helpFlags = this._helpFlags;195 cmd._helpDescription = this._helpDescription;196 cmd._helpShortFlag = this._helpShortFlag;197 cmd._helpLongFlag = this._helpLongFlag;198+ cmd._helpCommandName = this._helpCommandName;199+ cmd._helpCommandnameAndArgs = this._helpCommandnameAndArgs;200+ cmd._helpCommandDescription = this._helpCommandDescription;201 cmd._exitCallback = this._exitCallback;202 cmd._storeOptionsAsProperties = this._storeOptionsAsProperties;203 cmd._passCommandToAction = this._passCommandToAction;204 195- cmd._executableFile = opts.executableFile; // Custom name for executable file205+ cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor206 this.commands.push(cmd);197- cmd.parseExpectedArgs(args);207+ cmd._parseExpectedArgs(args);208 cmd.parent = this;209 210 if (desc) return this;211 return cmd;212 };213 214 /**215+ * Add a prepared subcommand.216+ *217+ * @param {Command} cmd - new subcommand218+ * @return {Command} parent command for chaining219+ * @api public220+ */221+222+Command.prototype.addCommand = function(cmd) {223+ if (!cmd._name) throw new Error('Command passed to .AddCommand must have a name');224+225+ // To keep things simple, block automatic name generation for deeply nested executables.226+ // Fail fast and detect when adding rather than later when parsing.227+ function checkExplicitNames(commandArray) {228+ commandArray.forEach((cmd) => {229+ if (cmd._executableHandler && !cmd._executableFile) {230+ throw new Error(`Must specify executableFile for deeply nested executable: ${cmd.name()}`);231+ }232+ checkExplicitNames(cmd.commands);233+ });234+ }235+ checkExplicitNames(cmd.commands);236+237+ this.commands.push(cmd);238+ cmd.parent = this;239+ return this;240+};241+242+/**243 * Define argument syntax for the top-level command.244 *245 * @api public246 */247 248 Command.prototype.arguments = function(desc) {211- return this.parseExpectedArgs(desc.split(/ +/));249+ return this._parseExpectedArgs(desc.split(/ +/));250 };251 252 /**215- * Add an implicit `help [cmd]` subcommand216- * which invokes `--help` for the given command.253+ * Override default decision whether to add implicit help command.254 *255+ * addHelpCommand() // force on256+ * addHelpCommand(false); // force off257+ * addHelpCommand('help [cmd]', 'display help for [cmd]'); // force on with custom detais258+ *259+ * @return {Command} for chaining260+ * @api public261+ */262+263+Command.prototype.addHelpCommand = function(enableOrNameAndArgs, description) {264+ if (enableOrNameAndArgs === false) {265+ this._hasImplicitHelpCommand = false;266+ } else {267+ this._hasImplicitHelpCommand = true;268+ if (typeof enableOrNameAndArgs === 'string') {269+ this._helpCommandName = enableOrNameAndArgs.split(' ')[0];270+ this._helpCommandnameAndArgs = enableOrNameAndArgs;271+ }272+ this._helpCommandDescription = description || this._helpCommandDescription;273+ }274+ return this;275+};276+277+/**278+ * @return {boolean}279 * @api private280 */281 221-Command.prototype.addImplicitHelpCommand = function() {222- this.command('help [cmd]', 'display help for [cmd]');282+Command.prototype._lazyHasImplicitHelpCommand = function() {283+ if (this._hasImplicitHelpCommand === undefined) {284+ this._hasImplicitHelpCommand = this.commands.length && !this._actionHandler && !this._findCommand('help');285+ }286+ return this._hasImplicitHelpCommand;287 };288 289 /**290 * Parse expected `args`.1 unmodified line292 * For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`.293 *294 * @param {Array} args295 * @return {Command} for chaining232- * @api public296+ * @api private297 */298 235-Command.prototype.parseExpectedArgs = function(args) {299+Command.prototype._parseExpectedArgs = function(args) {300 if (!args.length) return;301 var self = this;302 args.forEach(function(arg) {303 var argDetails = {82 unmodified lines386 */387 388 Command.prototype.action = function(fn) {389 var self = this;326- var listener = function(args, unknown) {327- // Parse any so-far unknown options328- args = args || [];329- unknown = unknown || [];330-331- var parsed = self.parseOptions(unknown);332-333- // Output help if necessary334- outputHelpIfRequested(self, parsed.unknown);335- self._checkForMissingMandatoryOptions();336-337- // If there are still any unknown options, then we simply die.338- if (parsed.unknown.length > 0) {339- self.unknownOption(parsed.unknown[0]);340- }341-342- args = args.concat(parsed.operands, parsed.unknown);343-344- self._args.forEach(function(expectedArg, i) {345- if (expectedArg.required && args[i] == null) {346- self.missingArgument(expectedArg.name);347- } else if (expectedArg.variadic) {348- if (i !== self._args.length - 1) {349- self.variadicArgNotLast(expectedArg.name);350- }351-352- args[i] = args.splice(i);353- }354- });355-356- // The .action callback takes an extra parameter which is the command itself.390+ var listener = function(args) {391+ // The .action callback takes an extra parameter which is the command or options.392 var expectedArgsCount = self._args.length;393 var actionArgs = args.slice(0, expectedArgsCount);394 if (self._passCommandToAction) {395 actionArgs[expectedArgsCount] = self;12 unmodified lines408 rootCommand = rootCommand.parent;409 }410 rootCommand._actionResults.push(actionResult);411 };377- var parent = this.parent || this;378- if (parent === this) {379- parent.on('program-command', listener);380- } else {381- parent.on('command:' + this._name, listener);382- }383-384- if (this._alias) parent.on('command:' + this._alias, listener);412+ this._actionHandler = listener;413 return this;414 };415 416 /**35 unmodified lines452 if (option.negate || option.optional || option.required || typeof defaultValue === 'boolean') {453 // when --no-foo we make sure default is true, unless a --foo option is already defined454 if (option.negate) {455 const positiveLongFlag = option.long.replace(/^--no-/, '--');428- defaultValue = self.optionFor(positiveLongFlag) ? self._getOptionValue(name) : true;456+ defaultValue = self._findOption(positiveLongFlag) ? self._getOptionValue(name) : true;457 }458 // preassign only if we have a default459 if (defaultValue !== undefined) {460 self._setOptionValue(name, defaultValue);188 unmodified lines649 * @api public650 */651 652 Command.prototype.parse = function(argv) {625- // implicit help626- if (this.executables) this.addImplicitHelpCommand();627-653 // store raw args654 this.rawArgs = argv;655 631- // guess name632- this._name = this._name || basename(argv[1], '.js');656+ // Guess name, used in usage in help.657+ this._name = this._name || path.basename(argv[1], path.extname(argv[1]));658 634- // github-style sub-commands with no sub-command635- if (this.executables && argv.length < 3 && !this.defaultExecutable) {636- // this user needs help637- argv.push(this._helpLongFlag);638- }659+ this._parseCommand([], argv.slice(2));660 640- // process argv, leaving off first two args which are app and scriptname.641- const parsed = this.parseOptions(argv.slice(2));642- const args = parsed.operands.concat(parsed.unknown);643- this.args = args.slice();644-645- var result = this.parseArgs(parsed.operands, parsed.unknown);646-647- if (args[0] === 'help' && args.length === 1) this.help();648-649- // Note for future: we could return early if we found an action handler in parseArgs, as none of following code needed?650-651- // <cmd> --help652- if (args[0] === 'help') {653- args[0] = args[1];654- args[1] = this._helpLongFlag;655- } else {656- // If calling through to executable subcommand we could check for help flags before failing,657- // but a somewhat unlikely case since program options not passed to executable subcommands.658- // Wait for reports to see if check needed and what usage pattern is.659- this._checkForMissingMandatoryOptions();660- }661-662- // executable sub-commands663- // (Debugging note for future: args[0] is not right if an action has been called)664- var name = result.args[0];665- var subCommand = null;666-667- // Look for subcommand668- if (name) {669- subCommand = this.commands.find(function(command) {670- return command._name === name;671- });672- }673-674- // Look for alias675- if (!subCommand && name) {676- subCommand = this.commands.find(function(command) {677- return command.alias() === name;678- });679- if (subCommand) {680- name = subCommand._name;681- args[0] = name;682- }683- }684-685- // Look for default subcommand686- if (!subCommand && this.defaultExecutable) {687- name = this.defaultExecutable;688- args.unshift(name);689- subCommand = this.commands.find(function(command) {690- return command._name === name;691- });692- }693-694- if (this._execs.has(name)) {695- return this.executeSubCommand(argv, args, subCommand ? subCommand._executableFile : undefined);696- }697-698- return result;661+ return this;662 };663 664 /**665 * Parse `argv`, setting options and invoking commands when defined.3 unmodified lines669 * @param {Array} argv670 * @return {Promise}671 * @api public672 */673+674 Command.prototype.parseAsync = function(argv) {675 this.parse(argv);676 return Promise.all(this._actionResults);677 };678 679 /**680 * Execute a sub-command executable.681 *718- * @param {Array} argv719- * @param {Array} args720- * @param {Array} unknown721- * @param {String} executableFile682 * @api private683 */684 725-Command.prototype.executeSubCommand = function(argv, args, executableFile) {726- if (!args.length) this.help();685+Command.prototype._executeSubCommand = function(subcommand, args) {686+ args = args.slice();687+ let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows.688+ const sourceExt = ['.js', '.ts', '.mjs'];689 728- var isExplicitJS = false; // Whether to use node to launch "executable"690+ // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.691+ this._checkForMissingMandatoryOptions();692 730- // executable731- var pm = argv[1];693+ // Want the entry script as the reference for command name and directory for searching for other files.694+ const scriptPath = this.rawArgs[1];695+696+ let baseDir;697+ try {698+ const resolvedLink = fs.realpathSync(scriptPath);699+ baseDir = path.dirname(resolvedLink);700+ } catch (e) {701+ baseDir = '.'; // dummy, probably not going to find executable!702+ }703+704 // name of the subcommand, like `pm-install`733- var bin = basename(pm, path.extname(pm)) + '-' + args[0];734- if (executableFile != null) {735- bin = executableFile;736- // Check for same extensions as we scan for below so get consistent launch behaviour.737- var executableExt = path.extname(executableFile);738- isExplicitJS = executableExt === '.js' || executableExt === '.ts' || executableExt === '.mjs';705+ let bin = path.basename(scriptPath, path.extname(scriptPath)) + '-' + subcommand._name;706+ if (subcommand._executableFile) {707+ bin = subcommand._executableFile;708 }709 741- // In case of globally installed, get the base dir where executable742- // subcommand file should be located at743- var baseDir;744-745- var resolvedLink = fs.realpathSync(pm);746-747- baseDir = dirname(resolvedLink);748-749- // prefer local `./<bin>` to bin in the $PATH750- var localBin = path.join(baseDir, bin);751-752- // whether bin file is a js script with explicit `.js` or `.ts` extension753- if (exists(localBin + '.js')) {754- bin = localBin + '.js';755- isExplicitJS = true;756- } else if (exists(localBin + '.ts')) {757- bin = localBin + '.ts';758- isExplicitJS = true;759- } else if (exists(localBin + '.mjs')) {760- bin = localBin + '.mjs';761- isExplicitJS = true;762- } else if (exists(localBin)) {710+ const localBin = path.join(baseDir, bin);711+ if (fs.existsSync(localBin)) {712+ // prefer local `./<bin>` to bin in the $PATH713 bin = localBin;714+ } else {715+ // Look for source files.716+ sourceExt.forEach((ext) => {717+ if (fs.existsSync(`${localBin}${ext}`)) {718+ bin = `${localBin}${ext}`;719+ }720+ });721 }722+ launchWithNode = sourceExt.includes(path.extname(bin));723 766- args = args.slice(1);767-768- var proc;724+ let proc;725 if (process.platform !== 'win32') {770- if (isExplicitJS) {726+ if (launchWithNode) {727 args.unshift(bin);728 // add executable arguments to spawn729 args = incrementNodeInspectorPort(process.execArgv).concat(args);730 7 unmodified lines738 args = incrementNodeInspectorPort(process.execArgv).concat(args);739 proc = spawn(process.execPath, args, { stdio: 'inherit' });740 }741 786- var signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];742+ const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];743 signals.forEach(function(signal) {744 process.on(signal, function() {745 if (proc.killed === false && proc.exitCode === null) {746 proc.kill(signal);12 unmodified lines759 });760 }761 proc.on('error', function(err) {762 if (err.code === 'ENOENT') {807- console.error('error: %s(1) does not exist, try --help', bin);763+ console.error('error: %s(1) does not exist', bin);764 } else if (err.code === 'EACCES') {809- console.error('error: %s(1) not executable. try chmod or run with root', bin);765+ console.error('error: %s(1) not executable', bin);766 }767 if (!exitCallback) {768 process.exit(1);769 } else {7 unmodified lines777 this.runningCommand = proc;778 };779 780 /**825- * Parse command `args`.781+ * @api private782+ */783+Command.prototype._dispatchSubcommand = function(commandName, operands, unknown) {784+ const subCommand = this._findCommand(commandName);785+ if (!subCommand) this._helpAndError();786+787+ if (subCommand._executableHandler) {788+ this._executeSubCommand(subCommand, operands.concat(unknown));789+ } else {790+ subCommand._parseCommand(operands, unknown);791+ }792+};793+794+/**795+ * Process arguments in context of this command.796 *827- * When listener(s) are available those828- * callbacks are invoked, otherwise the "*"829- * event is emitted and those actions are invoked.830- *831- * @param {Array} args832- * @return {Command} for chaining797 * @api private798 */799 836-Command.prototype.parseArgs = function(operands, unknown) {837- if (operands.length) {838- const name = operands[0];839- if (this.listeners('command:' + name).length) {840- this.emit('command:' + operands[0], operands.slice(1), unknown);800+Command.prototype._parseCommand = function(operands, unknown) {801+ const parsed = this.parseOptions(unknown);802+ operands = operands.concat(parsed.operands);803+ unknown = parsed.unknown;804+ this.args = operands.concat(unknown);805+806+ if (operands && this._findCommand(operands[0])) {807+ this._dispatchSubcommand(operands[0], operands.slice(1), unknown);808+ } else if (this._lazyHasImplicitHelpCommand() && operands[0] === this._helpCommandName) {809+ if (operands.length === 1) {810+ this.help();811 } else {842- this.emit('program-command', operands, unknown);843- this.emit('command:*', operands, unknown);812+ this._dispatchSubcommand(operands[1], [], [this._helpLongFlag]);813 }814+ } else if (this._defaultCommandName) {815+ outputHelpIfRequested(this, unknown); // Run the help for default command from parent rather than passing to default command816+ this._dispatchSubcommand(this._defaultCommandName, operands, unknown);817 } else {846- outputHelpIfRequested(this, unknown);818+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {819+ // probaby missing subcommand and no handler, user needs help820+ this._helpAndError();821+ }822 848- // If there were no args and we have unknown options,849- // then they are extraneous and we need to error.850- if (unknown.length > 0 && !this.defaultExecutable) {851- this.unknownOption(unknown[0]);823+ outputHelpIfRequested(this, parsed.unknown);824+ this._checkForMissingMandatoryOptions();825+ if (parsed.unknown.length > 0) {826+ this.unknownOption(parsed.unknown[0]);827 }853- // Call the program action handler, unless it has a (missing) required parameter and signature does not match.854- if (this._args.filter(function(a) { return a.required; }).length === 0) {855- this.emit('program-command');828+829+ if (this._actionHandler) {830+ const self = this;831+ const args = this.args.slice();832+ this._args.forEach(function(arg, i) {833+ if (arg.required && args[i] == null) {834+ self.missingArgument(arg.name);835+ } else if (arg.variadic) {836+ if (i !== self._args.length - 1) {837+ self.variadicArgNotLast(arg.name);838+ }839+840+ args[i] = args.splice(i);841+ }842+ });843+844+ this._actionHandler(args);845+ this.emit('command:' + this.name(), operands, unknown);846+ } else if (operands.length) {847+ if (this._findCommand('*')) {848+ this._dispatchSubcommand('*', operands, unknown);849+ } else if (this.listenerCount('command:*')) {850+ this.emit('command:*', operands, unknown);851+ } else if (this.commands.length) {852+ this.unknownCommand();853+ }854+ } else if (this.commands.length) {855+ // This command has subcommands and nothing hooked up at this level, so display help.856+ this._helpAndError();857+ } else {858+ // fall through for caller to handle after calling .parse()859 }860 }861+};862 859- return this;863+/**864+ * Find matching command.865+ *866+ * @api private867+ */868+Command.prototype._findCommand = function(name) {869+ if (!name) return undefined;870+ return this.commands.find(cmd => cmd._name === name || cmd._alias === name);871 };872 873 /**874 * Return an option matching `arg` if any.2 unmodified lines877 * @return {Option}878 * @api private879 */880 870-Command.prototype.optionFor = function(arg) {881+Command.prototype._findOption = function(arg) {882 return this.options.find(option => option.is(arg));883 };884 885 /**886 * Display an error message if a mandatory option does not have a value.887+ * Lazy calling after checking for help flags from leaf subcommand.888 *889 * @api private890 */891 892 Command.prototype._checkForMissingMandatoryOptions = function() {881- // Walk up hierarchy so can call from action handler after checking for displaying help.893+ // Walk up hierarchy so can call in subcommand after checking for displaying help.894 for (var cmd = this; cmd; cmd = cmd.parent) {895 cmd.options.forEach((anOption) => {896 if (anOption.mandatory && (cmd._getOptionValue(anOption.attributeName()) === undefined)) {897 cmd.missingMandatoryOptionValue(anOption);40 unmodified lines938 break;939 }940 941 if (maybeOption(arg)) {930- const option = this.optionFor(arg);942+ const option = this._findOption(arg);943 // recognised option, call listener to assign value with possible custom processing944 if (option) {945 if (option.required) {946 const value = args.shift();14 unmodified lines961 }962 963 // Look for combo options following single dash, eat first one if known.964 if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {953- const option = this.optionFor(`-${arg[1]}`);965+ const option = this._findOption(`-${arg[1]}`);966 if (option) {967 if (option.required || option.optional) {968 // option with value following in same argument969 this.emit(`option:${option.name()}`, arg.slice(2));8 unmodified lines978 979 // Look for known long flag with value, like --foo=bar980 if (/^--[^=]+=/.test(arg)) {981 const index = arg.indexOf('=');970- const option = this.optionFor(arg.slice(0, index));982+ const option = this._findOption(arg.slice(0, index));983 if (option && (option.required || option.optional)) {984 this.emit(`option:${option.name()}`, arg.slice(index + 1));985 continue;986 }92 unmodified lines1079 this._exit(1, 'commander.unknownOption', message);1080 };1081 1082 /**1083+ * Unknown command.1084+ *1085+ * @param {String} flag1086+ * @api private1087+ */1088+1089+Command.prototype.unknownCommand = function() {1090+ const message = `error: unknown command '${this.args[0]}'`;1091+ console.error(message);1092+ this._exit(1, 'commander.unknownCommand', message);1093+};1094+1095+/**1096 * Variadic argument with `name` is not the last argument as required.1097 *1098 * @param {String} name1099 * @api private118 unmodified lines1218 * @api private1219 */1220 1221 Command.prototype.prepareCommands = function() {1197- return this.commands.filter(function(cmd) {1222+ const commandDetails = this.commands.filter(function(cmd) {1223 return !cmd._noHelp;1224 }).map(function(cmd) {1225 var args = cmd._args.map(function(arg) {1226 return humanReadableArgName(arg);6 unmodified lines1233 (args ? ' ' + args : ''),1234 cmd._description1235 ];1236 });1237+1238+ if (this._lazyHasImplicitHelpCommand()) {1239+ commandDetails.push([this._helpCommandnameAndArgs, this._helpCommandDescription]);1240+ }1241+ return commandDetails;1242 };1243 1244 /**1245 * Return the largest command length.93 unmodified lines1339 * @api private1340 */1341 1342 Command.prototype.commandHelp = function() {1313- if (!this.commands.length) return '';1343+ if (!this.commands.length && !this._lazyHasImplicitHelpCommand()) return '';1344 1345 var commands = this.prepareCommands();1346 var width = this.padWidth();1347 129 unmodified lines1477 this._exit(process.exitCode || 0, 'commander.help', '(outputHelp)');1478 };1479 1480 /**1481+ * Output help information and exit. Display for error situations.1482+ *1483+ * @api private1484+ */1485+1486+Command.prototype._helpAndError = function() {1487+ this.outputHelp();1488+ // message: do not have all displayed text available so only passing placeholder.1489+ this._exit(1, 'commander.help', '(outputHelp)');1490+};1491+1492+/**1493 * Camel-case the given `flag`1494 *1495 * @param {String} flag1496 * @return {String}66 unmodified lines1563 /**1564 * Output help information if help flags specified1565 *1566 * @param {Command} cmd - command to output help for1525- * @param {Array} options - array of options to search for -h or --help1567+ * @param {Array} args - array of options to search for help flags1568 * @api private1569 */1570 1529-function outputHelpIfRequested(cmd, options) {1530- options = options || [];1531-1532- for (var i = 0; i < options.length; i++) {1533- if (options[i] === cmd._helpLongFlag || options[i] === cmd._helpShortFlag) {1534- cmd.outputHelp();1535- // (Do not have all displayed text available so only passing placeholder.)1536- cmd._exit(0, 'commander.helpDisplayed', '(outputHelp)');1537- }1571+function outputHelpIfRequested(cmd, args) {1572+ const helpOption = args.find(arg => arg === cmd._helpLongFlag || arg === cmd._helpShortFlag);1573+ if (helpOption) {1574+ cmd.outputHelp();1575+ // (Do not have all displayed text available so only passing placeholder.)1576+ cmd._exit(0, 'commander.helpDisplayed', '(outputHelp)');1577 }1578 }1579 1580 /**11 unmodified lines1592 ? '<' + nameOutput + '>'1593 : '[' + nameOutput + ']';1594 }1595 1557-// for versions before node v0.8 when there weren't `fs.existsSync`1558-function exists(file) {1559- try {1560- if (fs.statSync(file).isFile()) {1561- return true;1562- }1563- } catch (e) {1564- return false;1565- }1566-}1567-1596 /**1597 * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command).1598 *1599 * @param {string[]} args - array of arguments from node.execArgv42 unmodified linesmodified:Readme_zh-CN.md+6 added-14 removed
29 unmodified lines30 - [.helpOption(flags, description)](#helpoptionflags-description)31 - [.help(cb)](#helpcb)32 - [自定义事件监听](#%e8%87%aa%e5%ae%9a%e4%b9%89%e4%ba%8b%e4%bb%b6%e7%9b%91%e5%90%ac)33 - [零碎知识](#%e9%9b%b6%e7%a2%8e%e7%9f%a5%e8%af%86)34- - [避免选项命名冲突](#避免选项命名冲突)34+ - [避免选项命名冲突](#%e9%81%bf%e5%85%8d%e9%80%89%e9%a1%b9%e5%91%bd%e5%90%8d%e5%86%b2%e7%aa%81)35 - [TypeScript](#typescript)36- - [Node 选项例如 --harmony](#node-%e9%80%89%e9%a1%b9%e4%be%8b%e5%a6%82---harmony)36+ - [Node 选项例如 `--harmony`](#node-%e9%80%89%e9%a1%b9%e4%be%8b%e5%a6%82---harmony)37 - [Node 调试](#node-%e8%b0%83%e8%af%95)38 - [重载退出(exit)处理](#%e9%87%8d%e8%bd%bd%e9%80%80%e5%87%baexit%e5%a4%84%e7%90%86)39 - [例子](#%e4%be%8b%e5%ad%90)40 - [许可证](#%e8%ae%b8%e5%8f%af%e8%af%81)41 - [支持](#%e6%94%af%e6%8c%81)42- - [企业使用Commander](#企业使用Commander)42+ - [企业使用Commander](#%e4%bc%81%e4%b8%9a%e4%bd%bf%e7%94%a8commander)43 44 ## 安装45 46 ```bash387 unmodified lines434 -P, --pineapple Add pineapple435 -b, --bbq Add bbq sauce436 -c, --cheese <type> Add the specified type of cheese (default: "marble")437 -C, --no-cheese You do not want any cheese438- -h, --help output usage information438+ -h, --help display help for command439 ```440 441 ### 自定义帮助442 9 unmodified lines452 .option('-f, --foo', 'enable some foo')453 .option('-b, --bar', 'enable some bar')454 .option('-B, --baz', 'enable some baz');455 456-// must be before .parse() since457-// node's emit() is immediate458-456+// must be before .parse()457 program.on('--help', function(){458 console.log('');459 console.log('Examples:');460 console.log(' $ custom-help --help');10 unmodified lines471 ```Text472 Usage: custom-help [options]473 474 Options:477- -h, --help output usage information475+ -h, --help display help for command476 -V, --version output the version number477 -f, --foo enable some foo478 -b, --bar enable some bar479 -B, --baz enable some baz187 unmodified lines667 console.log(' $ deploy exec sequential');668 console.log(' $ deploy exec async');669 });670 673-program674- .command('*')675- .action(function(env){676- console.log('deploying "%s"', env);677- });678-671 program.parse(process.argv);672 ```673 674 更多的 [演示](https://github.com/tj/commander.js/tree/master/examples) 可以在这里找到。17 unmodified linesmodified:Readme.md+52 added-33 removed
9 unmodified lines10 Read this in other languages: English | [简体中文](./Readme_zh-CN.md)11 12 - [Commander.js](#commanderjs)13 - [Installation](#installation)14- - [Declaring program variable](#declaring-program-variable)14+ - [Declaring _program_ variable](#declaring-program-variable)15 - [Options](#options)16 - [Common option types, boolean and value](#common-option-types-boolean-and-value)17 - [Default option value](#default-option-value)18 - [Other option types, negatable boolean and flag|value](#other-option-types-negatable-boolean-and-flagvalue)3 unmodified lines22 - [Commands](#commands)23 - [Specify the argument syntax](#specify-the-argument-syntax)24 - [Action handler (sub)commands](#action-handler-subcommands)25 - [Git-style executable (sub)commands](#git-style-executable-subcommands)26- - [Automated --help](#automated---help)26+ - [Automated help](#automated-help)27 - [Custom help](#custom-help)28 - [.usage and .name](#usage-and-name)29 - [.outputHelp(cb)](#outputhelpcb)30 - [.helpOption(flags, description)](#helpoptionflags-description)31+ - [.addHelpCommand()](#addhelpcommand)32 - [.help(cb)](#helpcb)33 - [Custom event listeners](#custom-event-listeners)34 - [Bits and pieces](#bits-and-pieces)35 - [Avoiding option name clashes](#avoiding-option-name-clashes)36 - [TypeScript](#typescript)36- - [Node options such as --harmony](#node-options-such-as---harmony)37+ - [Node options such as `--harmony`](#node-options-such-as---harmony)38 - [Node debugging](#node-debugging)39 - [Override exit handling](#override-exit-handling)40 - [Examples](#examples)41 - [License](#license)227 unmodified lines269 270 program.parse(process.argv);271 ```272 272-```273+```bash274 $ pizza275 error: required option '-c, --cheese <type>' not specified276 ```277 18 unmodified lines296 ```297 298 ## Commands299 299-You can specify (sub)commands for your top-level command using `.command`. There are two ways these can be implemented: using an action handler attached to the command, or as a separate executable file (described in more detail later). In the first parameter to `.command` you specify the command name and any command arguments. The arguments may be `<required>` or `[optional]`, and the last argument may also be `variadic...`.300+You can specify (sub)commands for your top-level command using `.command()` or `.addCommand()`. There are two ways these can be implemented: using an action handler attached to the command, or as a separate executable file (described in more detail later). The subcommands may be nested ([example](./examples/nestedCommands.js)).301 302+In the first parameter to `.command()` you specify the command name and any command arguments. The arguments may be `<required>` or `[optional]`, and the last argument may also be `variadic...`.303+304+You can use `.addCommand()` to add an already configured subcommand to the program.305+306 For example:307 308 ```js309 // Command implemented using action handler (description is supplied separately to `.command`)9 unmodified lines319 // Returns top-level command for adding more commands.320 program321 .command('start <service>', 'start named service')322 .command('stop [service]', 'stop named service, or all if no name supplied');323+324+// Command prepared separately.325+// Returns top-level command for adding more commands.326+program327+ .addCommand(build.makeBuildCommand());328 ```329 330+Configuration options can be passed with the call to `.command()`. Specifying `true` for `opts.noHelp` will remove the command from the generated help output. Specifying `true` for `opts.isDefault` will run the subcommand if no other subcommand is specified ([example](./examples/defaultCommand.js)).331+332 ### Specify the argument syntax333 334 You use `.arguments` to specify the arguments for the top-level command, and for subcommands they are included in the `.command` call. Angled brackets (e.g. `<required>`) indicate required input. Square brackets (e.g. `[optional]`) indicate optional input.335 72 unmodified lines408 await program.parseAsync(process.argv);409 }410 ```411 400-A command's options on the command line are validated when the command is used. Any unknown options will be reported as an error. However, if an action-based command does not define an action, then the options are not validated.412+A command's options on the command line are validated when the command is used. Any unknown options will be reported as an error.413 402-Configuration options can be passed with the call to `.command()`. Specifying `true` for `opts.noHelp` will remove the command from the generated help output.403-414 ### Git-style executable (sub)commands415 406-When `.command()` is invoked with a description argument, this tells commander that you're going to use separate executables for sub-commands, much like `git(1)` and other popular tools.416+When `.command()` is invoked with a description argument, this tells commander that you're going to use separate executables for sub-commands, much like `git` and other popular tools.417 Commander will search the executables in the directory of the entry script (like `./examples/pm`) with the name `program-subcommand`, like `pm-install`, `pm-search`.418 You can specify a custom name with the `executableFile` configuration option.419 420 You handle the options for an executable (sub)command in the executable, and don't declare them at the top-level.10 unmodified lines431 .command('list', 'list packages installed', {isDefault: true})432 .parse(process.argv);433 ```434 425-Configuration options can be passed with the call to `.command()`. Specifying `true` for `opts.noHelp` will remove the command from the generated help output. Specifying `true` for `opts.isDefault` will run the subcommand if no other subcommand is specified.426-Specifying a name with `executableFile` will override the default constructed name.427-435 If the program is designed to be installed globally, make sure the executables have proper modes, like `755`.436 430-## Automated --help437+## Automated help438 432- The help information is auto-generated based on the information commander already knows about your program, so the following `--help` info is for free:439+ The help information is auto-generated based on the information commander already knows about your program. The default440+ help option is `-h,--help`.441 442 ```bash443 $ ./examples/pizza --help444 Usage: pizza [options]6 unmodified lines451 -P, --pineapple Add pineapple452 -b, --bbq Add bbq sauce453 -c, --cheese <type> Add the specified type of cheese (default: "marble")454 -C, --no-cheese You do not want any cheese447- -h, --help output usage information455+ -h, --help display help for command456 ```457 458+A `help` command is added by default if your command has subcommands. It can be used alone, or with a subcommand name to show459+further help for the subcommand. These are effectively the same if the `shell` program has implicit help:460+461+```bash462+shell help463+shell --help464+465+shell help spawn466+shell spawn --help467+```468+469 ### Custom help470 452- You can display arbitrary `-h, --help` information471+ You can display extra `-h, --help` information472 by listening for "--help". Commander will automatically454- exit once you are done so that the remainder of your program455- does not execute causing undesired behaviors, for example456- in the following executable "stuff" will not output when457- `--help` is used.473+ exit after displaying the help.474 475 ```js476 #!/usr/bin/env node477 4 unmodified lines482 .option('-f, --foo', 'enable some foo')483 .option('-b, --bar', 'enable some bar')484 .option('-B, --baz', 'enable some baz');485 470-// must be before .parse() since471-// node's emit() is immediate472-486+// must be before .parse()487 program.on('--help', function(){488 console.log('')489 console.log('Examples:');490 console.log(' $ custom-help --help');10 unmodified lines501 ```Text502 Usage: custom-help [options]503 504 Options:491- -h, --help output usage information505 -V, --version output the version number506 -f, --foo enable some foo507 -b, --bar enable some bar508 -B, --baz enable some baz509+ -h, --help display help for command510 511 Examples:512 $ custom-help --help513 $ custom-help -h49 unmodified lines563 program564 .helpOption('-e, --HELP', 'read more information');565 ```566 567+### .addHelpCommand()568+569+You can explicitly turn on or off the implicit help command with `.addHelpCommand()` and `.addHelpCommand(false)`.570+571+You can both turn on and customise the help command by supplying the name and description:572+573+```js574+program.addHelpCommand('assist [command]', 'show assistance');575+```576+577 ### .help(cb)578 579 Output help information and exit immediately.580 Optional callback cb allows post-processing of help text before it is displayed.6 unmodified lines587 program.on('option:verbose', function () {588 process.env.VERBOSE = this.verbose;589 });590 567-// error on unknown commands568-program.on('command:*', function () {569- console.error('Invalid command: %s\nSee --help for a list of available commands.', program.args[0]]);591+// custom error on unknown command592+program.on('command:*', function (operands) {593+ console.error(`Invalid command '${operands[0]}'. Did you mean:`);594+ console.error(mySuggestions(operands[0]));595 process.exit(1);596 });597 ```598 111 unmodified lines710 console.log(' $ deploy exec sequential');711 console.log(' $ deploy exec async');712 });713 689-program690- .command('*')691- .action(function(env){692- console.log('deploying "%s"', env);693- });694-714 program.parse(process.argv);715 ```716 717 More Demos can be found in the [examples](https://github.com/tj/commander.js/tree/master/examples) directory.17 unmodified lines