Merge remote-tracking branch 'origin/develop' into release/7.x
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by John Gee · committed by John Gee · parents a05a8bc, 3998dd6 · Browse files · 6 files·+258 added−1 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+258 added−1 removed
- tests:+19 added−0 removed
- other:+239 added−1 removed
Provenance
- Commit
091224d- Tree
86720fe- Author
John Gee <john@ruru.gen.nz>- Committer
John Gee <john@ruru.gen.nz>- Parent 1
a05a8bc- Parent 2
3998dd6
6 files changed+258 added−1 removed
added:docs/options-taking-varying-arguments.md+220 added
1+# Options taking varying numbers of option-arguments2+3+The README covers declaring and using options, and mostly parsing will work the way you and your users expect. This page covers some special cases4+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)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)13+ - [Terminology](#terminology)14+15+Certain options take a varying number of arguments:16+17+```js18+program19+ .option('-c, --compress [percentage]') // 0 or 120+ .option('--preprocess <file...>') // 1 or more21+ .option('--test [name...]') // 0 or more22+```23+24+This page uses examples with options taking 0 or 1 arguments, but the discussions also apply to variadic options taking more arguments.25+26+## Parsing ambiguity27+28+There is a potential downside to be aware of. If a command has both29+command-arguments and options with varying option-arguments, this introduces a parsing ambiguity which may affect the user of your program.30+Commander looks for option-arguments first, but the user may31+intend the argument following the option as a command or command-argument.32+33+```js34+program35+ .name('cook')36+ .arguments('[technique]')37+ .option('-i, --ingredient [ingredient]', 'add cheese or given ingredient')38+ .action((technique, options) => {39+ console.log(`technique: ${technique}`);40+ const ingredient = (options.ingredient === true) ? 'cheese' : options.ingredient;41+ console.log(`ingredient: ${ingredient}`);42+ });43+44+program.parse();45+```46+47+```sh48+$ cook scrambled49+technique: scrambled50+ingredient: undefined51+52+$ cook -i53+technique: undefined54+ingredient: cheese55+56+$ cook -i egg57+technique: undefined58+ingredient: egg59+60+$ cook -i scrambled # oops61+technique: undefined62+ingredient: scrambled63+```64+65+The explicit way to resolve this is use `--` to indicate the end of the options and option-arguments:66+67+```sh68+$ node cook.js -i -- egg69+technique: egg70+ingredient: cheese71+```72+73+If you want to avoid your users needing to learn when to use `--`, there are a few approaches you could take.74+75+### Alternative: Make `--` part of your syntax76+77+Rather than trying to teach your users what `--` does, you could just make it part of your syntax.78+79+```js80+program.usage('[options] -- [technique]');81+```82+83+```sh84+$ cook --help85+Usage: cook [options] -- [technique]86+87+Options:88+ -i, --ingredient [ingredient] add cheese or given ingredient89+ -h, --help display help for command90+91+$ cook -- scrambled92+technique: scrambled93+ingredient: undefined94+95+$ cook -i -- scrambled96+technique: scrambled97+ingredient: cheese98+```99+100+### Alternative: Put options last101+102+Commander follows the GNU convention for parsing and allows options before or after the command-arguments, or intermingled.103+So by putting the options last, the command-arguments do not get confused with the option-arguments.104+105+```js106+program.usage('[technique] [options]');107+```108+109+```sh110+$ cook --help111+Usage: cook [technique] [options]112+113+Options:114+ -i, --ingredient [ingredient] add cheese or given ingredient115+ -h, --help display help for command116+117+$ node cook.js scrambled -i118+technique: scrambled119+ingredient: cheese120+```121+122+### Alternative: Use options instead of command-arguments123+124+This is a bit more radical, but completely avoids the parsing ambiguity!125+126+```js127+program128+ .name('cook')129+ .option('-t, --technique <technique>', 'cooking technique')130+ .option('-i, --ingredient [ingredient]', 'add cheese or given ingredient')131+ .action((options) => {132+ console.log(`technique: ${options.technique}`);133+ const ingredient = (options.ingredient === true) ? 'cheese' : options.ingredient;134+ console.log(`ingredient: ${ingredient}`);135+ });136+```137+138+```sh139+$ cook -i -t scrambled140+technique: scrambled141+ingredient: cheese142+```143+## Combining short options, and options taking arguments144+145+Multiple boolean short options can be combined after a single `-`, like `ls -al`. You can also include just146+a single short option which might take a value, as any following characters will147+be taken as the value.148+149+This means that by default you can not combine short options which may take an argument.150+151+```js152+program153+ .name('collect')154+ .option("-o, --other [count]", "other serving(s)")155+ .option("-v, --vegan [count]", "vegan serving(s)")156+ .option("-l, --halal [count]", "halal serving(s)");157+program.parse(process.argv);158+159+const opts = program.opts();160+if (opts.other) console.log(`other servings: ${opts.other}`);161+if (opts.vegan) console.log(`vegan servings: ${opts.vegan}`);162+if (opts.halal) console.log(`halal servings: ${opts.halal}`);163+```164+165+```sh166+$ collect -o 3167+other servings: 3168+$ collect -o3 169+other servings: 3170+$ collect -l -v171+vegan servings: true172+halal servings: true173+$ collect -lv # oops174+halal servings: v175+```176+177+If you wish to use options taking varying arguments as boolean options, you need to specify them separately.178+179+```180+$ collect -a -v -l181+any servings: true182+vegan servings: true183+halal servings: true184+```185+186+### Combining short options as if boolean187+188+Before Commander v5, combining a short option and the value was not supported, and combined short flags were always expanded.189+So `-avl` expanded to `-a -v -l`.190+191+If you want backwards compatible behaviour, or prefer combining short options as booleans to combining short option and value, 192+you may change the behavior.193+194+To modify the parsing of options taking an optional value:195+196+```js197+.combineFlagAndOptionalValue(true) // `-v45` is treated like `--vegan=45`, this is the default behaviour198+.combineFlagAndOptionalValue(false) // `-vl` is treated like `-v -l`199+```200+201+## Terminology202+203+_Work in progress: this section may move to the main README, or a page of its own._204+205+The command line arguments are made up of options, option-arguments, commands, and command-arguments.206+207+| Term | Explanation |208+| --- | --- |209+| option | an argument which is a `-` followed by a character, or `--` followed by a word (or hyphenated words), like `-s` or `--short` |210+| option-argument| some options can take an argument |211+| command | a program or command can have subcommands |212+| command-argument | argument for the command (and not an option or option-argument) |213+214+For example:215+216+```sh217+my-utility command -o --option option-argument command-argument-1 command-argument-2218+```219+220+In other references options are sometimes called flags, and command-arguments are sometimes called positional arguments or operands.modified:examples/env+9 added
10 unmodified lines11 12 program13 .version('0.0.1')14 .arguments('<cmd> [env]')15+ .description('test command', {16+ cmd: 'command to run',17+ env: 'environment to run test in'18+ })19 .action(function(cmdValue, envValue) {20 console.log('command:', cmdValue);21 console.log('environment:', envValue || 'no environment given');22 });23 24 program.parse(process.argv);25+26+// Try the following:27+// node env --help28+// node env add29+// node env add browsermodified:tests/command.help.test.js+19 added
200 unmodified lines201 .addOption(new commander.Option('-c, --colour <colour>').choices(['red', 'blue']).default('red'));202 const helpInformation = program.helpInformation();203 expect(helpInformation).toMatch('(choices: "red", "blue", default: "red")');204 });205+206+test('when arguments then included in helpInformation', () => {207+ const program = new commander.Command();208+ program209+ .name('foo')210+ .arguments('<file>');211+ const helpInformation = program.helpInformation();212+ expect(helpInformation).toMatch('Usage: foo [options] <file>');213+});214+215+test('when arguments described then included in helpInformation', () => {216+ const program = new commander.Command();217+ program218+ .arguments('<file>')219+ .helpOption(false)220+ .description('description', { file: 'input source' });221+ const helpInformation = program.helpInformation();222+ expect(helpInformation).toMatch(/Arguments:\n\n +file +input source/); // [sic], extra line223+});modified:.gitignore+1 added
1 unmodified line2 node_modules3 *.sock4 .idea5 .vscode/6+coverage/modified:package.json+3 added
41 unmodified lines424344454647484950515241 unmodified lines "standard": "^14.3.4", "typescript": "^3.9.7" }, "typings": "typings/index.d.ts", "jest": { "collectCoverage": true }, "engines": { "node": ">= 6" }}modified:Readme.md+6 added-1 removed
75 unmodified lines76 Options are defined with the `.option()` method, also serving as documentation for the options. Each option can have a short flag (single character) and a long name, separated by a comma or space or vertical bar ('|').77 78 The options can be accessed as properties on the Command object. Multi-word options such as "--template-engine" are camel-cased, becoming `program.templateEngine` etc. See also optional new behaviour to [avoid name clashes](#avoiding-option-name-clashes).79 80-Multiple short flags may optionally be combined in a single argument following the dash: boolean flags, the last flag may take a value, and the value.80+Multiple short flags may optionally be combined in a single argument following the dash: boolean flags, followed by a single option taking a value (possibly followed by the value).81 For example `-a -b -p 80` may be written as `-ab -p80` or even `-abp80`.82 83 You can use `--` to indicate the end of the options, and any remaining arguments will be used without being interpreted.84 This is particularly useful for passing options through to another310 unmodified lines395 396 ### Specify the argument syntax397 398 You use `.arguments` to specify the arguments for the top-level command, and for subcommands they are usually included in the `.command` call. Angled brackets (e.g. `<required>`) indicate required input. Square brackets (e.g. `[optional]`) indicate optional input.399+You can optionally describe the arguments in the help by supplying a hash as second parameter to `.description()`.400 401 Example file: [env](./examples/env)402 403 ```js404 program405 .version('0.1.0')406 .arguments('<cmd> [env]')407+ .description('test command', {408+ cmd: 'command to run',409+ env: 'environment to run test in'410+ })411 .action(function (cmd, env) {412 console.log('command:', cmd);413 console.log('environment:', env || 'no environment given');414 });403 unmodified lines