Rework options description to clarify option types and custom processing
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 · parent 3e8bf54 · Browse files · 7 files·+249 added−126 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+249 added−126 removed
- other:+249 added−126 removed
Provenance
- Commit
4309421- Tree
cb37dc1- Author
John Gee <john@ruru.gen.nz>- Committer
John Gee <john@ruru.gen.nz>- Parent
3e8bf54
7 files changed+249 added−126 removed
deleted:examples/coercion-46 removed
1-#!/usr/bin/env node2-3-/**4- * Module dependencies.5- */6-7-var program = require('../');8-9-function range(val) {10- return val.split('..').map(Number);11-}12-13-function list(val) {14- return val.split(',');15-}16-17-function collect(val, memo) {18- memo.push(val);19- return memo;20-}21-22-function increaseVerbosity(v, total) {23- return total + 1;24-}25-26-program27- .version('0.0.1')28- .usage('test')29- .option('-i, --integer <n>', 'An integer argument', parseInt)30- .option('-f, --float <n>', 'A float argument', parseFloat)31- .option('-r, --range <a>..<b>', 'A range', range)32- .option('-l, --list <items>', 'A list', list)33- .option('-o, --optional [value]', 'An optional value')34- .option('-c, --collect [value]', 'A repeatable value', collect, [])35- .option('-v, --verbose', 'A value that can be increased', increaseVerbosity, 0)36- .parse(process.argv);37-38-console.log(' int: %j', program.integer);39-console.log(' float: %j', program.float);40-console.log(' optional: %j', program.optional);41-program.range = program.range || [];42-console.log(' range: %j..%j', program.range[0], program.range[1]);43-console.log(' list: %j', program.list);44-console.log(' collect: %j', program.collect);45-console.log(' verbosity: %j', program.verbose);46-console.log(' args: %j', program.args);added:examples/options-common.js+15 added
123456789101112131415#!/usr/bin/env node
const program = require('commander');
program .option('-d, --debug', 'output extra debugging') .option('-s, --small', 'small pizza size') .option('-p, --pizza-type <type>', 'flavour of pizza');
program.parse(process.argv);
if (program.debug) console.log(program.opts());console.log('pizza details:');if (program.small) console.log('- small pizza size');if (program.pizzaType) console.log(`- ${program.pizzaType}`);added:examples/options-custom-processing.js+35 added
1234567891011121314151617181920212223242526272829303132333435#!/usr/bin/env node
const program = require('commander');
function myParseInt(value, dummyPrevious) { // parseInt takes a string and a radix return parseInt(value, 10);}
function increaseVerbosity(dummyValue, previous) { return previous + 1;}
function collect(value, previous) { return previous.concat([value]);}
function commaSeparatedList(value, dummyPrevious) { return value.split(',');}
program .option('-f, --float <number>', 'float argument', parseFloat) .option('-i, --integer <number>', 'integer argument', myParseInt) .option('-v, --verbose', 'verbosity that can be increased', increaseVerbosity, 0) .option('-c, --collect <value>', 'repeatable value', collect, []) .option('-l, --list <items>', 'comma separated list', commaSeparatedList);
program.parse(process.argv);if (program.float !== undefined) console.log(`float: ${program.float}`);if (program.integer !== undefined) console.log(`integer: ${program.integer}`);if (program.verbose > 0) console.log(`verbosity: ${program.verbose}`);if (program.collect.length > 0) console.log(program.collect);if (program.list !== undefined) console.log(program.list);added:examples/options-defaults.js+10 added
12345678910#!/usr/bin/env node
const program = require('commander');
program .option('-c, --cheese <type>', 'Add the specified type of cheese', 'blue');
program.parse(process.argv);
console.log(`cheese: ${program.cheese}`);added:examples/options-flag-or-value.js+12 added
123456789101112#!/usr/bin/env node
const program = require('commander');
program .option('-c, --cheese [type]', 'Add cheese with optional type');
program.parse(process.argv);
if (program.cheese === undefined) console.log('no cheese');else if (program.cheese === true) console.log('add cheese');else console.log(`add cheese type ${program.cheese}`);added:examples/options-negatable.js+10 added
12345678910#!/usr/bin/env node
const program = require('commander');
program .option('-n, --no-sauce', 'Remove sauce') .parse(process.argv);
if (program.sauce) console.log('you ordered a pizza with sauce');else console.log('you ordered a pizza without sauce');modified:Readme.md+167 added-80 removed
1 # Commander.js2 3-3 [](http://travis-ci.org/tj/commander.js)4 [](https://www.npmjs.org/package/commander)5 [](https://npmcharts.com/compare/commander?minimal=true)6 [](https://packagephobia.now.sh/result?p=commander)1 unmodified line8 9 The complete solution for [node.js](http://nodejs.org) command-line interfaces, inspired by Ruby's [commander](https://github.com/commander-rb/commander). 10 [API documentation](http://tj.github.com/commander.js/)11 13-12 ## Installation13 14 $ npm install commander15 18-## Option parsing16+## Declaring _program_ variable17 20-Options with commander are defined with the `.option()` method, also serving as documentation for the options. The example below parses args and options from `process.argv`, leaving remaining args as the `program.args` array which were not consumed by options.18+Commander exports a global object which is convenient for quick programs.19+This is used in the examples in this README for brevity.20 21 ```js23-#!/usr/bin/env node22+const program = require('commander');23+program.version('0.0.1);24+```25 25-/**26- * Module dependencies.27- */26+For larger programs which may use commander in multiple ways, including unit testing, it is better to create a local Command object to use.27 28+ ```js29-var program = require('commander');29+ const commander = require('commander');30+ const program = new commander.Command;31+ program.version('0.0.1);32+ ```33 34+35+## Options36+37+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.38+39+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. Multiple short flags may be combined as a single arg, for example `-abc` is equivalent to `-a -b -c`.40+41+### Common option types, boolean and value42+43+The two most used option types are a boolean flag, and an option which takes a value (declared using angle brackets). Both are `undefined` unless specified on command line.44+45+```js46+const program = require('commander');47+48 program32- .version('0.1.0')33- .option('-p, --peppers', 'Add peppers')34- .option('-P, --pineapple', 'Add pineapple')35- .option('-b, --bbq-sauce', 'Add bbq sauce')36- .option('-c, --cheese [type]', 'Add the specified type of cheese [marble]', 'marble')37- .parse(process.argv);49+ .option('-d, --debug', 'output extra debugging')50+ .option('-s, --small', 'small pizza size')51+ .option('-p, --pizza-type <type>', 'flavour of pizza');52 39-console.log('you ordered a pizza with:');40-if (program.peppers) console.log(' - peppers');41-if (program.pineapple) console.log(' - pineapple');42-if (program.bbqSauce) console.log(' - bbq');43-console.log(' - %s cheese', program.cheese);53+program.parse(process.argv);54+55+if (program.debug) console.log(program.opts());56+console.log('pizza details:');57+if (program.small) console.log('- small pizza size');58+if (program.pizzaType) console.log(`- ${program.pizzaType}`);59 ```60 46-Short flags may be passed as a single arg, for example `-abc` is equivalent to `-a -b -c`. Multi-word options such as "--template-engine" are camel-cased, becoming `program.templateEngine` etc.61+```bash62+$ pizza-options -d63+{ debug: true, small: undefined, pizzaType: undefined }64+pizza details:65+$ pizza-options -p66+error: option `-p, --pizza-type <type>' argument missing67+$ pizza-options -ds -p vegetarian68+{ debug: true, small: true, pizzaType: 'vegetarian' }69+pizza details:70+- small pizza size71+- vegetarian72+$ pizza-options --pizza-type=cheese73+pizza details:74+- cheese75+```76 48-Note that multi-word options starting with `--no` prefix negate the boolean value of the following word. For example, `--no-sauce` sets the value of `program.sauce` to false.77+`program.parse(arguments)` processes the arguments, leaving any args not consumed by the options as the `program.args` array.78 79+### Default option value80+81+You can specify a default value for an option which takes a value.82+83 ```js51-#!/usr/bin/env node84+const program = require('commander');85 53-/**54- * Module dependencies.55- */86+program87+ .option('-c, --cheese <type>', 'add the specified type of cheese', 'blue');88 57-var program = require('commander');89+program.parse(process.argv);90 91+console.log(`cheese: ${program.cheese}`);92+```93+94+```bash95+$ pizza-options96+cheese: blue97+$ pizza-options --cheese stilton98+cheese: stilton99+```100+101+### Other option types, negatable boolean and flag|value102+103+You can specify a boolean option long name with a leading `no-` to make it true by default and able to be negated.104+105+106+```js107+const program = require('commander');108+109 program60- .option('--no-sauce', 'Remove sauce')110+ .option('-n, --no-sauce', 'Remove sauce')111 .parse(process.argv);112 63-console.log('you ordered a pizza');64-if (program.sauce) console.log(' with sauce');65-else console.log(' without sauce');113+if (program.sauce) console.log('you ordered a pizza with sauce');114+else console.log('you ordered a pizza without sauce');115 ```116 68-To get string arguments from options you will need to use angle brackets <> for required inputs or square brackets [] for optional inputs. 117+```bash118+$ pizza-options119+you ordered a pizza with sauce120+$ pizza-options --sauce121+error: unknown option `--sauce'122+$ pizza-options --no-sauce123+you ordered a pizza without sauce124+```125+You can specify an option which functions as a flag but may also take a value (declared using square brackets).126 70-e.g. ```.option('-m --myarg [myVar]', 'my super cool description')```127 72-Then to access the input if it was passed in.128+```js129+const program = require('commander');130 74-e.g. ```var myInput = program.myarg```131+program132+ .option('-c, --cheese [type]', 'Add cheese with optional type');133 76-**NOTE**: If you pass a argument without using brackets the example above will return true and not the value passed in.134+program.parse(process.argv);135 136+if (program.cheese === undefined) console.log('no cheese');137+else if (program.cheese === true) console.log('add cheese');138+else console.log(`add cheese type ${program.cheese}`);139+```140 79-## Version option141+```bash142+$ pizza-options143+no cheese144+$ pizza-options --cheese145+add cheese146+$ pizza-options --cheese mozzarella147+add cheese type mozzarella148+```149 150+### Custom option processing151+152+You may specify a function to do custom processing on options. The callback function receives two parameters, the user specified value and the 153+previous value for the option. It returns the new value for the option.154+155+This allows you to coerce the option value to the desired type, or accumulate values, or do entirely custom processing.156+157+You can optionally specify the default/starting value for the option after the function.158+159+```js160+const program = require('commander');161+162+function myParseInt(value, dummyPrevious) {163+ // parseInt takes a string and an optional radix164+ return parseInt(value);165+}166+167+function increaseVerbosity(dummyValue, previous) {168+ return previous + 1;169+}170+171+function collect(value, previous) {172+ return previous.concat([value]);173+}174+175+function commaSeparatedList(value, dummyPrevious) {176+ return value.split(',');177+}178+179+program180+ .option('-f, --float <number>', 'float argument', parseFloat)181+ .option('-i, --integer <number>', 'integer argument', myParseInt)182+ .option('-v, --verbose', 'verbosity that can be increased', increaseVerbosity, 0)183+ .option('-c, --collect <value>', 'repeatable value', collect, [])184+ .option('-l, --list <items>', 'comma separated list', commaSeparatedList)185+;186+187+program.parse(process.argv);188+189+if (program.float !== undefined) console.log(`float: ${program.float}`);190+if (program.integer !== undefined) console.log(`integer: ${program.integer}`);191+if (program.verbose > 0) console.log(`verbosity: ${program.verbose}`);192+if (program.collect.length > 0) console.log(program.collect);193+if (program.list !== undefined) console.log(program.list);194+```195+196+```bash197+$ custom -f 1e2198+float: 100199+$ custom --integer 2200+integer: 2201+$ custom -v -v -v202+verbose: 3203+$ custom -c a -c b -c c204+[ 'a', 'b', 'c' ]205+$ custom --list x,y,z206+[ 'x', 'y', 'z' ]207+```208+209+### Version option210+211 Calling the `version` implicitly adds the `-V` and `--version` options to the command.212 When either of these options is present, the command prints the version number and exits.213 214 $ ./examples/pizza -V28 unmodified lines243 ```244 245 A command's options are validated when the command is used. Any unknown options will be reported as an error. However, if an action-based command does not define an action, then the options are not validated.246 117-## Coercion118-119-```js120-function range(val) {121- return val.split('..').map(Number);122-}123-124-function list(val) {125- return val.split(',');126-}127-128-function collect(val, memo) {129- memo.push(val);130- return memo;131-}132-133-function increaseVerbosity(v, total) {134- return total + 1;135-}136-137-program138- .version('0.1.0')139- .usage('[options] <file ...>')140- .option('-i, --integer <n>', 'An integer argument', parseInt)141- .option('-f, --float <n>', 'A float argument', parseFloat)142- .option('-r, --range <a>..<b>', 'A range', range)143- .option('-l, --list <items>', 'A list', list)144- .option('-o, --optional [value]', 'An optional value')145- .option('-c, --collect [value]', 'A repeatable value', collect, [])146- .option('-v, --verbose', 'A value that can be increased', increaseVerbosity, 0)147- .parse(process.argv);148-149-console.log(' int: %j', program.integer);150-console.log(' float: %j', program.float);151-console.log(' optional: %j', program.optional);152-program.range = program.range || [];153-console.log(' range: %j..%j', program.range[0], program.range[1]);154-console.log(' list: %j', program.list);155-console.log(' collect: %j', program.collect);156-console.log(' verbosity: %j', program.verbose);157-console.log(' args: %j', program.args);158-```159-247 ## Regular Expression248 ```js249 program250 .version('0.1.0')265 unmodified lines