Skip to content
Myr

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

7 files+338 added−132 removed

deleted:examples/coercion-46 removed
1#!/usr/bin/env node23/**4 * Module dependencies.5 */67var program = require('../');89function range(val) {10 return val.split('..').map(Number);11}1213function list(val) {14 return val.split(',');15}1617function collect(val, memo) {18 memo.push(val);19 return memo;20}2122function increaseVerbosity(v, total) {23 return total + 1;24}2526program27 .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);3738console.log(' int: %j', program.integer);39console.log(' float: %j', program.float);40console.log(' optional: %j', program.optional);41program.range = program.range || [];42console.log(' range: %j..%j', program.range[0], program.range[1]);43console.log(' list: %j', program.list);44console.log(' collect: %j', program.collect);45console.log(' verbosity: %j', program.verbose);46console.log(' args: %j', program.args);
added:examples/options-common.js+36 added
added:examples/options-custom-processing.js+53 added
added:examples/options-defaults.js+22 added
added:examples/options-flag-or-value.js+26 added
added:examples/options-negatable.js+24 added
modified:Readme.md+177 added-86 removed
1# Commander.js233[![Build Status](https://api.travis-ci.org/tj/commander.js.svg?branch=master)](http://travis-ci.org/tj/commander.js)4[![NPM Version](http://img.shields.io/npm/v/commander.svg?style=flat)](https://www.npmjs.org/package/commander)5[![NPM Downloads](https://img.shields.io/npm/dm/commander.svg?style=flat)](https://npmcharts.com/compare/commander?minimal=true)6[![Install Size](https://packagephobia.now.sh/badge?p=commander)](https://packagephobia.now.sh/result?p=commander)78 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/)101211## Installation1213 $ npm install commander1417## Option parsing15## Declaring _program_ variable1619Options 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.17Commander exports a global object which is convenient for quick programs.18This is used in the examples in this README for brevity.1920```js22#!/usr/bin/env node21const program = require('commander');22program.version('0.0.1);23```2424/**25 * Module dependencies.26 */25For larger programs which may use commander in multiple ways, including unit testing, it is better to create a local Command object to use.2627 ```js28var program = require('commander');28 const commander = require('commander');29 const program = new commander.Command();30 program.version('0.0.1);31 ```323334## Options3536Options 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.3738The 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`.3940### Common option types, boolean and value4142The 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.4344```js45const program = require('commander');4647program31 .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');5138console.log('you ordered a pizza with:');39if (program.peppers) console.log(' - peppers');40if (program.pineapple) console.log(' - pineapple');41if (program.bbqSauce) console.log(' - bbq');42console.log(' - %s cheese', program.cheese);52program.parse(process.argv);5354if (program.debug) console.log(program.opts());55console.log('pizza details:');56if (program.small) console.log('- small pizza size');57if (program.pizzaType) console.log(`- ${program.pizzaType}`);58```5945Short 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 }63pizza details:64$ pizza-options -p65error: option `-p, --pizza-type <type>' argument missing66$ pizza-options -ds -p vegetarian67{ debug: true, small: true, pizzaType: 'vegetarian' }68pizza details:69- small pizza size70- vegetarian71$ pizza-options --pizza-type=cheese72pizza details:73- cheese74```7547Note 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.7778### Default option value7980You can specify a default value for an option which takes a value.8182```js50#!/usr/bin/env node83const program = require('commander');8452/**53 * Module dependencies.54 */85program86 .option('-c, --cheese <type>', 'add the specified type of cheese', 'blue');8756var program = require('commander');88program.parse(process.argv);8990console.log(`cheese: ${program.cheese}`);91```9293```bash94$ pizza-options95cheese: blue96$ pizza-options --cheese stilton97cheese: stilton98```99100### Other option types, negatable boolean and flag|value101102You can specify a boolean option long name with a leading `no-` to make it true by default and able to be negated.103104105```js106const program = require('commander');107108program59 .option('--no-sauce', 'Remove sauce')109 .option('-n, --no-sauce', 'Remove sauce')110 .parse(process.argv);11162console.log('you ordered a pizza');63if (program.sauce) console.log(' with sauce');64else console.log(' without sauce');112if (program.sauce) console.log('you ordered a pizza with sauce');113else console.log('you ordered a pizza without sauce');114```11567To get string arguments from options you will need to use angle brackets <> for required inputs or square brackets [] for optional inputs. 116```bash117$ pizza-options118you ordered a pizza with sauce119$ pizza-options --sauce120error: unknown option `--sauce'121$ pizza-options --no-sauce122you ordered a pizza without sauce123```124You can specify an option which functions as a flag but may also take a value (declared using square brackets).12569e.g. ```.option('-m --myarg [myVar]', 'my super cool description')```12671Then to access the input if it was passed in.127```js128const program = require('commander');12973e.g. ```var myInput = program.myarg```130program131 .option('-c, --cheese [type]', 'Add cheese with optional type');13275**NOTE**: If you pass a argument without using brackets the example above will return true and not the value passed in.133program.parse(process.argv);134135if (program.cheese === undefined) console.log('no cheese');136else if (program.cheese === true) console.log('add cheese');137else console.log(`add cheese type ${program.cheese}`);138```13978## Version option140```bash141$ pizza-options142no cheese143$ pizza-options --cheese144add cheese145$ pizza-options --cheese mozzarella146add cheese type mozzarella147```14880Calling the `version` implicitly adds the `-V` and `--version` options to the command.81When either of these options is present, the command prints the version number and exits.149### Custom option processing150151You may specify a function to do custom processing of option values. The callback function receives two parameters, the user specified value and the 152previous value for the option. It returns the new value for the option.153154This allows you to coerce the option value to the desired type, or accumulate values, or do entirely custom processing.155156You can optionally specify the default/starting value for the option after the function.157158```js159const program = require('commander');160161function myParseInt(value, dummyPrevious) {162 // parseInt takes a string and an optional radix163 return parseInt(value);164}165166function increaseVerbosity(dummyValue, previous) {167 return previous + 1;168}169170function collect(value, previous) {171 return previous.concat([value]);172}173174function commaSeparatedList(value, dummyPrevious) {175 return value.split(',');176}177178program179 .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;185186program.parse(process.argv);187188if (program.float !== undefined) console.log(`float: ${program.float}`);189if (program.integer !== undefined) console.log(`integer: ${program.integer}`);190if (program.verbose > 0) console.log(`verbosity: ${program.verbose}`);191if (program.collect.length > 0) console.log(program.collect);192if (program.list !== undefined) console.log(program.list);193```194195```bash196$ custom -f 1e2197float: 100198$ custom --integer 2199integer: 2200$ custom -v -v -v201verbose: 3202$ custom -c a -c b -c c203[ 'a', 'b', 'c' ]204$ custom --list x,y,z205[ 'x', 'y', 'z' ]206```207208### Version option209210The 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.211212```js213 program.version('0.0.1');214```215216```bash217 $ ./examples/pizza -V218 0.0.1219```22086If 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.221You 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.222223```js89program90 .version('0.0.1', '-v, --version')224program.version('0.0.1', '-v, --version');225```22693The version flags can be named anything, but the long option is required.227228229## Command-specific options230231You can attach options to a command.232
13 unmodified lines
246```247248A 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.249116## Coercion117118```js119function range(val) {120 return val.split('..').map(Number);121}122123function list(val) {124 return val.split(',');125}126127function collect(val, memo) {128 memo.push(val);129 return memo;130}131132function increaseVerbosity(v, total) {133 return total + 1;134}135136program137 .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);147148console.log(' int: %j', program.integer);149console.log(' float: %j', program.float);150console.log(' optional: %j', program.optional);151program.range = program.range || [];152console.log(' range: %j..%j', program.range[0], program.range[1]);153console.log(' list: %j', program.list);154console.log(' collect: %j', program.collect);155console.log(' verbosity: %j', program.verbose);156console.log(' args: %j', program.args);157```158250## Regular Expression251```js252program253 .version('0.1.0')
265 unmodified lines