Merge pull request #953 from shadowspawn/feature/943-options
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Rework options description to clarify option types and custom processing
authored by Tomoaki Abe · committed by GitHub · parents b2dd7e6, ccee61c · Browse files · 7 files·+338 added−132 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+338 added−132 removed
- other:+338 added−132 removed
Provenance
- Commit
9b6fdae- Tree
8cbf464- Author
Tomoaki Abe <abe@enzou.tokyo>- Committer
GitHub <noreply@github.com>- Parent 1
b2dd7e6- Parent 2
ccee61c
7 files changed+338 added−132 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+36 added
123456789101112131415161718192021222324252627282930313233343536#!/usr/bin/env node
// This is used as an example in the README for:// Common option types, boolean and value// The two most used option types are a boolean flag, and an option which takes a value (declared using angle brackets).//// Example output pretending command called pizza-options (or try directly with `node options-common.js`)//// $ pizza-options -d// { debug: true, small: undefined, pizzaType: undefined }// pizza details:// $ pizza-options -p// error: option `-p, --pizza-type <type>' argument missing// $ pizza-options -ds -p vegetarian// { debug: true, small: true, pizzaType: 'vegetarian' }// pizza details:// - small pizza size// - vegetarian// $ pizza-options --pizza-type=cheese// pizza details:// - cheese
const commander = require('commander');const program = new commander.Command();
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+53 added
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253#!/usr/bin/env node
// This is used as an example in the README for:// Custom option processing// You may specify a function to do custom processing of option values. ...//// Example output pretending command called custom (or try directly with `node options-custom-processing.js`)//// $ custom -f 1e2// float: 100// $ custom --integer 2// integer: 2// $ custom -v -v -v// verbose: 3// $ custom -c a -c b -c c// [ 'a', 'b', 'c' ]// $ custom --list x,y,z// [ 'x', 'y', 'z' ]
const commander = require('commander');const program = new commander.Command();
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+22 added
12345678910111213141516171819202122#!/usr/bin/env node
// This is used as an example in the README for:// Default option value// You can specify a default value for an option which takes a value.//// Example output pretending command called pizza-options (or try directly with `node options-defaults.js`)//// $ pizza-options// cheese: blue// $ pizza-options --cheese stilton// cheese: stilton
const commander = require('commander');const program = new commander.Command();
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+26 added
1234567891011121314151617181920212223242526#!/usr/bin/env node
// This is used as an example in the README for:// Other option types, flag|value// You can specify an option which functions as a flag but may also take a value (declared using square brackets).//// Example output pretending command called pizza-options (or try directly with `node options-flag-or-value.js`)//// $ pizza-options// no cheese// $ pizza-options --cheese// add cheese// $ pizza-options --cheese mozzarella// add cheese type mozzarella
const commander = require('commander');const program = new commander.Command();
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+24 added
123456789101112131415161718192021222324#!/usr/bin/env node
// This is used as an example in the README for:// Other option types, negatable boolean// You can specify a boolean option long name with a leading `no-` to make it true by default and able to be negated.//// Example output pretending command called pizza-options (or try directly with `node options-negatable.js`)//// $ pizza-options// you ordered a pizza with sauce// $ pizza-options --sauce// error: unknown option `--sauce'// $ pizza-options --no-sauce// you ordered a pizza without sauce
const commander = require('commander');const program = new commander.Command();
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+177 added-86 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)7 8 The complete solution for [node.js](http://nodejs.org) command-line interfaces, inspired by Ruby's [commander](https://github.com/commander-rb/commander). 9 [API documentation](http://tj.github.com/commander.js/)10 12-11 ## Installation12 13 $ npm install commander14 17-## Option parsing15+## Declaring _program_ variable16 19-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.17+Commander exports a global object which is convenient for quick programs.18+This is used in the examples in this README for brevity.19 20 ```js22-#!/usr/bin/env node21+const program = require('commander');22+program.version('0.0.1);23+```24 24-/**25- * Module dependencies.26- */25+For larger programs which may use commander in multiple ways, including unit testing, it is better to create a local Command object to use.26 27+ ```js28-var program = require('commander');28+ const commander = require('commander');29+ const program = new commander.Command();30+ program.version('0.0.1);31+ ```32 33+34+## Options35+36+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.37+38+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`.39+40+### Common option types, boolean and value41+42+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.43+44+```js45+const program = require('commander');46+47 program31- .version('0.1.0')32- .option('-p, --peppers', 'Add peppers')33- .option('-P, --pineapple', 'Add pineapple')34- .option('-b, --bbq-sauce', 'Add bbq sauce')35- .option('-c, --cheese [type]', 'Add the specified type of cheese [marble]', 'marble')36- .parse(process.argv);48+ .option('-d, --debug', 'output extra debugging')49+ .option('-s, --small', 'small pizza size')50+ .option('-p, --pizza-type <type>', 'flavour of pizza');51 38-console.log('you ordered a pizza with:');39-if (program.peppers) console.log(' - peppers');40-if (program.pineapple) console.log(' - pineapple');41-if (program.bbqSauce) console.log(' - bbq');42-console.log(' - %s cheese', program.cheese);52+program.parse(process.argv);53+54+if (program.debug) console.log(program.opts());55+console.log('pizza details:');56+if (program.small) console.log('- small pizza size');57+if (program.pizzaType) console.log(`- ${program.pizzaType}`);58 ```59 45-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.60+```bash61+$ pizza-options -d62+{ debug: true, small: undefined, pizzaType: undefined }63+pizza details:64+$ pizza-options -p65+error: option `-p, --pizza-type <type>' argument missing66+$ pizza-options -ds -p vegetarian67+{ debug: true, small: true, pizzaType: 'vegetarian' }68+pizza details:69+- small pizza size70+- vegetarian71+$ pizza-options --pizza-type=cheese72+pizza details:73+- cheese74+```75 47-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.76+`program.parse(arguments)` processes the arguments, leaving any args not consumed by the options as the `program.args` array.77 78+### Default option value79+80+You can specify a default value for an option which takes a value.81+82 ```js50-#!/usr/bin/env node83+const program = require('commander');84 52-/**53- * Module dependencies.54- */85+program86+ .option('-c, --cheese <type>', 'add the specified type of cheese', 'blue');87 56-var program = require('commander');88+program.parse(process.argv);89 90+console.log(`cheese: ${program.cheese}`);91+```92+93+```bash94+$ pizza-options95+cheese: blue96+$ pizza-options --cheese stilton97+cheese: stilton98+```99+100+### Other option types, negatable boolean and flag|value101+102+You can specify a boolean option long name with a leading `no-` to make it true by default and able to be negated.103+104+105+```js106+const program = require('commander');107+108 program59- .option('--no-sauce', 'Remove sauce')109+ .option('-n, --no-sauce', 'Remove sauce')110 .parse(process.argv);111 62-console.log('you ordered a pizza');63-if (program.sauce) console.log(' with sauce');64-else console.log(' without sauce');112+if (program.sauce) console.log('you ordered a pizza with sauce');113+else console.log('you ordered a pizza without sauce');114 ```115 67-To get string arguments from options you will need to use angle brackets <> for required inputs or square brackets [] for optional inputs. 116+```bash117+$ pizza-options118+you ordered a pizza with sauce119+$ pizza-options --sauce120+error: unknown option `--sauce'121+$ pizza-options --no-sauce122+you ordered a pizza without sauce123+```124+You can specify an option which functions as a flag but may also take a value (declared using square brackets).125 69-e.g. ```.option('-m --myarg [myVar]', 'my super cool description')```126 71-Then to access the input if it was passed in.127+```js128+const program = require('commander');129 73-e.g. ```var myInput = program.myarg```130+program131+ .option('-c, --cheese [type]', 'Add cheese with optional type');132 75-**NOTE**: If you pass a argument without using brackets the example above will return true and not the value passed in.133+program.parse(process.argv);134 135+if (program.cheese === undefined) console.log('no cheese');136+else if (program.cheese === true) console.log('add cheese');137+else console.log(`add cheese type ${program.cheese}`);138+```139 78-## Version option140+```bash141+$ pizza-options142+no cheese143+$ pizza-options --cheese144+add cheese145+$ pizza-options --cheese mozzarella146+add cheese type mozzarella147+```148 80-Calling the `version` implicitly adds the `-V` and `--version` options to the command.81-When either of these options is present, the command prints the version number and exits.149+### Custom option processing150 151+You may specify a function to do custom processing of option values. The callback function receives two parameters, the user specified value and the 152+previous value for the option. It returns the new value for the option.153+154+This allows you to coerce the option value to the desired type, or accumulate values, or do entirely custom processing.155+156+You can optionally specify the default/starting value for the option after the function.157+158+```js159+const program = require('commander');160+161+function myParseInt(value, dummyPrevious) {162+ // parseInt takes a string and an optional radix163+ return parseInt(value);164+}165+166+function increaseVerbosity(dummyValue, previous) {167+ return previous + 1;168+}169+170+function collect(value, previous) {171+ return previous.concat([value]);172+}173+174+function commaSeparatedList(value, dummyPrevious) {175+ return value.split(',');176+}177+178+program179+ .option('-f, --float <number>', 'float argument', parseFloat)180+ .option('-i, --integer <number>', 'integer argument', myParseInt)181+ .option('-v, --verbose', 'verbosity that can be increased', increaseVerbosity, 0)182+ .option('-c, --collect <value>', 'repeatable value', collect, [])183+ .option('-l, --list <items>', 'comma separated list', commaSeparatedList)184+;185+186+program.parse(process.argv);187+188+if (program.float !== undefined) console.log(`float: ${program.float}`);189+if (program.integer !== undefined) console.log(`integer: ${program.integer}`);190+if (program.verbose > 0) console.log(`verbosity: ${program.verbose}`);191+if (program.collect.length > 0) console.log(program.collect);192+if (program.list !== undefined) console.log(program.list);193+```194+195+```bash196+$ custom -f 1e2197+float: 100198+$ custom --integer 2199+integer: 2200+$ custom -v -v -v201+verbose: 3202+$ custom -c a -c b -c c203+[ 'a', 'b', 'c' ]204+$ custom --list x,y,z205+[ 'x', 'y', 'z' ]206+```207+208+### Version option209+210+The optional `version` method adds handling for displaying the command version. The default option flags are `-V` and `--version`, and when present the command prints the version number and exits.211+212+```js213+ program.version('0.0.1');214+```215+216+```bash217 $ ./examples/pizza -V218 0.0.1219+```220 86-If you want your program to respond to the `-v` option instead of the `-V` option, simply pass custom flags to the `version` method using the same syntax as the `option` method.221+You may specify custom flags by passing an additional parameter to the `version` method using the same syntax as the `option` method. The version flags can be named anything, but a long name is required.222 223 ```js89-program90- .version('0.0.1', '-v, --version')224+program.version('0.0.1', '-v, --version');225 ```226 93-The version flags can be named anything, but the long option is required.227 228+229 ## Command-specific options230 231 You can attach options to a command.232 13 unmodified lines246 ```247 248 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.249 116-## Coercion117-118-```js119-function range(val) {120- return val.split('..').map(Number);121-}122-123-function list(val) {124- return val.split(',');125-}126-127-function collect(val, memo) {128- memo.push(val);129- return memo;130-}131-132-function increaseVerbosity(v, total) {133- return total + 1;134-}135-136-program137- .version('0.1.0')138- .usage('[options] <file ...>')139- .option('-i, --integer <n>', 'An integer argument', parseInt)140- .option('-f, --float <n>', 'A float argument', parseFloat)141- .option('-r, --range <a>..<b>', 'A range', range)142- .option('-l, --list <items>', 'A list', list)143- .option('-o, --optional [value]', 'An optional value')144- .option('-c, --collect [value]', 'A repeatable value', collect, [])145- .option('-v, --verbose', 'A value that can be increased', increaseVerbosity, 0)146- .parse(process.argv);147-148-console.log(' int: %j', program.integer);149-console.log(' float: %j', program.float);150-console.log(' optional: %j', program.optional);151-program.range = program.range || [];152-console.log(' range: %j..%j', program.range[0], program.range[1]);153-console.log(' list: %j', program.list);154-console.log(' collect: %j', program.collect);155-console.log(' verbosity: %j', program.verbose);156-console.log(' args: %j', program.args);157-```158-250 ## Regular Expression251 ```js252 program253 .version('0.1.0')265 unmodified lines