Skip to content
Myr

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

authored by John Gee · committed by GitHub · parent 1691344 · Browse files · 27 files+763 added−338 removed
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

27 files+763 added−338 removed

modified:examples/custom-help+1 added-3 removed
7 unmodified lines
8 .option('-f, --foo', 'enable some foo')9 .option('-b, --bar', 'enable some bar')10 .option('-B, --baz', 'enable some baz');1112// must be before .parse() since13// node's emit() is immediate1412// must be before .parse()13program.on('--help', function() {14 console.log('');15 console.log('Examples:');16 console.log('');
7 unmodified lines
added:examples/defaultCommand.js+36 added
modified:examples/deploy-6 removed
32 unmodified lines
33 console.log(' $ deploy exec async');34 console.log();35 });3637program38 .command('*')39 .action(function(env) {40 console.log('deploying "%s"', env);41 });4237program.parse(process.argv);
added:examples/nestedCommands.js+47 added
modified:tests/args.variadic.test.js+1 added-1 removed
modified:tests/command.action.test.js+7 added-1 removed
44 unmodified lines
45 expect(actionMock).toHaveBeenCalledWith('my-file', program);46});4748test('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});6364// Changes made in #729 to call program action handler65test('when .action on program and no arguments then action called', () => {
72 unmodified lines
added:tests/command.addCommand.test.js+69 added
modified:tests/command.allowUnknownOptions.test.js+1 added-1 removed
1const commander = require('../');23// Not testing output, just testing whether an error is detected.45describe('.version', () => {5describe('allowUnknownOption', () => {6 // Optional. Use internal knowledge to suppress output to keep test output clean.7 let consoleErrorSpy;89 beforeAll(() => {
61 unmodified lines
modified:tests/command.asterisk.test.js+17 added-1 removed
9 unmodified lines
10//11// Historical: the event 'command:*' used to also be shared by the action handler on the program.1213describe(".command('*')", () => {14 // Use internal knowledge to suppress output to keep test output clean.15 let writeMock;1617 beforeAll(() => {18 writeMock = jest.spyOn(process.stdout, 'write').mockImplementation(() => { });19 });2021 afterAll(() => {22 writeMock.mockRestore();23 });2425 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 });3940 test('when unrecognised argument then asterisk action called', () => {
78 unmodified lines
modified:tests/command.commandHelp.test.js+2 added-2 removed
5 unmodified lines
6 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});1213test('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
1const childProcess = require('child_process');2const path = require('path');3const commander = require('../');45describe('default executable command', () => {6 // Calling node explicitly so pm works without file suffix cross-platform.7 const pm = path.join(__dirname, './fixtures/pm');89 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 });1516 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 });2223 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});3031describe('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 }4344 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 });4950 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 });5556 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
1const childProcess = require('child_process');2const path = require('path');34// Calling node explicitly so pm works without file suffix cross-platform.56const pm = path.join(__dirname, './fixtures/pm');78test('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});1415test('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});2122test('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 lines
11 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 lines
23 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 lines
modified:tests/command.exitOverride.test.js+18 added-2 removed
49 unmodified lines
50 expect(consoleErrorSpy).toHaveBeenCalled();51 expectCommanderError(caughtErr, 1, 'commander.unknownOption', "error: unknown option '-m'");52 });5354 test('when specify unknown command then throw CommanderError', () => {55 const program = new commander.Command();56 program57 .exitOverride()58 .command('sub');5960 let caughtErr;61 try {62 program.parse(['node', 'test', 'oops']);63 } catch (err) {64 caughtErr = err;65 }6667 expect(consoleErrorSpy).toHaveBeenCalled();68 expectCommanderError(caughtErr, 1, 'commander.unknownCommand', "error: unknown command 'oops'");69 });7071 // 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 lines
151 } catch (err) {152 caughtErr = err;153 }154138 // 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 });158159 test('when specify --version then throw CommanderError', () => {160 const myVersion = '1.2.3';
86 unmodified lines
modified:tests/command.help.test.js+4 added-3 removed
12 unmodified lines
13 const expectedHelpInformation =14`Usage: test [options] [command]1516Options:17 -h, --help output usage information17 -h, --help display help for command1819Commands:20 my-command <file>21 help [command] display help for command22`;2323 program.parse(['node', 'test']);24 program.name('test');25 const helpInformation = program.helpInformation();26 expect(helpInformation).toBe(expectedHelpInformation);27});28
1 unmodified line
30 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 lines
added:tests/command.helpCommand.test.js+100 added
1const commander = require('../');23describe('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 });910 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 });1617 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 });2324 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 });3132 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});3940describe('help command processed on correct command', () => {41 // Use internal knowledge to suppress output to keep test output clean.42 let consoleErrorSpy;43 let writeSpy;4445 beforeAll(() => {46 consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => { });47 writeSpy = jest.spyOn(process.stdout, 'write').mockImplementation(() => { });48 });4950 afterEach(() => {51 consoleErrorSpy.mockClear();52 writeSpy.mockClear();53 });5455 afterAll(() => {56 consoleErrorSpy.mockRestore();57 writeSpy.mockRestore();58 });5960 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 });6970 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 });7980 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 });9091 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
1const commander = require('../');23test('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
1const commander = require('../');23describe('unknownOption', () => {4 // Optional. Use internal knowledge to suppress output to keep test output clean.5 let consoleErrorSpy;67 beforeAll(() => {8 consoleErrorSpy = jest.spyOn(console, 'error').mockImplementation(() => { });9 });1011 afterEach(() => {12 consoleErrorSpy.mockClear();13 });1415 afterAll(() => {16 consoleErrorSpy.mockRestore();17 });1819 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 });2324 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 });3132 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 });3940 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
1const commander = require('../');23// Checking for detection of unknown options, including regression tests for some past issues.45describe('.version', () => {5describe('unknownOption', () => {6 // Optional. Use internal knowledge to suppress output to keep test output clean.7 let consoleErrorSpy;89 beforeAll(() => {
76 unmodified lines
modified:tests/command.usage.test.js+4 added-4 removed
1 unmodified line
23test('when default usage and check program help then starts with default usage', () => {4 const program = new commander.Command();56 program.parse(['node', 'test']);6 program.name('test');7 const helpInformation = program.helpInformation();89 expect(helpInformation).toMatch(new RegExp('^Usage: test \\[options\\]'));10});
3 unmodified lines
14 const program = new commander.Command();15 program16 .usage(myUsage);1718 program.parse(['node', 'test']);18 program.name('test');19 const helpInformation = program.helpInformation();2021 expect(helpInformation).toMatch(new RegExp(`^Usage: test ${myUsage}`));22});
2 unmodified lines
25 const program = new commander.Command();26 const subCommand = program27 .command('info');2829 program.parse(['node', 'test']);29 program.name('test');30 const helpInformation = subCommand.helpInformation();3132 expect(helpInformation).toMatch(new RegExp('^Usage: test info \\[options\\]'));33});
4 unmodified lines
38 const subCommand = program39 .command('info')40 .usage(myUsage);4142 program.parse(['node', 'test']);42 program.name('test');43 const helpInformation = subCommand.helpInformation();4445 expect(helpInformation).toMatch(new RegExp(`^Usage: test info ${myUsage}`));46});
modified:tests/helpwrap.test.js+8 added-5 removed
1const commander = require('../');23// Test auto wrap and indent with some manual strings.4// Fragile tests with complete help output.56test('when long option description then wrap and indent', () => {7 const oldColumns = process.stdout.columns;8 process.stdout.columns = 80;
7 unmodified lines
16Options: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`;2223 expect(program.helpInformation()).toBe(expectedOutput);24 process.stdout.columns = oldColumns;
11 unmodified lines
3637Options: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`;4243 expect(program.helpInformation()).toBe(expectedOutput);44 process.stdout.columns = oldColumns;
11 unmodified lines
56`Usage: [options] [command]5758Options:59 -x -extra-long-option-switch x59 -h, --help output usage information60 -h, --help display help for command6162Commands:63 alpha Lorem mollit quis dolor ex do eu quis ad insa64 a commodo esse.65 help [command] display help for command66`;6768 expect(program.helpInformation()).toBe(expectedOutput);69 process.stdout.columns = oldColumns;
11 unmodified lines
81 const expectedOutput =82`Usage: [options] [command]8384Options:83 -h, --help output usage information85 -h, --help display help for command8687Commands:88 1234567801234567890x ${commandDescription}89 help [command] display help for command90`;9192 expect(program.helpInformation()).toBe(expectedOutput);93 process.stdout.columns = oldColumns;
20 unmodified lines
114 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`;120121 expect(program.helpInformation()).toBe(expectedOutput);122 process.stdout.columns = oldColumns;
3 unmodified lines
modified:tests/options.mandatory.test.js+3 added-1 removed
217 unmodified lines
218 .exitOverride()219 .command('sub')220 .requiredOption('--subby <type>', 'description')221 .action((cmd) => {});222 program223 .command('sub2');224225 expect(() => {224 program.parse(['node', 'test']);226 program.parse(['node', 'test', 'sub2']);227 }).not.toThrow();228 });229});230
50 unmodified lines
modified:typings/commander-tests.ts+4 added-3 removed
71 unmodified lines
72 .option('-f, --foo', 'enable some foo')73 .option('-b, --bar', 'enable some bar')74 .option('-B, --baz', 'enable some baz');7576// must be before .parse() since77// node's emit() is immediate7876// must be before .parse()77program.on('--help', () => {78 console.log(' Examples:');79 console.log('');80 console.log(' $ custom-help --help');
29 unmodified lines
110program111 .command("name1", "description")112 .command("name2", "description", { isDefault:true })113114const preparedCommand = new program.Command('prepared');115program.addCommand(preparedCommand);116117program118 .exitOverride();119120program.exitOverride((err):never => {
23 unmodified lines
modified:typings/index.d.ts+6 added-8 removed
78 unmodified lines
79 */80 command(nameAndArgs: string, description: string, opts?: commander.CommandOptions): Command;8182 /**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;8889 /**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;9596 /**97 * Register callback to use as replacement for calling process.exit.98 */
230 unmodified lines
modified:index.js+248 added-220 removed
3 unmodified lines
45var EventEmitter = require('events').EventEmitter;6var spawn = require('child_process').spawn;7var path = require('path');8var dirname = path.dirname;9var basename = path.basename;8var fs = require('fs');910/**11 * Inherit `Command` from `EventEmitter.prototype`.
109 unmodified lines
121122function 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;137138 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}148149/**150 * Define a command.
34 unmodified lines
185 var cmd = new Command(args.shift());186187 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;192193 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;204195 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;209210 if (desc) return this;211 return cmd;212};213214/**215 * Add a prepared subcommand.216 *217 * @param {Command} cmd - new subcommand218 * @return {Command} parent command for chaining219 * @api public220 */221222Command.prototype.addCommand = function(cmd) {223 if (!cmd._name) throw new Error('Command passed to .AddCommand must have a name');224225 // 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);236237 this.commands.push(cmd);238 cmd.parent = this;239 return this;240};241242/**243 * Define argument syntax for the top-level command.244 *245 * @api public246 */247248Command.prototype.arguments = function(desc) {211 return this.parseExpectedArgs(desc.split(/ +/));249 return this._parseExpectedArgs(desc.split(/ +/));250};251252/**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 */262263Command.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};276277/**278 * @return {boolean}279 * @api private280 */281221Command.prototype.addImplicitHelpCommand = function() {222 this.command('help [cmd]', 'display help for [cmd]');282Command.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};288289/**290 * Parse expected `args`.
1 unmodified line
292 * For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`.293 *294 * @param {Array} args295 * @return {Command} for chaining232 * @api public296 * @api private297 */298235Command.prototype.parseExpectedArgs = function(args) {299Command.prototype._parseExpectedArgs = function(args) {300 if (!args.length) return;301 var self = this;302 args.forEach(function(arg) {303 var argDetails = {
82 unmodified lines
386 */387388Command.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 || [];330331 var parsed = self.parseOptions(unknown);332333 // Output help if necessary334 outputHelpIfRequested(self, parsed.unknown);335 self._checkForMissingMandatoryOptions();336337 // If there are still any unknown options, then we simply die.338 if (parsed.unknown.length > 0) {339 self.unknownOption(parsed.unknown[0]);340 }341342 args = args.concat(parsed.operands, parsed.unknown);343344 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 }351352 args[i] = args.splice(i);353 }354 });355356 // 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 lines
408 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 }383384 if (this._alias) parent.on('command:' + this._alias, listener);412 this._actionHandler = listener;413 return this;414};415416/**
35 unmodified lines
452 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 lines
649 * @api public650 */651652Command.prototype.parse = function(argv) {625 // implicit help626 if (this.executables) this.addImplicitHelpCommand();627653 // store raw args654 this.rawArgs = argv;655631 // 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]));658634 // 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));660640 // 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();644645 var result = this.parseArgs(parsed.operands, parsed.unknown);646647 if (args[0] === 'help' && args.length === 1) this.help();648649 // Note for future: we could return early if we found an action handler in parseArgs, as none of following code needed?650651 // <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 }661662 // 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;666667 // Look for subcommand668 if (name) {669 subCommand = this.commands.find(function(command) {670 return command._name === name;671 });672 }673674 // 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 }684685 // 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 }693694 if (this._execs.has(name)) {695 return this.executeSubCommand(argv, args, subCommand ? subCommand._executableFile : undefined);696 }697698 return result;661 return this;662};663664/**665 * Parse `argv`, setting options and invoking commands when defined.
3 unmodified lines
669 * @param {Array} argv670 * @return {Promise}671 * @api public672 */673674Command.prototype.parseAsync = function(argv) {675 this.parse(argv);676 return Promise.all(this._actionResults);677};678679/**680 * Execute a sub-command executable.681 *718 * @param {Array} argv719 * @param {Array} args720 * @param {Array} unknown721 * @param {String} executableFile682 * @api private683 */684725Command.prototype.executeSubCommand = function(argv, args, executableFile) {726 if (!args.length) this.help();685Command.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'];689728 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();692730 // 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];695696 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 }703704 // 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 }709741 // In case of globally installed, get the base dir where executable742 // subcommand file should be located at743 var baseDir;744745 var resolvedLink = fs.realpathSync(pm);746747 baseDir = dirname(resolvedLink);748749 // prefer local `./<bin>` to bin in the $PATH750 var localBin = path.join(baseDir, bin);751752 // 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));723766 args = args.slice(1);767768 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 lines
738 args = incrementNodeInspectorPort(process.execArgv).concat(args);739 proc = spawn(process.execPath, args, { stdio: 'inherit' });740 }741786 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 lines
759 });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 lines
777 this.runningCommand = proc;778};779780/**825 * Parse command `args`.781 * @api private782 */783Command.prototype._dispatchSubcommand = function(commandName, operands, unknown) {784 const subCommand = this._findCommand(commandName);785 if (!subCommand) this._helpAndError();786787 if (subCommand._executableHandler) {788 this._executeSubCommand(subCommand, operands.concat(unknown));789 } else {790 subCommand._parseCommand(operands, unknown);791 }792};793794/**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 */799836Command.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);800Command.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);805806 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 }822848 // 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');828829 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 }839840 args[i] = args.splice(i);841 }842 });843844 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};862859 return this;863/**864 * Find matching command.865 *866 * @api private867 */868Command.prototype._findCommand = function(name) {869 if (!name) return undefined;870 return this.commands.find(cmd => cmd._name === name || cmd._alias === name);871};872873/**874 * Return an option matching `arg` if any.
2 unmodified lines
877 * @return {Option}878 * @api private879 */880870Command.prototype.optionFor = function(arg) {881Command.prototype._findOption = function(arg) {882 return this.options.find(option => option.is(arg));883};884885/**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 */891892Command.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 lines
938 break;939 }940941 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 lines
961 }962963 // 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 lines
978979 // 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 lines
1079 this._exit(1, 'commander.unknownOption', message);1080};10811082/**1083 * Unknown command.1084 *1085 * @param {String} flag1086 * @api private1087 */10881089Command.prototype.unknownCommand = function() {1090 const message = `error: unknown command '${this.args[0]}'`;1091 console.error(message);1092 this._exit(1, 'commander.unknownCommand', message);1093};10941095/**1096 * Variadic argument with `name` is not the last argument as required.1097 *1098 * @param {String} name1099 * @api private
118 unmodified lines
1218 * @api private1219 */12201221Command.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 lines
1233 (args ? ' ' + args : ''),1234 cmd._description1235 ];1236 });12371238 if (this._lazyHasImplicitHelpCommand()) {1239 commandDetails.push([this._helpCommandnameAndArgs, this._helpCommandDescription]);1240 }1241 return commandDetails;1242};12431244/**1245 * Return the largest command length.
93 unmodified lines
1339 * @api private1340 */13411342Command.prototype.commandHelp = function() {1313 if (!this.commands.length) return '';1343 if (!this.commands.length && !this._lazyHasImplicitHelpCommand()) return '';13441345 var commands = this.prepareCommands();1346 var width = this.padWidth();1347
129 unmodified lines
1477 this._exit(process.exitCode || 0, 'commander.help', '(outputHelp)');1478};14791480/**1481 * Output help information and exit. Display for error situations.1482 *1483 * @api private1484 */14851486Command.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};14911492/**1493 * Camel-case the given `flag`1494 *1495 * @param {String} flag1496 * @return {String}
66 unmodified lines
1563/**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 */15701529function outputHelpIfRequested(cmd, options) {1530 options = options || [];15311532 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 }1571function 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}15791580/**
11 unmodified lines
1592 ? '<' + nameOutput + '>'1593 : '[' + nameOutput + ']';1594}15951557// for versions before node v0.8 when there weren't `fs.existsSync`1558function exists(file) {1559 try {1560 if (fs.statSync(file).isFile()) {1561 return true;1562 }1563 } catch (e) {1564 return false;1565 }1566}15671596/**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.execArgv
42 unmodified lines
modified:Readme_zh-CN.md+6 added-14 removed
29 unmodified lines
30 - [.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)4344## 安装4546```bash
387 unmodified lines
434 -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```440441### 自定义帮助442
9 unmodified lines
452 .option('-f, --foo', 'enable some foo')453 .option('-b, --bar', 'enable some bar')454 .option('-B, --baz', 'enable some baz');455456// must be before .parse() since457// node's emit() is immediate458456// must be before .parse()457program.on('--help', function(){458 console.log('');459 console.log('Examples:');460 console.log(' $ custom-help --help');
10 unmodified lines
471```Text472Usage: custom-help [options]473474Options: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 baz
187 unmodified lines
667 console.log(' $ deploy exec sequential');668 console.log(' $ deploy exec async');669 });670673program674 .command('*')675 .action(function(env){676 console.log('deploying "%s"', env);677 });678671program.parse(process.argv);672```673674更多的 [演示](https://github.com/tj/commander.js/tree/master/examples) 可以在这里找到。
17 unmodified lines
modified:Readme.md+52 added-33 removed
9 unmodified lines
10Read this in other languages: English | [简体中文](./Readme_zh-CN.md)1112- [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 lines
22 - [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 lines
269270program.parse(process.argv);271```272272```273```bash274$ pizza275error: required option '-c, --cheese <type>' not specified276```277
18 unmodified lines
296```297298## Commands299299You 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...`.300You 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)).301302In 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...`.303304You can use `.addCommand()` to add an already configured subcommand to the program.305306For example:307308```js309// Command implemented using action handler (description is supplied separately to `.command`)
9 unmodified lines
319// Returns top-level command for adding more commands.320program321 .command('start <service>', 'start named service')322 .command('stop [service]', 'stop named service, or all if no name supplied');323324// Command prepared separately.325// Returns top-level command for adding more commands.326program327 .addCommand(build.makeBuildCommand());328```329330Configuration 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)).331332### Specify the argument syntax333334You 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 lines
408 await program.parseAsync(process.argv);409}410```411400A 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.412A command's options on the command line are validated when the command is used. Any unknown options will be reported as an error.413402Configuration options can be passed with the call to `.command()`. Specifying `true` for `opts.noHelp` will remove the command from the generated help output.403414### Git-style executable (sub)commands415406When `.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.416When `.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.417Commander will search the executables in the directory of the entry script (like `./examples/pm`) with the name `program-subcommand`, like `pm-install`, `pm-search`.418You can specify a custom name with the `executableFile` configuration option.419420You handle the options for an executable (sub)command in the executable, and don't declare them at the top-level.
10 unmodified lines
431 .command('list', 'list packages installed', {isDefault: true})432 .parse(process.argv);433```434425Configuration 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.426Specifying a name with `executableFile` will override the default constructed name.427435If the program is designed to be installed globally, make sure the executables have proper modes, like `755`.436430## Automated --help437## Automated help438432 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`.441442```bash443$ ./examples/pizza --help444Usage: pizza [options]
6 unmodified lines
451 -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```457458A `help` command is added by default if your command has subcommands. It can be used alone, or with a subcommand name to show459further help for the subcommand. These are effectively the same if the `shell` program has implicit help:460461```bash462shell help463shell --help464465shell help spawn466shell spawn --help467```468469### Custom help470452 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.474475```js476#!/usr/bin/env node477
4 unmodified lines
482 .option('-f, --foo', 'enable some foo')483 .option('-b, --bar', 'enable some bar')484 .option('-B, --baz', 'enable some baz');485470// must be before .parse() since471// node's emit() is immediate472486// must be before .parse()487program.on('--help', function(){488 console.log('')489 console.log('Examples:');490 console.log(' $ custom-help --help');
10 unmodified lines
501```Text502Usage: custom-help [options]503504Options: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 command510511Examples:512 $ custom-help --help513 $ custom-help -h
49 unmodified lines
563program564 .helpOption('-e, --HELP', 'read more information');565```566567### .addHelpCommand()568569You can explicitly turn on or off the implicit help command with `.addHelpCommand()` and `.addHelpCommand(false)`.570571You can both turn on and customise the help command by supplying the name and description:572573```js574program.addHelpCommand('assist [command]', 'show assistance');575```576577### .help(cb)578579 Output help information and exit immediately.580 Optional callback cb allows post-processing of help text before it is displayed.
6 unmodified lines
587program.on('option:verbose', function () {588 process.env.VERBOSE = this.verbose;589});590567// error on unknown commands568program.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 command592program.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 lines
710 console.log(' $ deploy exec sequential');711 console.log(' $ deploy exec async');712 });713689program690 .command('*')691 .action(function(env){692 console.log('deploying "%s"', env);693 });694714program.parse(process.argv);715```716717More Demos can be found in the [examples](https://github.com/tj/commander.js/tree/master/examples) directory.
17 unmodified lines