Skip to content
Myr

More consistent way of adding command arguments (#1490)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* added addArguments method * fix undefined args * added tests, docs and typings * code review fixes * throw error on bad arg * Parse command-argument details in constructor * Handle argument descriptions separately for legacy and new support * Add text to distinguish test names with .each * Match nameAndArgs into two parts, rather than split on spaces. * Update release date post-release to be more accurate * Fix test naming * Simplify and tidy argument example * Typing and typings test for .argument * Expand argument section to include existing multiple-argument approaches. * Add name method and improve Argument typings and tests * Fix copy-and-paste JSDoc error * Update example to match new method and README * Deprecate old way of adding command argument descriptions * Be lenient about Argument construction to allow lazy building * Call first param to .argument "name", and expand jsdoc * Add low-level check that get same Argument from multiple ways of specifying argument * Minor wording tweaks * Add low-level tests for multiple arg variations * Simplify test. Use .argument now. * Restore simple test, use .argument * Big switch from .arguments to .argument in tests * Expand help to explain argument variations * Keep Argument properties private for now (like Command, unlike Option) * Argument should follow Option for properties, make public again * Generate help for arguments using same methods as for option and subcommand * Simplify Argument .name(), just getter * Expand test coverage for visibleArguments * Rework the multiple ways of specifying command-arguments * Add Argument to esm exports (and createOption)

authored by John Gee · committed by GitHub · parent 327a3dd · Browse files · 33 files+622 added−189 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Co-authored-by: Nir Yosef <niryo@wix.com>

Diff stats

33 files+622 added−189 removed

  • tests:+324 added−92 removed
  • other:+298 added−97 removed

33 files+622 added−189 removed

modified:docs/zh-CN/可变参数的选项.md+2 added-2 removed
modified:docs/deprecated.md+25 added
84 unmodified lines
85);86```8788Deprecated from Commander v7. 8990## cmd.description(cmdDescription, argDescriptions)9192This was used to add command argument descriptions for the help.9394```js95program96 .command('price <book>')97 .description('show price of book', {98 book: 'ISBN number for book'99 });100```101102The new approach is to use the `.argument()` method.103104```js105program106 .command('price')107 .description('show price of book')108 .argument('<book>', 'ISBN number for book');109```110111112Deprecated from Commander v8.113
modified:docs/options-taking-varying-arguments.md+2 added-2 removed
3 unmodified lines
4and subtle issues in depth.56- [Options taking varying numbers of option-arguments](#options-taking-varying-numbers-of-option-arguments)7 - [Parsing ambiguity](#parsing-ambiguity)8 - [Alternative: Make `--` part of your syntax](#alternative-make----part-of-your-syntax)8 - [Alternative: Make `--` part of your syntax](#alternative-make-----part-of-your-syntax)9 - [Alternative: Put options last](#alternative-put-options-last)10 - [Alternative: Use options instead of command-arguments](#alternative-use-options-instead-of-command-arguments)11 - [Combining short options, and options taking arguments](#combining-short-options-and-options-taking-arguments)12 - [Combining short options as if boolean](#combining-short-options-as-if-boolean)
20 unmodified lines
3334```js35program36 .name('cook')37 .arguments('[technique]')37 .argument('[technique]')38 .option('-i, --ingredient [ingredient]', 'add cheese or given ingredient')39 .action((technique, options) => {40 console.log(`technique: ${technique}`);41 const ingredient = (options.ingredient === true) ? 'cheese' : options.ingredient;
160 unmodified lines
added:examples/argument.js+24 added
1#!/usr/bin/env node23// This example shows specifying the arguments using argument() function.45// const { Command } = require('commander'); // (normal include)6const { Command } = require('../'); // include commander in git clone of commander repo7const program = new Command();89program10 .version('0.1.0')11 .argument('<username>', 'user to login')12 .argument('[password]', 'password for user, if required')13 .description('example program for argument')14 .action((username, password) => {15 console.log('username:', username);16 console.log('password:', password || 'no password given');17 });1819program.parse();2021// Try the following:22// node arguments.js --help23// node arguments.js user24// node arguments.js user secret
modified:examples/arguments.js+1 added-1 removed
13 unmodified lines
14 password: 'password for user, if required'15 })16 .action((username, password) => {17 console.log('username:', username);18 console.log('environment:', password || 'no password given');18 console.log('password:', password || 'no password given');19 });2021program.parse();22
4 unmodified lines
modified:examples/pass-through-options.js+2 added-1 removed
3 unmodified lines
4const { Command } = require('../'); // include commander in git clone of commander repo5const program = new Command();67program8 .arguments('<utility> [args...]')8 .argument('<utility>')9 .argument('[args...]')10 .passThroughOptions()11 .option('-d, --dry-run')12 .action((utility, args, options) => {13 const action = options.dryRun ? 'Would run' : 'Running';
11 unmodified lines
modified:examples/thank.js+1 added-1 removed
5 unmodified lines
6const { Command } = require('../'); // include commander in git clone of commander repo7const program = new Command();89program10 .arguments('<name>')10 .argument('<name>')11 .option('-t, --title <honorific>', 'title to use before name')12 .option('-d, --debug', 'display some debugging')13 .action((name, options, command) => {14 if (options.debug) {
12 unmodified lines
added:tests/argument.variadic.test.js+84 added
1const commander = require('../');23// Testing variadic arguments. Testing all the action arguments, but could test just variadicArg.45describe('variadic argument', () => {6 test('when no extra arguments specified for program then variadic arg is empty array', () => {7 const actionMock = jest.fn();8 const program = new commander.Command();9 program10 .argument('<id>')11 .argument('[variadicArg...]')12 .action(actionMock);1314 program.parse(['node', 'test', 'id']);1516 expect(actionMock).toHaveBeenCalledWith('id', [], program.opts(), program);17 });1819 test('when extra arguments specified for program then variadic arg is array of values', () => {20 const actionMock = jest.fn();21 const program = new commander.Command();22 program23 .addArgument(new commander.Argument('<id>'))24 .argument('[variadicArg...]')25 .action(actionMock);26 const extraArguments = ['a', 'b', 'c'];2728 program.parse(['node', 'test', 'id', ...extraArguments]);2930 expect(actionMock).toHaveBeenCalledWith('id', extraArguments, program.opts(), program);31 });3233 test('when no extra arguments specified for command then variadic arg is empty array', () => {34 const actionMock = jest.fn();35 const program = new commander.Command();36 const cmd = program37 .command('sub [variadicArg...]')38 .action(actionMock);3940 program.parse(['node', 'test', 'sub']);4142 expect(actionMock).toHaveBeenCalledWith([], cmd.opts(), cmd);43 });4445 test('when extra arguments specified for command then variadic arg is array of values', () => {46 const actionMock = jest.fn();47 const program = new commander.Command();48 const cmd = program49 .command('sub [variadicArg...]')50 .action(actionMock);51 const extraArguments = ['a', 'b', 'c'];5253 program.parse(['node', 'test', 'sub', ...extraArguments]);5455 expect(actionMock).toHaveBeenCalledWith(extraArguments, cmd.opts(), cmd);56 });5758 test('when program variadic argument not last then error', () => {59 const program = new commander.Command();6061 expect(() => {62 program63 .argument('<variadicArg...>')64 .argument('[optionalArg]');65 }).toThrow("only the last argument can be variadic 'variadicArg'");66 });6768 test('when command variadic argument not last then error', () => {69 const program = new commander.Command();7071 expect(() => {72 program.command('sub <variadicArg...> [optionalArg]');73 }).toThrow("only the last argument can be variadic 'variadicArg'");74 });7576 test('when variadic argument then usage shows variadic', () => {77 const program = new commander.Command();78 program79 .name('foo')80 .argument('[args...]');8182 expect(program.usage()).toBe('[options] [args...]');83 });84});
modified:tests/command.action.test.js+19 added-30 removed
21 unmodified lines
22 program.parse(['node', 'test', 'info', 'my-file']);23 expect(program.args).toEqual(['info', 'my-file']);24});2526test('when .action on program with required argument and argument supplied then action called', () => {26test.each(getTestCases('<file>'))('when .action on program with required argument via %s and argument supplied then action called', (methodName, program) => {27 const actionMock = jest.fn();28 const program = new commander.Command();29 program30 .arguments('<file>')31 .action(actionMock);28 program.action(actionMock);29 program.parse(['node', 'test', 'my-file']);30 expect(actionMock).toHaveBeenCalledWith('my-file', program.opts(), program);31});3236test('when .action on program with required argument and argument not supplied then action not called', () => {33test.each(getTestCases('<file>'))('when .action on program with required argument via %s and argument not supplied then action not called', (methodName, program) => {34 const actionMock = jest.fn();38 const program = new commander.Command();35 program36 .exitOverride()37 .configureOutput({ writeErr: () => {} })42 .arguments('<file>')38 .action(actionMock);39 expect(() => {40 program.parse(['node', 'test']);41 }).toThrow();
9 unmodified lines
51 program.parse(['node', 'test']);52 expect(actionMock).toHaveBeenCalledWith(program.opts(), program);53});5460test('when .action on program with optional argument supplied then action called', () => {55test.each(getTestCases('[file]'))('when .action on program with optional argument via %s supplied then action called', (methodName, program) => {56 const actionMock = jest.fn();62 const program = new commander.Command();63 program64 .arguments('[file]')65 .action(actionMock);57 program.action(actionMock);58 program.parse(['node', 'test', 'my-file']);59 expect(actionMock).toHaveBeenCalledWith('my-file', program.opts(), program);60});6170test('when .action on program without optional argument supplied then action called', () => {62test.each(getTestCases('[file]'))('when .action on program without optional argument supplied then action called', (methodName, program) => {63 const actionMock = jest.fn();72 const program = new commander.Command();73 program74 .arguments('[file]')75 .action(actionMock);64 program.action(actionMock);65 program.parse(['node', 'test']);66 expect(actionMock).toHaveBeenCalledWith(undefined, program.opts(), program);67});6880test('when .action on program with optional argument and subcommand and program argument then program action called', () => {69test.each(getTestCases('[file]'))('when .action on program with optional argument via %s and subcommand and program argument then program action called', (methodName, program) => {70 const actionMock = jest.fn();82 const program = new commander.Command();71 program.action(actionMock);72 program84 .arguments('[file]')85 .action(actionMock);86 program73 .command('subcommand');7475 program.parse(['node', 'test', 'a']);7677 expect(actionMock).toHaveBeenCalledWith('a', program.opts(), program);78});7980// Changes made in #1062 to allow this case95test('when .action on program with optional argument and subcommand and no program argument then program action called', () => {81test.each(getTestCases('[file]'))('when .action on program with optional argument via %s and subcommand and no program argument then program action called', (methodName, program) => {82 const actionMock = jest.fn();97 const program = new commander.Command();98 program99 .arguments('[file]')100 .action(actionMock);101 program102 .command('subcommand');83 program.action(actionMock);84 program.command('subcommand');8586 program.parse(['node', 'test']);8788 expect(actionMock).toHaveBeenCalledWith(undefined, program.opts(), program);
13 unmodified lines
102 expect(asyncFinished).toBe(false);103 await later;104 expect(asyncFinished).toBe(true);105});106107function getTestCases(arg) {108 const withArguments = new commander.Command().arguments(arg);109 const withArgument = new commander.Command().argument(arg);110 const withAddArgument = new commander.Command().addArgument(new commander.Argument(arg));111 return [['.arguments', withArguments], ['.argument', withArgument], ['.addArgument', withAddArgument]];112}
modified:tests/command.allowExcessArguments.test.js+4 added-4 removed
92 unmodified lines
9394 test('when specify expected arg and allowExcessArguments(false) then no error', () => {95 const program = new commander.Command();96 program97 .arguments('<file>')97 .argument('<file>')98 .exitOverride()99 .allowExcessArguments(false)100 .action(() => {});101
4 unmodified lines
106107 test('when specify excess after <arg> and allowExcessArguments(false) then error', () => {108 const program = new commander.Command();109 program110 .arguments('<file>')110 .argument('<file>')111 .exitOverride()112 .allowExcessArguments(false)113 .action(() => {});114
4 unmodified lines
119120 test('when specify excess after [arg] and allowExcessArguments(false) then error', () => {121 const program = new commander.Command();122 program123 .arguments('[file]')123 .argument('[file]')124 .exitOverride()125 .allowExcessArguments(false)126 .action(() => {});127
4 unmodified lines
132133 test('when specify args for [args...] and allowExcessArguments(false) then no error', () => {134 const program = new commander.Command();135 program136 .arguments('[files...]')136 .argument('[files...]')137 .exitOverride()138 .allowExcessArguments(false)139 .action(() => {});140
5 unmodified lines
modified:tests/command.allowUnknownOption.test.js+1 added-1 removed
81 unmodified lines
82 const program = new commander.Command();83 program84 .exitOverride()85 .command('sub')86 .arguments('[args...]') // unknown option will be passed as an argument86 .argument('[args...]') // unknown option will be passed as an argument87 .allowUnknownOption()88 .option('-p, --pepper', 'add pepper')89 .action(() => { });90
5 unmodified lines
added:tests/command.argumentVariations.test.js+104 added
1const commander = require('../');23// Do some low-level checks that the multiple ways of specifying command arguments produce same internal result,4// and not exhaustively testing all methods elsewhere.56test.each(getSingleArgCases('<explicit-required>'))('when add "<arg>" using %s then argument required', (methodName, cmd) => {7 const argument = cmd._args[0];8 const expectedShape = {9 _name: 'explicit-required',10 required: true,11 variadic: false,12 description: ''13 };14 expect(argument).toEqual(expectedShape);15});1617test.each(getSingleArgCases('implicit-required'))('when add "arg" using %s then argument required', (methodName, cmd) => {18 const argument = cmd._args[0];19 const expectedShape = {20 _name: 'implicit-required',21 required: true,22 variadic: false,23 description: ''24 };25 expect(argument).toEqual(expectedShape);26});2728test.each(getSingleArgCases('[optional]'))('when add "[arg]" using %s then argument optional', (methodName, cmd) => {29 const argument = cmd._args[0];30 const expectedShape = {31 _name: 'optional',32 required: false,33 variadic: false,34 description: ''35 };36 expect(argument).toEqual(expectedShape);37});3839test.each(getSingleArgCases('<explicit-required...>'))('when add "<arg...>" using %s then argument required and variadic', (methodName, cmd) => {40 const argument = cmd._args[0];41 const expectedShape = {42 _name: 'explicit-required',43 required: true,44 variadic: true,45 description: ''46 };47 expect(argument).toEqual(expectedShape);48});4950test.each(getSingleArgCases('implicit-required...'))('when add "arg..." using %s then argument required and variadic', (methodName, cmd) => {51 const argument = cmd._args[0];52 const expectedShape = {53 _name: 'implicit-required',54 required: true,55 variadic: true,56 description: ''57 };58 expect(argument).toEqual(expectedShape);59});6061test.each(getSingleArgCases('[optional...]'))('when add "[arg...]" using %s then argument optional and variadic', (methodName, cmd) => {62 const argument = cmd._args[0];63 const expectedShape = {64 _name: 'optional',65 required: false,66 variadic: true,67 description: ''68 };69 expect(argument).toEqual(expectedShape);70});7172function getSingleArgCases(arg) {73 return [74 ['.arguments', new commander.Command().arguments(arg)],75 ['.argument', new commander.Command().argument(arg)],76 ['.addArgument', new commander.Command('add-argument').addArgument(new commander.Argument(arg))],77 ['.command', new commander.Command().command(`command ${arg}`)]78 ];79}8081test.each(getMultipleArgCases('<first>', '[second]'))('when add two arguments using %s then two arguments', (methodName, cmd) => {82 expect(cmd._args[0].name()).toEqual('first');83 expect(cmd._args[1].name()).toEqual('second');84});8586function getMultipleArgCases(arg1, arg2) {87 return [88 ['.arguments', new commander.Command().arguments(`${arg1} ${arg2}`)],89 ['.argument', new commander.Command().argument(arg1).argument(arg2)],90 ['.addArgument', new commander.Command('add-argument').addArgument(new commander.Argument(arg1)).addArgument(new commander.Argument(arg2))],91 ['.command', new commander.Command().command(`command ${arg1} ${arg2}`)]92 ];93}9495test('when add arguments using multiple methods then all added', () => {96 // This is not a key use case, but explicitly test that additive behaviour.97 const program = new commander.Command();98 const cmd = program.command('sub <arg1> <arg2>');99 cmd.arguments('<arg3> <arg4>');100 cmd.argument('<arg5>');101 cmd.addArgument(new commander.Argument('arg6'));102 const argNames = cmd._args.map(arg => arg.name());103 expect(argNames).toEqual(['arg1', 'arg2', 'arg3', 'arg4', 'arg5', 'arg6']);104});
modified:tests/command.asterisk.test.js+4 added-4 removed
31 unmodified lines
32 const mockAction = jest.fn();33 const program = new commander.Command();34 program35 .command('*')36 .arguments('[args...]')36 .argument('[args...]')37 .action(mockAction);38 program.parse(['node', 'test', 'unrecognised-command']);39 expect(mockAction).toHaveBeenCalled();40 });
17 unmodified lines
58 program59 .command('install');60 program61 .command('*')62 .arguments('[args...]')62 .argument('[args...]')63 .action(mockAction);64 program.parse(['node', 'test', 'unrecognised-command']);65 expect(mockAction).toHaveBeenCalled();66 });
5 unmodified lines
72 program73 .command('install');74 const star = program75 .command('*')76 .arguments('[args...]')76 .argument('[args...]')77 .option('-d, --debug')78 .action(mockAction);79 program.parse(['node', 'test', 'unrecognised-command', '--debug']);80 expect(mockAction).toHaveBeenCalled();
11 unmodified lines
92 })93 .command('install');94 program95 .command('*')96 .arguments('[args...]')96 .argument('[args...]')97 .action(mockAction);98 let caughtErr;99 try {100 program.parse(['node', 'test', 'some-argument', '--unknown']);
64 unmodified lines
modified:tests/command.chain.test.js+13 added-1 removed
1const { Command, Option } = require('../');1const { Command, Option, Argument } = require('../');23// Testing the functions which should chain.4// parse and parseAsync are tested in command.parse.test.js5
9 unmodified lines
15 const result = program.addCommand(new Command('name'));16 expect(result).toBe(program);17 });1819 test('when call .argument() then returns this', () => {20 const program = new Command();21 const result = program.argument('<file>');22 expect(result).toBe(program);23 });2425 test('when call .addArgument() then returns this', () => {26 const program = new Command();27 const result = program.addArgument(new Argument('<file>'));28 expect(result).toBe(program);29 });3031 test('when set .arguments() then returns this', () => {32 const program = new Command();33 const result = program.arguments('<file>');34 expect(result).toBe(program);
134 unmodified lines
modified:tests/command.help.test.js+13 added-4 removed
233 unmodified lines
234 const helpInformation = program.helpInformation();235 expect(helpInformation).toMatch('(choices: "red", "blue", default: "red")');236});237238test('when arguments then included in helpInformation', () => {238test('when argument then included in helpInformation', () => {239 const program = new commander.Command();240 program241 .name('foo')242 .arguments('<file>');242 .argument('<file>');243 const helpInformation = program.helpInformation();244 expect(helpInformation).toMatch('Usage: foo [options] <file>');245});246247test('when arguments described then included in helpInformation', () => {247test('when argument described then included in helpInformation', () => {248 const program = new commander.Command();249 program250 .argument('<file>', 'input source')251 .helpOption(false);252 const helpInformation = program.helpInformation();253 expect(helpInformation).toMatch(/Arguments:\n +file +input source/);254});255256test('when arguments described in deprecated way then included in helpInformation', () => {257 const program = new commander.Command();258 program259 .arguments('<file>')260 .helpOption(false)261 .description('description', { file: 'input source' });262 const helpInformation = program.helpInformation();263 expect(helpInformation).toMatch(/Arguments:\n +file +input source/);264});265257test('when arguments described and empty description then arguments included in helpInformation', () => {266test('when arguments described in deprecated way and empty description then arguments still included in helpInformation', () => {267 const program = new commander.Command();268 program269 .arguments('<file>')270 .helpOption(false)
4 unmodified lines
modified:tests/command.positionalOptions.test.js+13 added-13 removed
7 unmodified lines
8 const program = new commander.Command();9 program.passThroughOptions();10 program11 .option('-d, --debug')12 .arguments('<args...>');12 .argument('<args...>');13 return program;14 }1516 test('when option before command-argument then option parsed', () => {
59 unmodified lines
76 const program = new commander.Command();77 program78 .enablePositionalOptions()79 .option('-s, --shared <value>')80 .arguments('<args...>');80 .argument('<args...>');81 const sub = program82 .command('sub')83 .arguments('[arg]')83 .argument('[arg]')84 .option('-s, --shared <value>')85 .action(() => {}); // Not used, but normal to have action handler on subcommand.86 return { program, sub };87 }
62 unmodified lines
150 program151 .enablePositionalOptions()152 .option('-s, --shared')153 .option('-g, --global')154 .arguments('<args...>');154 .argument('<args...>');155 const sub = program156 .command('sub', { isDefault: true })157 .arguments('[args...]')157 .argument('[args...]')158 .option('-s, --shared')159 .option('-d, --default')160 .action(() => {}); // Not used, but normal to have action handler on subcommand.161 program.command('another'); // Not used, but normal to have more than one subcommand if have a default.
55 unmodified lines
217 const program = new commander.Command();218 program219 .enablePositionalOptions()220 .option('-s, --shared <value>')221 .arguments('<args...>');221 .argument('<args...>');222 const sub = program223 .command('sub')224 .passThroughOptions()225 .arguments('[args...]')225 .argument('[args...]')226 .option('-s, --shared <value>')227 .option('-d, --debug')228 .action(() => {}); // Not used, but normal to have action handler on subcommand.229 return { program, sub };
58 unmodified lines
288 .enablePositionalOptions();289 const sub = program290 .command('sub', { isDefault: true })291 .passThroughOptions()292 .arguments('[args...]')292 .argument('[args...]')293 .option('-d, --debug')294 .action(() => {}); // Not used, but normal to have action handler on subcommand.295 return { program, sub };296 }
34 unmodified lines
331 const program = new commander.Command();332 program333 .enablePositionalOptions()334 .option('-g, --global')335 .arguments('<args...>')335 .argument('<args...>')336 .action(() => {});337 const sub = program338 .command('sub')339 .arguments('[arg]')339 .argument('[arg]')340 .action(() => {});341 return { program, sub };342 }343
34 unmodified lines
378 const program = new commander.Command();379 program380 .passThroughOptions()381 .option('-g, --global')382 .arguments('<args...>')382 .argument('<args...>')383 .action(() => {});384 const sub = program385 .command('sub')386 .arguments('[arg]')386 .argument('[arg]')387 .option('-g, --group')388 .option('-d, --debug')389 .action(() => {});390 return { program, sub };
59 unmodified lines
450 function makeProgram() {451 const program = new commander.Command();452 program453 .option('-d, --debug')454 .arguments('<args...>');454 .argument('<args...>');455 return program;456 }457458 test('when passThroughOptions() then option passed through', () => {
57 unmodified lines
modified:tests/command.unknownCommand.test.js+1 added-1 removed
28 unmodified lines
29 program30 .exitOverride()31 .command('sub');32 program33 .arguments('[args...]')33 .argument('[args...]')34 .action(() => { });35 expect(() => {36 program.parse('node test.js unknown'.split(' '));37 }).not.toThrow();
60 unmodified lines
modified:tests/command.unknownOption.test.js+2 added-2 removed
52 unmodified lines
53 test('when specify unknown option with program and action handler then error', () => {54 const program = new commander.Command();55 program56 .exitOverride()57 .arguments('[file]')57 .argument('[file]')58 .action(() => {});5960 let caughtErr;61 try {
8 unmodified lines
70 // Regression test from #96571 const program = new commander.Command();72 program73 .exitOverride()74 .arguments('[file]')74 .argument('[file]')75 .action(() => {});7677 let caughtErr;78 try {
20 unmodified lines
modified:tests/command.usage.test.js+4 added-4 removed
76 unmodified lines
7778 expect(program.usage()).not.toMatch('[command]');79});8081test('when arguments then arguments included in usage', () => {81test('when argument then argument included in usage', () => {82 const program = new commander.Command();8384 program85 .arguments('<file>');85 .argument('<file>');8687 expect(program.usage()).toMatch('<file>');88});8990test('when options and command and arguments then all three included in usage', () => {90test('when options and command and argument then all three included in usage', () => {91 const program = new commander.Command();9293 program94 .arguments('<file>')94 .argument('<file>')95 .option('--alpha')96 .command('beta');9798 expect(program.usage()).toEqual('[options] [command] <file>');
1 unmodified line
modified:tests/commander.configureCommand.test.js+3 added-3 removed
15 unmodified lines
16test('when default then options+command passed to action', () => {17 const program = new commander.Command();18 const callback = jest.fn();19 program20 .arguments('<value>')20 .argument('<value>')21 .action(callback);22 program.parse(['node', 'test', 'value']);23 expect(callback).toHaveBeenCalledWith('value', program.opts(), program);24});
34 unmodified lines
59 const program = new commander.Command();60 const callback = jest.fn();61 program62 .storeOptionsAsProperties()63 .arguments('<value>')63 .argument('<value>')64 .action(callback);65 program.parse(['node', 'test', 'value']);66 expect(callback).toHaveBeenCalledWith('value', program, program);67});
2 unmodified lines
70 const program = new commander.Command();71 const callback = jest.fn();72 program73 .storeOptionsAsProperties(false)74 .arguments('<value>')74 .argument('<value>')75 .action(callback);76 program.parse(['node', 'test', 'value']);77 expect(callback).toHaveBeenCalledWith('value', program.opts(), program);78});
8 unmodified lines
modified:tests/esm-imports-test.mjs+4 added-1 removed
1import { program, Command, Option, CommanderError, InvalidOptionArgumentError, Help, createCommand } from '../esm.mjs';1import { program, Command, Option, Argument, CommanderError, InvalidOptionArgumentError, Help, createCommand, createOption } from '../esm.mjs';23// Do some simple checks that expected imports are available at runtime.4// Run using `npm run test-esm`.5// Similar tests to test-imports.test.ts
19 unmodified lines
25checkClass(new Option('-e, --example'), 'Option');26checkClass(new CommanderError(1, 'code', 'failed'), 'CommanderError');27checkClass(new InvalidOptionArgumentError('failed'), 'InvalidOptionArgumentError');28checkClass(new Help(), 'Help');29checkClass(new Argument('<file>'), 'Argument');3031console.log('Checking createCommand');32check(typeof createCommand === 'function', 'createCommand is function');33console.log('Checking createOption');34check(typeof createOption === 'function', 'createOption is function');3536console.log('No problems');
modified:tests/help.commandTerm.test.js+2 added-2 removed
25 unmodified lines
26 });2728 test('when command has <argument> then returns name <argument>', () => {29 const command = new commander.Command('program')30 .arguments('<argument>');30 .argument('<argument>');31 const helper = new commander.Help();32 expect(helper.subcommandTerm(command)).toEqual('program <argument>');33 });3435 test('when command has everything then returns name|alias [options] <argument>', () => {36 const command = new commander.Command('program')37 .alias('alias')38 .option('-a,--all')39 .arguments('<argument>');39 .argument('<argument>');40 const helper = new commander.Help();41 expect(helper.subcommandTerm(command)).toEqual('program|alias [options] <argument>');42 });43});
modified:tests/help.commandUsage.test.js+1 added-1 removed
40 unmodified lines
41 test('when program has argument then usage includes argument', () => {42 const program = new commander.Command();43 program44 .name('program')45 .arguments('<file>');45 .argument('<file>');46 const helper = new commander.Help();47 expect(helper.commandUsage(program)).toEqual('program [options] <file>');48 });49});
modified:tests/help.longestArgumentTermLength.test.js+4 added-8 removed
10 unmodified lines
11 });1213 test('when has argument description then returns argument length', () => {14 const program = new commander.Command();15 program.arguments('<wonder>');16 program.description('dummy', { wonder: 'wonder description' });15 program.argument('<wonder>', 'wonder description');16 const helper = new commander.Help();17 expect(helper.longestArgumentTermLength(program, helper)).toEqual('wonder'.length);18 });1920 test('when has multiple argument descriptions then returns longest', () => {21 const program = new commander.Command();23 program.arguments('<alpha> <longest> <beta>');24 program.description('dummy', {25 alpha: 'x',26 longest: 'x',27 beta: 'x'28 });22 program.argument('<alpha>', 'x');23 program.argument('<longest>', 'x');24 program.argument('<beta>', 'x');25 const helper = new commander.Help();26 expect(helper.longestArgumentTermLength(program, helper)).toEqual('longest'.length);27 });28});
modified:tests/help.padWidth.test.js+3 added-6 removed
6 unmodified lines
7 test('when argument term longest return argument length', () => {8 const longestThing = 'veryLongThingBiggerThanOthers';9 const program = new commander.Command();10 program11 .arguments(`<${longestThing}>`)12 .description('description', { veryLongThingBiggerThanOthers: 'desc' })11 .argument(`<${longestThing}>`, 'description')12 .option('-o');13 program14 .command('sub');15 const helper = new commander.Help();
3 unmodified lines
19 test('when option term longest return option length', () => {20 const longestThing = '--very-long-thing-bigger-than-others';21 const program = new commander.Command();22 program24 .arguments('<file}>')25 .description('description', { file: 'desc' })23 .argument('<file>', 'desc')24 .option(longestThing);25 program26 .command('sub');27 const helper = new commander.Help();
3 unmodified lines
31 test('when command term longest return command length', () => {32 const longestThing = 'very-long-thing-bigger-than-others';33 const program = new commander.Command();34 program37 .arguments('<file}>')38 .description('description', { file: 'desc' })35 .argument('<file>', 'desc')36 .option('-o');37 program38 .command(longestThing);39 const helper = new commander.Help();
3 unmodified lines
modified:tests/help.visibleArguments.test.js+42 added-4 removed
10 unmodified lines
11 });1213 test('when argument but no argument description then empty array', () => {14 const program = new commander.Command();15 program.arguments('<file>');15 program.argument('<file>');16 const helper = new commander.Help();17 expect(helper.visibleArguments(program)).toEqual([]);18 });1920 test('when argument and argument description then returned', () => {21 const program = new commander.Command();22 program.arguments('<file>');23 program.description('dummy', { file: 'file description' });22 program.argument('<file>', 'file description');23 const helper = new commander.Help();25 expect(helper.visibleArguments(program)).toEqual([{ term: 'file', description: 'file description' }]);24 const visibleArguments = helper.visibleArguments(program);25 expect(visibleArguments.length).toEqual(1);26 expect(visibleArguments[0]).toEqual(new commander.Argument('<file>', 'file description'));27 });2829 test('when argument and legacy argument description then returned', () => {30 const program = new commander.Command();31 program.argument('<file>');32 program.description('', {33 file: 'file description'34 });35 const helper = new commander.Help();36 const visibleArguments = helper.visibleArguments(program);37 expect(visibleArguments.length).toEqual(1);38 expect(visibleArguments[0]).toEqual(new commander.Argument('<file>', 'file description'));39 });4041 test('when arguments and some described then all returned', () => {42 const program = new commander.Command();43 program.argument('<file1>', 'file1 description');44 program.argument('<file2>');45 const helper = new commander.Help();46 const visibleArguments = helper.visibleArguments(program);47 expect(visibleArguments.length).toEqual(2);48 expect(visibleArguments[0]).toEqual(new commander.Argument('<file1>', 'file1 description'));49 expect(visibleArguments[1]).toEqual(new commander.Argument('<file2>'));50 });5152 test('when arguments and some legacy described then all returned', () => {53 const program = new commander.Command();54 program.argument('<file1>');55 program.argument('<file2>');56 program.description('', {57 file1: 'file1 description'58 });59 const helper = new commander.Help();60 const visibleArguments = helper.visibleArguments(program);61 expect(visibleArguments.length).toEqual(2);62 expect(visibleArguments[0]).toEqual(new commander.Argument('<file1>', 'file1 description'));63 expect(visibleArguments[1]).toEqual(new commander.Argument('<file2>'));64 });65});
modified:tests/options.variadic.test.js+3 added-3 removed
60 unmodified lines
61 test('when variadic with short combined argument then not variadic', () => {62 const program = new commander.Command();63 program64 .option('-r,--required <value...>')65 .arguments('[arg]');65 .argument('[arg]');6667 program.parse(['-rone', 'operand'], { from: 'user' });68 expect(program.opts().required).toEqual(['one']);69 });
1 unmodified line
71 test('when variadic with long combined argument then not variadic', () => {72 const program = new commander.Command();73 program74 .option('-r,--required <value...>')75 .arguments('[arg]');75 .argument('[arg]');7677 program.parse(['--required=one', 'operand'], { from: 'user' });78 expect(program.opts().required).toEqual(['one']);79 });
2 unmodified lines
82 const program = new commander.Command();83 program84 .option('-r,--required <value...>')85 .option('-f, --flag')86 .arguments('[arg]');86 .argument('[arg]');8788 program.parse(['-r', 'one', '-f'], { from: 'user' });89 const opts = program.opts();90 expect(opts.required).toEqual(['one']);
80 unmodified lines
modified:typings/index.d.ts+51 added-3 removed
18 unmodified lines
19 interface InvalidOptionArgumentError extends CommanderError {20 }21 type InvalidOptionArgumentErrorConstructor = new (message: string) => InvalidOptionArgumentError;2223 interface Argument {24 description: string;25 required: boolean;26 variadic: boolean;2728 /**29 * Return argument name.30 */31 name(): string;32 }3334 interface Option {35 flags: string;36 description: string;37
58 unmodified lines
96 */97 attributeName(): string;98 }99 type OptionConstructor = new (flags: string, description?: string) => Option;100 type ArgumentConstructor = new (arg: string, description?: string) => Argument;101102 interface Help {103 /** output helpWidth, long lines are wrapped to fit */104 helpWidth?: number;
7 unmodified lines
112 /** Get the option term to show in the list of options. */113 optionTerm(option: Option): string;114 /** Get the option description to show in the list of options. */115 optionDescription(option: Option): string;116 /** Get the argument term to show in the list of arguments. */117 argumentTerm(argument: Argument): string;118 /** Get the argument description to show in the list of arguments. */119 argumentDescription(argument: Argument): string;120121 /** Get the command usage to be displayed at the top of the built-in help. */122 commandUsage(cmd: Command): string;123 /** Get the description for the command. */
3 unmodified lines
127 visibleCommands(cmd: Command): Command[];128 /** Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one. */129 visibleOptions(cmd: Command): Option[];130 /** Get an array of the arguments which have descriptions. */115 visibleArguments(cmd: Command): Array<{ term: string; description: string}>;131 visibleArguments(cmd: Command): Argument[];132133 /** Get the longest command term length. */134 longestSubcommandTermLength(cmd: Command, helper: Help): number;135 /** Get the longest option term length. */
115 unmodified lines
251252 /**253 * Define argument syntax for command.254 *255 * The default is that the argument is required, and you can explicitly256 * indicate this with <> around the name. Put [] around the name for an optional argument.257 *258 * @example259 *260 * program.argument('<input-file>');261 * program.argument('[output-file]');262 *263 * @returns `this` command for chaining264 */241 arguments(desc: string): this;265 argument(name: string, description?: string): this;266267 /**268 * Define argument syntax for command, adding a prepared argument.269 *270 * @returns `this` command for chaining271 */272 addArgument(arg: Argument): this;273274 /**275 * Define argument syntax for command, adding multiple at once (without descriptions).276 *277 * See also .argument().278 *279 * @example280 *281 * program.arguments('<cmd> [env]');282 *283 * @returns `this` command for chaining284 */285 arguments(names: string): this;286287 /**288 * Override default decision whether to add implicit help command.289 *290 * addHelpCommand() // force on291 * addHelpCommand(false); // force off
243 unmodified lines
535 * Set the description.536 *537 * @returns `this` command for chaining538 */539540 description(str: string): this;541 /** @deprecated since v8, instead use .argument to add command argument with description */495 description(str: string, argsDescription?: {[argName: string]: string}): this;542 description(str: string, argsDescription: {[argName: string]: string}): this;543 /**544 * Get the description.545 */546 description(): string;
113 unmodified lines
660 interface CommanderStatic extends Command {661 program: Command;662 Command: CommandConstructor;663 Option: OptionConstructor;664 Argument: ArgumentConstructor;665 CommanderError: CommanderErrorConstructor;666 InvalidOptionArgumentError: InvalidOptionArgumentErrorConstructor;667 Help: HelpConstructor;668 }
7 unmodified lines
modified:typings/index.test-d.ts+19 added-1 removed
35 unmodified lines
3637// addCommand38expectType<commander.Command>(program.addCommand(new commander.Command('abc')));3940// argument41expectType<commander.Command>(program.argument('<value>'));42expectType<commander.Command>(program.argument('<value>', 'description'));4344// arguments45expectType<commander.Command>(program.arguments('<cmd> [env]'));4647// addHelpCommand
129 unmodified lines
177178// description179expectType<commander.Command>(program.description('my description'));180expectType<string>(program.description());181expectType<commander.Command>(program.description('my description of command with arg foo', { foo: 'foo description'})); // deprecated182183// alias184expectType<commander.Command>(program.alias('my alias'));185expectType<string>(program.alias());
85 unmodified lines
271// Help272const helper = new commander.Help();273const helperCommand = new commander.Command();274const helperOption = new commander.Option('-a, --all');275const helperArgument = new commander.Argument('<file>');276277expectType<number | undefined>(helper.helpWidth);278expectType<boolean>(helper.sortSubcommands);279expectType<boolean>(helper.sortOptions);
3 unmodified lines
283expectType<string>(helper.commandDescription(helperCommand));284expectType<string>(helper.subcommandDescription(helperCommand));285expectType<string>(helper.optionTerm(helperOption));286expectType<string>(helper.optionDescription(helperOption));287expectType<string>(helper.argumentTerm(helperArgument));288expectType<string>(helper.argumentDescription(helperArgument));289290expectType<commander.Command[]>(helper.visibleCommands(helperCommand));291expectType<commander.Option[]>(helper.visibleOptions(helperCommand));284expectType<Array<{ term: string; description: string}>>(helper.visibleArguments(helperCommand));292expectType<commander.Argument[]>(helper.visibleArguments(helperCommand));293294expectType<number>(helper.longestSubcommandTermLength(helperCommand, helper));295expectType<number>(helper.longestOptionTermLength(helperCommand, helper));296expectType<number>(helper.longestArgumentTermLength(helperCommand, helper));
37 unmodified lines
334expectType<string>(baseOption.name());335336// attributeName337expectType<string>(baseOption.attributeName());338339// Argument properties340const baseArgument = new commander.Argument('<foo');341expectType<string>(baseArgument.description);342expectType<boolean>(baseArgument.required);343expectType<boolean>(baseArgument.variadic);344345// Argument methods346// name347expectType<string>(baseArgument.name());
modified:CHANGELOG.md+1 added-1 removed
6 unmodified lines
78<!-- markdownlint-disable MD024 -->9<!-- markdownlint-disable MD004 -->1011## [7.2.0] (2021-03-26)11## [7.2.0] (2021-03-22)1213### Added1415- TypeScript typing for `parent` property on `Command` ([#1475])
425 unmodified lines
modified:esm.mjs+1 added-1 removed
1import commander from './index.js';23// wrapper to provide named exports for ESM.4export const { program, Option, Command, CommanderError, InvalidOptionArgumentError, Help, createCommand } = commander;4export const { program, Option, Command, Argument, CommanderError, InvalidOptionArgumentError, Help, createCommand, createOption } = commander;
modified:index.js+147 added-67 removed
26 unmodified lines
27 visibleCommands(cmd) {28 const visibleCommands = cmd.commands.filter(cmd => !cmd._hidden);29 if (cmd._hasImplicitHelpCommand()) {30 // Create a command matching the implicit help command.31 const args = cmd._helpCommandnameAndArgs.split(/ +/);32 const helpCommand = cmd.createCommand(args.shift())31 const [, helpName, helpArgs] = cmd._helpCommandnameAndArgs.match(/([^ ]+) *(.*)/);32 const helpCommand = cmd.createCommand(helpName)33 .helpOption(false);34 helpCommand.description(cmd._helpCommandDescription);35 helpCommand._parseExpectedArgs(args);35 if (helpArgs) helpCommand.arguments(helpArgs);36 visibleCommands.push(helpCommand);37 }38 if (this.sortSubcommands) {39 visibleCommands.sort((a, b) => {
38 unmodified lines
78 return visibleOptions;79 }8081 /**82 * Get an array of the arguments which have descriptions.82 * Get an array of the arguments if any have a description.83 *84 * @param {Command} cmd85 * @returns {{ term: string, description:string }[]}85 * @returns {Argument[]}86 */8788 visibleArguments(cmd) {89 if (cmd._argsDescription && cmd._args.length) {90 return cmd._args.map((argument) => {91 return { term: argument.name, description: cmd._argsDescription[argument.name] || '' };92 }, 0);89 // Side effect! Apply the legacy descriptions before the arguments are displayed.90 if (cmd._argsDescription) {91 cmd._args.forEach(argument => {92 argument.description = argument.description || cmd._argsDescription[argument.name()] || '';93 });94 }9596 // If there are any arguments with a description then return all the arguments.97 if (cmd._args.find(argument => argument.description)) {98 return cmd._args;99 };100 return [];101 }102103 /**
23 unmodified lines
127 return option.flags;128 }129130 /**131 * Get the argument term to show in the list of arguments.132 *133 * @param {Argument} argument134 * @returns {string}135 */136137 argumentTerm(argument) {138 return argument.name();139 }140141 /**142 * Get the longest command term length.143 *144 * @param {Command} cmd145 * @param {Help} helper
29 unmodified lines
175 */176177 longestArgumentTermLength(cmd, helper) {178 return helper.visibleArguments(cmd).reduce((max, argument) => {162 return Math.max(max, argument.term.length);179 return Math.max(max, helper.argumentTerm(argument).length);180 }, 0);181 };182183 /**
66 unmodified lines
250 return option.description;251 };252253 /**254 * Get the argument description to show in the list of arguments.255 *256 * @param {Argument} argument257 * @return {string}258 */259260 argumentDescription(argument) {261 return argument.description;262 }263264 /**265 * Generate the built-in help text.266 *267 * @param {Command} cmd268 * @param {Help} helper
26 unmodified lines
295 }296297 // Arguments298 const argumentList = helper.visibleArguments(cmd).map((argument) => {271 return formatItem(argument.term, argument.description);299 return formatItem(helper.argumentTerm(argument), helper.argumentDescription(argument));300 });301 if (argumentList.length > 0) {302 output = output.concat(['Arguments:', formatList(argumentList), '']);303 }
67 unmodified lines
371 }).join('\n');372 }373}374375class Argument {376 /**377 * Initialize a new command argument with the given name and description.378 * The default is that the argument is required, and you can explicitly379 * indicate this with <> around the name. Put [] around the name for an optional argument.380 *381 * @param {string} name382 * @param {string} [description]383 */384385 constructor(name, description) {386 this.description = description || '';387 this.variadic = false;388389 switch (name[0]) {390 case '<': // e.g. <required>391 this.required = true;392 this._name = name.slice(1, -1);393 break;394 case '[': // e.g. [optional]395 this.required = false;396 this._name = name.slice(1, -1);397 break;398 default:399 this.required = true;400 this._name = name;401 break;402 }403404 if (this._name.length > 3 && this._name.slice(-3) === '...') {405 this.variadic = true;406 this._name = this._name.slice(0, -3);407 }408 }409410 /**411 * Return argument name.412 *413 * @return {string}414 */415416 name() {417 return this._name;418 };419}420421class Option {422 /**423 * Initialize a new `Option` with the given `flags` and `description`.424 *
214 unmodified lines
639 this._exitCallback = null;640 this._aliases = [];641 this._combineFlagAndOptionalValue = true;642 this._description = '';569 this._argsDescription = undefined;643 this._argsDescription = undefined; // legacy644 this._enablePositionalOptions = false;645 this._passThroughOptions = false;646647 // see .configureOutput() for docs
51 unmodified lines
699 opts = desc;700 desc = null;701 }702 opts = opts || {};629 const args = nameAndArgs.split(/ +/);630 const cmd = this.createCommand(args.shift());703 const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);704 const cmd = this.createCommand(name);705706 if (desc) {707 cmd.description(desc);708 cmd._executableHandler = true;
18 unmodified lines
727 cmd._allowExcessArguments = this._allowExcessArguments;728 cmd._enablePositionalOptions = this._enablePositionalOptions;729730 cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor731 if (args) cmd.arguments(args);732 this.commands.push(cmd);658 cmd._parseExpectedArgs(args);733 cmd.parent = this;734735 if (desc) return this;736 return cmd;
99 unmodified lines
836 return this;837 };838839 /**766 * Define argument syntax for the command.840 * Define argument syntax for command.841 *842 * The default is that the argument is required, and you can explicitly843 * indicate this with <> around the name. Put [] around the name for an optional argument.844 *845 * @example846 *847 * program.argument('<input-file>');848 * program.argument('[output-file]');849 *850 * @param {string} name851 * @param {string} [description]852 * @return {Command} `this` command for chaining853 */854 argument(name, description) {855 const argument = new Argument(name, description);856 this.addArgument(argument);857 return this;858 }859769 arguments(desc) {770 return this._parseExpectedArgs(desc.split(/ +/));860 /**861 * Define argument syntax for command, adding multiple at once (without descriptions).862 *863 * See also .argument().864 *865 * @example866 *867 * program.arguments('<cmd> [env]');868 *869 * @param {string} names870 * @return {Command} `this` command for chaining871 */872873 arguments(names) {874 names.split(/ +/).forEach((detail) => {875 this.argument(detail);876 });877 return this;878 };879880 /**881 * Define argument syntax for command, adding a prepared argument.882 *883 * @param {Argument} argument884 * @return {Command} `this` command for chaining885 */886 addArgument(argument) {887 const previousArgument = this._args.slice(-1)[0];888 if (previousArgument && previousArgument.variadic) {889 throw new Error(`only the last argument can be variadic '${previousArgument.name()}'`);890 }891 this._args.push(argument);892 return this;893 }894895 /**896 * Override default decision whether to add implicit help command.897 *898 * addHelpCommand() // force on899 * addHelpCommand(false); // force off
28 unmodified lines
928 return this._addImplicitHelpCommand;929 };930931 /**810 * Parse expected `args`.811 *812 * For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`.813 *814 * @param {Array} args815 * @return {Command} `this` command for chaining816 * @api private817 */818819 _parseExpectedArgs(args) {820 if (!args.length) return;821 args.forEach((arg) => {822 const argDetails = {823 required: false,824 name: '',825 variadic: false826 };827828 switch (arg[0]) {829 case '<':830 argDetails.required = true;831 argDetails.name = arg.slice(1, -1);832 break;833 case '[':834 argDetails.name = arg.slice(1, -1);835 break;836 }837838 if (argDetails.name.length > 3 && argDetails.name.slice(-3) === '...') {839 argDetails.variadic = true;840 argDetails.name = argDetails.name.slice(0, -3);841 }842 if (argDetails.name) {843 this._args.push(argDetails);844 }845 });846 this._args.forEach((arg, i) => {847 if (arg.variadic && i < this._args.length - 1) {848 throw new Error(`only the last argument can be variadic '${arg.name}'`);849 }850 });851 return this;852 };853854 /**932 * Register callback to use as replacement for calling process.exit.933 *934 * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing935 * @return {Command} `this` command for chaining
630 unmodified lines
1566 // Check expected arguments and collect variadic together.1567 const args = this.args.slice();1568 this._args.forEach((arg, i) => {1569 if (arg.required && args[i] == null) {1493 this.missingArgument(arg.name);1570 this.missingArgument(arg.name());1571 } else if (arg.variadic) {1572 args[i] = args.splice(i);1573 args.length = Math.min(i + 1, args.length);1574 }
352 unmodified lines
1927 */1928 description(str, argsDescription) {1929 if (str === undefined && argsDescription === undefined) return this._description;1930 this._description = str;1931 if (argsDescription) {1854 this._argsDescription = argsDescription;1932 this._argsDescription = argsDescription;1933 }1934 return this;1935 };19361937 /**
236 unmodified lines
2174 */21752176exports.Command = Command;2177exports.Option = Option;2178exports.Argument = Argument;2179exports.CommanderError = CommanderError;2180exports.InvalidOptionArgumentError = InvalidOptionArgumentError;2181exports.Help = Help;2182
30 unmodified lines
22132214/**2215 * Takes an argument and returns its human readable equivalent for help usage.2216 *2137 * @param {Object} arg2217 * @param {Argument} arg2218 * @return {string}2219 * @api private2220 */22212222function humanReadableArgName(arg) {2143 const nameOutput = arg.name + (arg.variadic === true ? '...' : '');2223 const nameOutput = arg.name() + (arg.variadic === true ? '...' : '');22242225 return arg.required2226 ? '<' + nameOutput + '>'2227 : '[' + nameOutput + ']';
70 unmodified lines
modified:Readme.md+22 added-17 removed
392 unmodified lines
393## Commands394395You can specify (sub)commands using `.command()` or `.addCommand()`. There are two ways these can be implemented: using an action handler attached to the command, or as a stand-alone executable file (described in more detail later). The subcommands may be nested ([example](./examples/nestedCommands.js)).396397In 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...`.397In the first parameter to `.command()` you specify the command name. You may append the command-arguments after the command name, or specify them separately using `.argument()`. The arguments may be `<required>` or `[optional]`, and the last argument may also be `variadic...`.398399You can use `.addCommand()` to add an already configured subcommand to the program.400401For example:
7 unmodified lines
409 .action((source, destination) => {410 console.log('clone command called');411 });412413// Command implemented using stand-alone executable file (description is second parameter to `.command`)413// Command implemented using stand-alone executable file, indicated by adding description as second parameter to `.command`.414// Returns `this` for adding more commands.415program416 .command('start <service>', 'start named service')417 .command('stop [service]', 'stop named service, or all if no name supplied');
9 unmodified lines
427subcommand is specified ([example](./examples/defaultCommand.js)).428429### Specify the argument syntax430431You use `.arguments` to specify the expected command-arguments for the top-level command, and for subcommands they are usually432included in the `.command` call. Angled brackets (e.g. `<required>`) indicate required command-arguments.433Square brackets (e.g. `[optional]`) indicate optional command-arguments.434You can optionally describe the arguments in the help by supplying a hash as second parameter to `.description()`.431For subcommands, you can specify the argument syntax in the call to `.command()` (as shown above). This432is the only method usable for subcommands implemented using a stand-alone executable, but for other subcommands433you can instead use the following method.434436Example file: [arguments.js](./examples/arguments.js)435To configure a command, you can use `.argument()` to specify each expected command-argument. 436You supply the argument name and an optional description. The argument may be `<required>` or `[optional]`.437438Example file: [argument.js](./examples/argument.js)439440```js441program442 .version('0.1.0')441 .arguments('<username> [password]')442 .description('test command', {443 username: 'user to login',444 password: 'password for user, if required'445 })443 .argument('<username>', 'user to login')444 .argument('[password]', 'password for user, if required')445 .action((username, password) => {446 console.log('username:', username);448 console.log('environment:', password || 'no password given');447 console.log('password:', password || 'no password given');448 });449```450451 The last argument of a command can be variadic, and only the last argument. To make an argument variadic you453 append `...` to the argument name. For example:452 append `...` to the argument name. A variadic argument is passed to the action handler as an array. For example:453454```js455program456 .version('0.1.0')458 .command('rmdir <dirs...>')457 .command('rmdir')458 .argument('<dirs...>')459 .action(function (dirs) {460 dirs.forEach((dir) => {461 console.log('rmdir %s', dir);462 });463 });464```465466The variadic argument is passed to the action handler as an array.466There is a convenience method to add multiple arguments at once, but without descriptions:467468```js469program470 .arguments('<username> <password>');471```472473### Action handler474475The action handler gets passed a parameter for each command-argument you declared, and two additional parameters476which are the parsed options and the command object itself.
1 unmodified line
478Example file: [thank.js](./examples/thank.js)479480```js481program477 .arguments('<name>')482 .argument('<name>')483 .option('-t, --title <honorific>', 'title to use before name')484 .option('-d, --debug', 'display some debugging')485 .action((name, options, command) => {486 if (options.debug) {
436 unmodified lines