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)
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
Provenance
- Commit
b286da9- Tree
34c9fb9- Author
John Gee <john@ruru.gen.nz>- Committer
GitHub <noreply@github.com>- Parent
327a3dd
33 files changed+622 added−189 removed
modified:docs/zh-CN/可变参数的选项.md+2 added-2 removed
29 unmodified lines30313233343435363738150 unmodified linesExpand all18919019119219319329 unmodified lines
```jsprogram .name('cook') .arguments('[technique]') .argument('[technique]') .option('-i, --ingredient [ingredient]', 'add cheese or given ingredient') .action((technique, options) => { console.log(`technique: ${technique}`); const ingredient = (options.ingredient === true) ? 'cheese' : options.ingredient;150 unmodified linesExpand all
```js.combineFlagAndOptionalValue(true) // `-v45` 被视为 `--vegan=45`,这是默认的行为.combineFlagAndOptionalValue(false) // `-vl` 被视为 `-v -l````No newline at end of file```modified:docs/deprecated.md+25 added
84 unmodified lines85 );86 ```87 88 Deprecated from Commander v7. 89+90+## cmd.description(cmdDescription, argDescriptions)91+92+This was used to add command argument descriptions for the help.93+94+```js95+program96+ .command('price <book>')97+ .description('show price of book', {98+ book: 'ISBN number for book'99+ });100+```101+102+The new approach is to use the `.argument()` method.103+104+```js105+program106+ .command('price')107+ .description('show price of book')108+ .argument('<book>', 'ISBN number for book');109+```110+111+112+Deprecated from Commander v8.113+modified:docs/options-taking-varying-arguments.md+2 added-2 removed
3 unmodified lines4 and subtle issues in depth.5 6 - [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 lines33 34 ```js35 program36 .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 linesadded:examples/argument.js+24 added
1+#!/usr/bin/env node2+3+// This example shows specifying the arguments using argument() function.4+5+// const { Command } = require('commander'); // (normal include)6+const { Command } = require('../'); // include commander in git clone of commander repo7+const program = new Command();8+9+program10+ .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+ });18+19+program.parse();20+21+// Try the following:22+// node arguments.js --help23+// node arguments.js user24+// node arguments.js user secretmodified:examples/arguments.js+1 added-1 removed
13 unmodified lines14 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 });20 21 program.parse();22 4 unmodified linesmodified:examples/pass-through-options.js+2 added-1 removed
3 unmodified lines4 const { Command } = require('../'); // include commander in git clone of commander repo5 const program = new Command();6 7 program8- .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 linesmodified:examples/thank.js+1 added-1 removed
5 unmodified lines6 const { Command } = require('../'); // include commander in git clone of commander repo7 const program = new Command();8 9 program10- .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 linesadded:tests/argument.variadic.test.js+84 added
1+const commander = require('../');2+3+// Testing variadic arguments. Testing all the action arguments, but could test just variadicArg.4+5+describe('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);13+14+ program.parse(['node', 'test', 'id']);15+16+ expect(actionMock).toHaveBeenCalledWith('id', [], program.opts(), program);17+ });18+19+ 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'];27+28+ program.parse(['node', 'test', 'id', ...extraArguments]);29+30+ expect(actionMock).toHaveBeenCalledWith('id', extraArguments, program.opts(), program);31+ });32+33+ 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);39+40+ program.parse(['node', 'test', 'sub']);41+42+ expect(actionMock).toHaveBeenCalledWith([], cmd.opts(), cmd);43+ });44+45+ 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'];52+53+ program.parse(['node', 'test', 'sub', ...extraArguments]);54+55+ expect(actionMock).toHaveBeenCalledWith(extraArguments, cmd.opts(), cmd);56+ });57+58+ test('when program variadic argument not last then error', () => {59+ const program = new commander.Command();60+61+ expect(() => {62+ program63+ .argument('<variadicArg...>')64+ .argument('[optionalArg]');65+ }).toThrow("only the last argument can be variadic 'variadicArg'");66+ });67+68+ test('when command variadic argument not last then error', () => {69+ const program = new commander.Command();70+71+ expect(() => {72+ program.command('sub <variadicArg...> [optionalArg]');73+ }).toThrow("only the last argument can be variadic 'variadicArg'");74+ });75+76+ test('when variadic argument then usage shows variadic', () => {77+ const program = new commander.Command();78+ program79+ .name('foo')80+ .argument('[args...]');81+82+ expect(program.usage()).toBe('[options] [args...]');83+ });84+});modified:tests/command.action.test.js+19 added-30 removed
21 unmodified lines22 program.parse(['node', 'test', 'info', 'my-file']);23 expect(program.args).toEqual(['info', 'my-file']);24 });25 26-test('when .action on program with required argument and argument supplied then action called', () => {26+test.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 });32 36-test('when .action on program with required argument and argument not supplied then action not called', () => {33+test.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 lines51 program.parse(['node', 'test']);52 expect(actionMock).toHaveBeenCalledWith(program.opts(), program);53 });54 60-test('when .action on program with optional argument supplied then action called', () => {55+test.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 });61 70-test('when .action on program without optional argument supplied then action called', () => {62+test.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 });68 80-test('when .action on program with optional argument and subcommand and program argument then program action called', () => {69+test.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');74 75 program.parse(['node', 'test', 'a']);76 77 expect(actionMock).toHaveBeenCalledWith('a', program.opts(), program);78 });79 80 // Changes made in #1062 to allow this case95-test('when .action on program with optional argument and subcommand and no program argument then program action called', () => {81+test.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');85 86 program.parse(['node', 'test']);87 88 expect(actionMock).toHaveBeenCalledWith(undefined, program.opts(), program);13 unmodified lines102 expect(asyncFinished).toBe(false);103 await later;104 expect(asyncFinished).toBe(true);105 });106+107+function 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 lines93 94 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 lines106 107 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 lines119 120 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 lines132 133 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 linesmodified:tests/command.allowUnknownOption.test.js+1 added-1 removed
81 unmodified lines82 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 linesadded:tests/command.argumentVariations.test.js+104 added
1+const commander = require('../');2+3+// 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.5+6+test.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+});16+17+test.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+});27+28+test.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+});38+39+test.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+});49+50+test.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+});60+61+test.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+});71+72+function 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+}80+81+test.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+});85+86+function 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+}94+95+test('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 lines32 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 lines58 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 lines72 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 lines92 })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 linesmodified:tests/command.chain.test.js+13 added-1 removed
1-const { Command, Option } = require('../');1+const { Command, Option, Argument } = require('../');2 3 // Testing the functions which should chain.4 // parse and parseAsync are tested in command.parse.test.js5 9 unmodified lines15 const result = program.addCommand(new Command('name'));16 expect(result).toBe(program);17 });18 19+ test('when call .argument() then returns this', () => {20+ const program = new Command();21+ const result = program.argument('<file>');22+ expect(result).toBe(program);23+ });24+25+ 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+ });30+31 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 linesmodified:tests/command.help.test.js+13 added-4 removed
233 unmodified lines234 const helpInformation = program.helpInformation();235 expect(helpInformation).toMatch('(choices: "red", "blue", default: "red")');236 });237 238-test('when arguments then included in helpInformation', () => {238+test('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 });246 247-test('when arguments described then included in helpInformation', () => {247+test('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+});255+256+test('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 });265 257-test('when arguments described and empty description then arguments included in helpInformation', () => {266+test('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 linesmodified:tests/command.positionalOptions.test.js+13 added-13 removed
7 unmodified lines8 const program = new commander.Command();9 program.passThroughOptions();10 program11 .option('-d, --debug')12- .arguments('<args...>');12+ .argument('<args...>');13 return program;14 }15 16 test('when option before command-argument then option parsed', () => {59 unmodified lines76 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 lines150 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 lines217 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 lines288 .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 lines331 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 lines378 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 lines450 function makeProgram() {451 const program = new commander.Command();452 program453 .option('-d, --debug')454- .arguments('<args...>');454+ .argument('<args...>');455 return program;456 }457 458 test('when passThroughOptions() then option passed through', () => {57 unmodified linesmodified:tests/command.unknownCommand.test.js+1 added-1 removed
28 unmodified lines29 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 linesmodified:tests/command.unknownOption.test.js+2 added-2 removed
52 unmodified lines53 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(() => {});59 60 let caughtErr;61 try {8 unmodified lines70 // Regression test from #96571 const program = new commander.Command();72 program73 .exitOverride()74- .arguments('[file]')74+ .argument('[file]')75 .action(() => {});76 77 let caughtErr;78 try {20 unmodified linesmodified:tests/command.usage.test.js+4 added-4 removed
76 unmodified lines77 78 expect(program.usage()).not.toMatch('[command]');79 });80 81-test('when arguments then arguments included in usage', () => {81+test('when argument then argument included in usage', () => {82 const program = new commander.Command();83 84 program85- .arguments('<file>');85+ .argument('<file>');86 87 expect(program.usage()).toMatch('<file>');88 });89 90-test('when options and command and arguments then all three included in usage', () => {90+test('when options and command and argument then all three included in usage', () => {91 const program = new commander.Command();92 93 program94- .arguments('<file>')94+ .argument('<file>')95 .option('--alpha')96 .command('beta');97 98 expect(program.usage()).toEqual('[options] [command] <file>');1 unmodified linemodified:tests/commander.configureCommand.test.js+3 added-3 removed
15 unmodified lines16 test('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 lines59 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 lines70 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 linesmodified:tests/esm-imports-test.mjs+4 added-1 removed
1-import { program, Command, Option, CommanderError, InvalidOptionArgumentError, Help, createCommand } from '../esm.mjs';1+import { program, Command, Option, Argument, CommanderError, InvalidOptionArgumentError, Help, createCommand, createOption } from '../esm.mjs';2 3 // 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.ts19 unmodified lines25 checkClass(new Option('-e, --example'), 'Option');26 checkClass(new CommanderError(1, 'code', 'failed'), 'CommanderError');27 checkClass(new InvalidOptionArgumentError('failed'), 'InvalidOptionArgumentError');28 checkClass(new Help(), 'Help');29+checkClass(new Argument('<file>'), 'Argument');30 31 console.log('Checking createCommand');32 check(typeof createCommand === 'function', 'createCommand is function');33+console.log('Checking createOption');34+check(typeof createOption === 'function', 'createOption is function');35 36 console.log('No problems');modified:tests/help.commandTerm.test.js+2 added-2 removed
25 unmodified lines26 });27 28 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 });34 35 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 lines41 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 lines11 });12 13 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 });19 20 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 lines7 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 lines19 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 lines31 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 linesmodified:tests/help.visibleArguments.test.js+42 added-4 removed
10 unmodified lines11 });12 13 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 });19 20 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 });28+29+ 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+ });40+41+ 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+ });51+52+ 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 lines61 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]');66 67 program.parse(['-rone', 'operand'], { from: 'user' });68 expect(program.opts().required).toEqual(['one']);69 });1 unmodified line71 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]');76 77 program.parse(['--required=one', 'operand'], { from: 'user' });78 expect(program.opts().required).toEqual(['one']);79 });2 unmodified lines82 const program = new commander.Command();83 program84 .option('-r,--required <value...>')85 .option('-f, --flag')86- .arguments('[arg]');86+ .argument('[arg]');87 88 program.parse(['-r', 'one', '-f'], { from: 'user' });89 const opts = program.opts();90 expect(opts.required).toEqual(['one']);80 unmodified linesmodified:typings/index.d.ts+51 added-3 removed
18 unmodified lines19 interface InvalidOptionArgumentError extends CommanderError {20 }21 type InvalidOptionArgumentErrorConstructor = new (message: string) => InvalidOptionArgumentError;22 23+ interface Argument {24+ description: string;25+ required: boolean;26+ variadic: boolean;27+28+ /**29+ * Return argument name.30+ */31+ name(): string;32+ }33+34 interface Option {35 flags: string;36 description: string;37 58 unmodified lines96 */97 attributeName(): string;98 }99 type OptionConstructor = new (flags: string, description?: string) => Option;100+ type ArgumentConstructor = new (arg: string, description?: string) => Argument;101 102 interface Help {103 /** output helpWidth, long lines are wrapped to fit */104 helpWidth?: number;7 unmodified lines112 /** 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;120 121 /** 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 lines127 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[];132 133 /** Get the longest command term length. */134 longestSubcommandTermLength(cmd: Command, helper: Help): number;135 /** Get the longest option term length. */115 unmodified lines251 252 /**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;266 267 /**268+ * Define argument syntax for command, adding a prepared argument.269+ *270+ * @returns `this` command for chaining271+ */272+ addArgument(arg: Argument): this;273+274+ /**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;286+287+ /**288 * Override default decision whether to add implicit help command.289 *290 * addHelpCommand() // force on291 * addHelpCommand(false); // force off243 unmodified lines535 * Set the description.536 *537 * @returns `this` command for chaining538 */539+540+ 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 lines660 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 linesmodified:typings/index.test-d.ts+19 added-1 removed
35 unmodified lines36 37 // addCommand38 expectType<commander.Command>(program.addCommand(new commander.Command('abc')));39 40+// argument41+expectType<commander.Command>(program.argument('<value>'));42+expectType<commander.Command>(program.argument('<value>', 'description'));43+44 // arguments45 expectType<commander.Command>(program.arguments('<cmd> [env]'));46 47 // addHelpCommand129 unmodified lines177 178 // description179 expectType<commander.Command>(program.description('my description'));180 expectType<string>(program.description());181+expectType<commander.Command>(program.description('my description of command with arg foo', { foo: 'foo description'})); // deprecated182 183 // alias184 expectType<commander.Command>(program.alias('my alias'));185 expectType<string>(program.alias());85 unmodified lines271 // Help272 const helper = new commander.Help();273 const helperCommand = new commander.Command();274 const helperOption = new commander.Option('-a, --all');275+const helperArgument = new commander.Argument('<file>');276 277 expectType<number | undefined>(helper.helpWidth);278 expectType<boolean>(helper.sortSubcommands);279 expectType<boolean>(helper.sortOptions);3 unmodified lines283 expectType<string>(helper.commandDescription(helperCommand));284 expectType<string>(helper.subcommandDescription(helperCommand));285 expectType<string>(helper.optionTerm(helperOption));286 expectType<string>(helper.optionDescription(helperOption));287+expectType<string>(helper.argumentTerm(helperArgument));288+expectType<string>(helper.argumentDescription(helperArgument));289 290 expectType<commander.Command[]>(helper.visibleCommands(helperCommand));291 expectType<commander.Option[]>(helper.visibleOptions(helperCommand));284-expectType<Array<{ term: string; description: string}>>(helper.visibleArguments(helperCommand));292+expectType<commander.Argument[]>(helper.visibleArguments(helperCommand));293 294 expectType<number>(helper.longestSubcommandTermLength(helperCommand, helper));295 expectType<number>(helper.longestOptionTermLength(helperCommand, helper));296 expectType<number>(helper.longestArgumentTermLength(helperCommand, helper));37 unmodified lines334 expectType<string>(baseOption.name());335 336 // attributeName337 expectType<string>(baseOption.attributeName());338+339+// Argument properties340+const baseArgument = new commander.Argument('<foo');341+expectType<string>(baseArgument.description);342+expectType<boolean>(baseArgument.required);343+expectType<boolean>(baseArgument.variadic);344+345+// Argument methods346+// name347+expectType<string>(baseArgument.name());modified:CHANGELOG.md+1 added-1 removed
6 unmodified lines7 8 <!-- markdownlint-disable MD024 -->9 <!-- markdownlint-disable MD004 -->10 11-## [7.2.0] (2021-03-26)11+## [7.2.0] (2021-03-22)12 13 ### Added14 15 - TypeScript typing for `parent` property on `Command` ([#1475])425 unmodified linesmodified:esm.mjs+1 added-1 removed
1 import commander from './index.js';2 3 // wrapper to provide named exports for ESM.4-export const { program, Option, Command, CommanderError, InvalidOptionArgumentError, Help, createCommand } = commander;4+export const { program, Option, Command, Argument, CommanderError, InvalidOptionArgumentError, Help, createCommand, createOption } = commander;modified:index.js+147 added-67 removed
26 unmodified lines27 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 lines78 return visibleOptions;79 }80 81 /**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 */87 88 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 }95+96+ // 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 }102 103 /**23 unmodified lines127 return option.flags;128 }129 130 /**131+ * Get the argument term to show in the list of arguments.132+ *133+ * @param {Argument} argument134+ * @returns {string}135+ */136+137+ argumentTerm(argument) {138+ return argument.name();139+ }140+141+ /**142 * Get the longest command term length.143 *144 * @param {Command} cmd145 * @param {Help} helper29 unmodified lines175 */176 177 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 };182 183 /**66 unmodified lines250 return option.description;251 };252 253 /**254+ * Get the argument description to show in the list of arguments.255+ *256+ * @param {Argument} argument257+ * @return {string}258+ */259+260+ argumentDescription(argument) {261+ return argument.description;262+ }263+264+ /**265 * Generate the built-in help text.266 *267 * @param {Command} cmd268 * @param {Help} helper26 unmodified lines295 }296 297 // 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 lines371 }).join('\n');372 }373 }374 375+class 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+ */384+385+ constructor(name, description) {386+ this.description = description || '';387+ this.variadic = false;388+389+ 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+ }403+404+ if (this._name.length > 3 && this._name.slice(-3) === '...') {405+ this.variadic = true;406+ this._name = this._name.slice(0, -3);407+ }408+ }409+410+ /**411+ * Return argument name.412+ *413+ * @return {string}414+ */415+416+ name() {417+ return this._name;418+ };419+}420+421 class Option {422 /**423 * Initialize a new `Option` with the given `flags` and `description`.424 *214 unmodified lines639 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;646 647 // see .configureOutput() for docs51 unmodified lines699 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);705 706 if (desc) {707 cmd.description(desc);708 cmd._executableHandler = true;18 unmodified lines727 cmd._allowExcessArguments = this._allowExcessArguments;728 cmd._enablePositionalOptions = this._enablePositionalOptions;729 730 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;734 735 if (desc) return this;736 return cmd;99 unmodified lines836 return this;837 };838 839 /**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+ }859 769- 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+ */872+873+ arguments(names) {874+ names.split(/ +/).forEach((detail) => {875+ this.argument(detail);876+ });877+ return this;878 };879 880 /**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+ }894+895+ /**896 * Override default decision whether to add implicit help command.897 *898 * addHelpCommand() // force on899 * addHelpCommand(false); // force off28 unmodified lines928 return this._addImplicitHelpCommand;929 };930 931 /**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- */818-819- _parseExpectedArgs(args) {820- if (!args.length) return;821- args.forEach((arg) => {822- const argDetails = {823- required: false,824- name: '',825- variadic: false826- };827-828- 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- }837-838- 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- };853-854- /**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 chaining630 unmodified lines1566 // 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 lines1927 */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 };1936 1937 /**236 unmodified lines2174 */2175 2176 exports.Command = Command;2177 exports.Option = Option;2178+exports.Argument = Argument;2179 exports.CommanderError = CommanderError;2180 exports.InvalidOptionArgumentError = InvalidOptionArgumentError;2181 exports.Help = Help;2182 30 unmodified lines2213 2214 /**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 */2221 2222 function humanReadableArgName(arg) {2143- const nameOutput = arg.name + (arg.variadic === true ? '...' : '');2223+ const nameOutput = arg.name() + (arg.variadic === true ? '...' : '');2224 2225 return arg.required2226 ? '<' + nameOutput + '>'2227 : '[' + nameOutput + ']';70 unmodified linesmodified:Readme.md+22 added-17 removed
392 unmodified lines393 ## Commands394 395 You 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)).396 397-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...`.397+In 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...`.398 399 You can use `.addCommand()` to add an already configured subcommand to the program.400 401 For example:7 unmodified lines409 .action((source, destination) => {410 console.log('clone command called');411 });412 413-// 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.415 program416 .command('start <service>', 'start named service')417 .command('stop [service]', 'stop named service, or all if no name supplied');9 unmodified lines427 subcommand is specified ([example](./examples/defaultCommand.js)).428 429 ### Specify the argument syntax430 431-You use `.arguments` to specify the expected command-arguments for the top-level command, and for subcommands they are usually432-included in the `.command` call. Angled brackets (e.g. `<required>`) indicate required command-arguments.433-Square brackets (e.g. `[optional]`) indicate optional command-arguments.434-You can optionally describe the arguments in the help by supplying a hash as second parameter to `.description()`.431+For subcommands, you can specify the argument syntax in the call to `.command()` (as shown above). This432+is the only method usable for subcommands implemented using a stand-alone executable, but for other subcommands433+you can instead use the following method.434 436-Example file: [arguments.js](./examples/arguments.js)435+To configure a command, you can use `.argument()` to specify each expected command-argument. 436+You supply the argument name and an optional description. The argument may be `<required>` or `[optional]`.437 438+Example file: [argument.js](./examples/argument.js)439+440 ```js441 program442 .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 ```450 451 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:453 454 ```js455 program456 .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 ```465 466-The variadic argument is passed to the action handler as an array.466+There is a convenience method to add multiple arguments at once, but without descriptions:467 468+```js469+program470+ .arguments('<username> <password>');471+```472+473 ### Action handler474 475 The action handler gets passed a parameter for each command-argument you declared, and two additional parameters476 which are the parsed options and the command object itself. 1 unmodified line478 Example file: [thank.js](./examples/thank.js)479 480 ```js481 program477- .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