Skip to content
Myr

Add documentation on tricks and traps of using optional options (#1332)

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

* Add documentation on tricks and traps of using optional options * Fix grammar and example. Add future works * Update variadic optional options * Add terminology section * Add that commander follows GNU utility convention * Update terminology; remove our terms from official terms * Update example using option as boolean flag and also having it accept operands * Refactor and expand intro and parse ambiguity * Expand fragments a little, reword GNU reference * Some tweaks, and add GNU link * Rework, and move file

authored by Chong Jia Wei · committed by GitHub · parent 5076dda · Browse files · 1 file+220 added−0 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: John Gee <john@ruru.gen.nz>

Diff stats

1 file+220 added−0 removed

  • other:+220 added−0 removed

1 file+220 added−0 removed

added:docs/options-taking-varying-arguments.md+220 added
1# Options taking varying numbers of option-arguments23The README covers declaring and using options, and mostly parsing will work the way you and your users expect. This page covers some special cases4and 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)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)1415Certain options take a varying number of arguments:1617```js18program19 .option('-c, --compress [percentage]') // 0 or 120 .option('--preprocess <file...>') // 1 or more21 .option('--test [name...]') // 0 or more22```2324This page uses examples with options taking 0 or 1 arguments, but the discussions also apply to variadic options taking more arguments.2526## Parsing ambiguity2728There is a potential downside to be aware of. If a command has both29command-arguments and options with varying option-arguments, this introduces a parsing ambiguity which may affect the user of your program.30Commander looks for option-arguments first, but the user may31intend the argument following the option as a command or command-argument.3233```js34program35 .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 });4344program.parse();45```4647```sh48$ cook scrambled49technique: scrambled50ingredient: undefined5152$ cook -i53technique: undefined54ingredient: cheese5556$ cook -i egg57technique: undefined58ingredient: egg5960$ cook -i scrambled # oops61technique: undefined62ingredient: scrambled63```6465The explicit way to resolve this is use `--` to indicate the end of the options and option-arguments:6667```sh68$ node cook.js -i -- egg69technique: egg70ingredient: cheese71```7273If you want to avoid your users needing to learn when to use `--`, there are a few approaches you could take.7475### Alternative: Make `--` part of your syntax7677Rather than trying to teach your users what `--` does, you could just make it part of your syntax.7879```js80program.usage('[options] -- [technique]');81```8283```sh84$ cook --help85Usage: cook [options] -- [technique]8687Options:88 -i, --ingredient [ingredient] add cheese or given ingredient89 -h, --help display help for command9091$ cook -- scrambled92technique: scrambled93ingredient: undefined9495$ cook -i -- scrambled96technique: scrambled97ingredient: cheese98```99100### Alternative: Put options last101102Commander follows the GNU convention for parsing and allows options before or after the command-arguments, or intermingled.103So by putting the options last, the command-arguments do not get confused with the option-arguments.104105```js106program.usage('[technique] [options]');107```108109```sh110$ cook --help111Usage: cook [technique] [options]112113Options:114 -i, --ingredient [ingredient] add cheese or given ingredient115 -h, --help display help for command116117$ node cook.js scrambled -i118technique: scrambled119ingredient: cheese120```121122### Alternative: Use options instead of command-arguments123124This is a bit more radical, but completely avoids the parsing ambiguity!125126```js127program128 .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```137138```sh139$ cook -i -t scrambled140technique: scrambled141ingredient: cheese142```143## Combining short options, and options taking arguments144145Multiple boolean short options can be combined after a single `-`, like `ls -al`. You can also include just146a single short option which might take a value, as any following characters will147be taken as the value.148149This means that by default you can not combine short options which may take an argument.150151```js152program153 .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)");157program.parse(process.argv);158159const opts = program.opts();160if (opts.other) console.log(`other servings: ${opts.other}`);161if (opts.vegan) console.log(`vegan servings: ${opts.vegan}`);162if (opts.halal) console.log(`halal servings: ${opts.halal}`);163```164165```sh166$ collect -o 3167other servings: 3168$ collect -o3 169other servings: 3170$ collect -l -v171vegan servings: true172halal servings: true173$ collect -lv # oops174halal servings: v175```176177If you wish to use options taking varying arguments as boolean options, you need to specify them separately.178179```180$ collect -a -v -l181any servings: true182vegan servings: true183halal servings: true184```185186### Combining short options as if boolean187188Before Commander v5, combining a short option and the value was not supported, and combined short flags were always expanded.189So `-avl` expanded to `-a -v -l`.190191If you want backwards compatible behaviour, or prefer combining short options as booleans to combining short option and value, 192you may change the behavior.193194To modify the parsing of options taking an optional value:195196```js197.combineFlagAndOptionalValue(true) // `-v45` is treated like `--vegan=45`, this is the default behaviour198.combineFlagAndOptionalValue(false) // `-vl` is treated like `-v -l`199```200201## Terminology202203_Work in progress: this section may move to the main README, or a page of its own._204205The command line arguments are made up of options, option-arguments, commands, and command-arguments.206207| 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) |213214For example:215216```sh217my-utility command -o --option option-argument command-argument-1 command-argument-2218```219220In other references options are sometimes called flags, and command-arguments are sometimes called positional arguments or operands.