Readme.md
This file
Path
Readme.md
351 lines · 9.9 KiB · Markdown
Last changed by
add callback to allow filtering or post-processing of help textdjulienbefore adoption4d421f9
History of this fileTake it
The walk stopped after 200 commits: lines older than 663b313 point at it.
docsTj Holowaychukbefore adoption663b313
lines 1–2why, one step back1# Commander.js2Merge pull request #356 from gitter-badger/gitter-badgeZhiye Libefore adoption54583a3
line 3why, one step back3Merge pull request #358 from zhiyelee/gitterZhiye Libefore adoption5ae016f
line 4why, one step back4[](http://travis-ci.org/tj/commander.js)Merge pull request #279 from zhiyelee/readmeZhiye Libefore adoption558169f
lines 5–6why, one step back5[](https://www.npmjs.org/package/commander)6[](https://www.npmjs.org/package/commander)Merge pull request #358 from zhiyelee/gitterZhiye Libefore adoption5ae016f
line 7why, one step back7[](https://gitter.im/tj/commander.js?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)docsTj Holowaychukbefore adoption663b313
line 8why, one step back8Merge pull request #300 from zhiyelee/ghreadZhiye Libefore adoption1444cf3
line 9why, one step back9 The complete solution for [node.js](http://nodejs.org) command-line interfaces, inspired by Ruby's [commander](https://github.com/tj/commander). reorganize readmezhiyeleebefore adoption79f04b3
line 10why, one step back10 [API documentation](http://tj.github.com/commander.js/)Merge pull request #279 from zhiyelee/readmeZhiye Libefore adoption558169f
line 11why, one step back11travis badgeTj Holowaychukbefore adoptione33a6cf
line 12why, one step back12docsTj Holowaychukbefore adoption663b313
lines 13–27why, one step back13## Installation1415 $ npm install commander1617## Option parsing1819 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.2021```js22#!/usr/bin/env node2324/**25 * Module dependencies.26 */27typoTj Holowaychukbefore adoption20e5d98
line 28why, one step back28var program = require('commander');docsTj Holowaychukbefore adoption663b313
lines 29–33why, one step back2930program31 .version('0.0.1')32 .option('-p, --peppers', 'Add peppers')33 .option('-P, --pineapple', 'Add pineapple')Merge pull request #371 from malthejorgensen/readme-camelcase-exampleZhiye Libefore adoptione326d94
line 34why, one step back34 .option('-b, --bbq-sauce', 'Add bbq sauce')docsTj Holowaychukbefore adoptiond721114
line 35why, one step back35 .option('-c, --cheese [type]', 'Add the specified type of cheese [marble]', 'marble')docsTj Holowaychukbefore adoption663b313
lines 36–39why, one step back36 .parse(process.argv);3738console.log('you ordered a pizza with:');39if (program.peppers) console.log(' - peppers');Merge pull request #158 from ChrisWren/masterTJ Holowaychukbefore adoption62cd70c
line 40why, one step back40if (program.pineapple) console.log(' - pineapple');Merge pull request #371 from malthejorgensen/readme-camelcase-exampleZhiye Libefore adoptione326d94
line 41why, one step back41if (program.bbqSauce) console.log(' - bbq');docsTj Holowaychukbefore adoptiona72b2da
line 42why, one step back42console.log(' - %s cheese', program.cheese);docsTj Holowaychukbefore adoption663b313
lines 43–44why, one step back43```44camel-case docsTj Holowaychukbefore adoption6a686c1
line 45why, one step back45 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.docsTj Holowaychukbefore adoption663b313
line 46why, one step back46reorganize readmezhiyeleebefore adoption79f04b3
lines 47–90why, one step back4748## Coercion4950```js51function range(val) {52 return val.split('..').map(Number);53}5455function list(val) {56 return val.split(',');57}5859function collect(val, memo) {60 memo.push(val);61 return memo;62}6364function increaseVerbosity(v, total) {65 return total + 1;66}6768program69 .version('0.0.1')70 .usage('[options] <file ...>')71 .option('-i, --integer <n>', 'An integer argument', parseInt)72 .option('-f, --float <n>', 'A float argument', parseFloat)73 .option('-r, --range <a>..<b>', 'A range', range)74 .option('-l, --list <items>', 'A list', list)75 .option('-o, --optional [value]', 'An optional value')76 .option('-c, --collect [value]', 'A repeatable value', collect, [])77 .option('-v, --verbose', 'A value that can be increased', increaseVerbosity, 0)78 .parse(process.argv);7980console.log(' int: %j', program.integer);81console.log(' float: %j', program.float);82console.log(' optional: %j', program.optional);83program.range = program.range || [];84console.log(' range: %j..%j', program.range[0], program.range[1]);85console.log(' list: %j', program.list);86console.log(' collect: %j', program.collect);87console.log(' verbosity: %j', program.verbose);88console.log(' args: %j', program.args);89```90Merge pull request #337 from palanik/masterRandall Koutnikbefore adoption46f9c52
lines 91–102why, one step back91## Regular Expression92```js93program94 .version('0.0.1')95 .option('-s --size <size>', 'Pizza size', /^(large|medium|small)$/i, 'medium')96 .option('-d --drink [drink]', 'Drink', /^(coke|pepsi|izze)$/i)97 .parse(process.argv);98 99console.log(' size: %j', program.size);100console.log(' drink: %j', program.drink);101```102Merge pull request #277 from whitlockjc/fix-issue-53Zhiye Libefore adoptionaf05389
lines 103–126why, one step back103## Variadic arguments104105 The last argument of a command can be variadic, and only the last argument. To make an argument variadic you have to106 append `...` to the argument name. Here is an example:107108```js109#!/usr/bin/env node110111/**112 * Module dependencies.113 */114115var program = require('commander');116117program118 .version('0.0.1')119 .command('rmdir <dir> [otherDirs...]')120 .action(function (dir, otherDirs) {121 console.log('rmdir %s', dir);122 if (otherDirs) {123 otherDirs.forEach(function (oDir) {124 console.log('rmdir %s', oDir);125 });126 }Merge pull request #280 from zhiyelee/fixdemoZhiye Libefore adoption2878611
lines 127–129why, one step back127 });128129program.parse(process.argv);Merge pull request #277 from whitlockjc/fix-issue-53Zhiye Libefore adoptionaf05389
lines 130–134why, one step back130```131132 An `Array` is used for the value of a variadic argument. This applies to `program.args` as well as the argument passed133 to your action as demonstrated above.134Merge pull request #392 from rrthomas/document-argumentsRandall Koutnikbefore adoptionc6ddd55
lines 135–159why, one step back135## Specify the argument syntax136137```js138#!/usr/bin/env node139140var program = require('../');141142program143 .version('0.0.1')144 .arguments('<cmd> [env]')145 .action(function (cmd, env) {146 cmdValue = cmd;147 envValue = env;148 });149150program.parse(process.argv);151152if (typeof cmdValue === 'undefined') {153 console.error('no command given!');154 process.exit(1);155}156console.log('command:', cmdValue);157console.log('environment:', envValue || "no environment given");158```159Merge pull request #295 from zhiyelee/git-style-readmeZhiye Libefore adoptionfc543c8
lines 160–169why, one step back160## Git-style sub-commands161162```js163// file: ./examples/pm164var program = require('..');165166program167 .version('0.0.1')168 .command('install [name]', 'install one or more packages')169 .command('search [query]', 'search with optional query')Merge pull request #415 from Qix-/default-subcommandRandall Koutnikbefore adoption0af40a5
line 170why, one step back170 .command('list', 'list packages installed', {isDefault: true})Merge pull request #295 from zhiyelee/git-style-readmeZhiye Libefore adoptionfc543c8
lines 171–174why, one step back171 .parse(process.argv);172```173174When `.command()` is invoked with a description argument, no `.action(callback)` should be called to handle sub-commands, otherwise there will be an error. This tells commander that you're going to use separate executables for sub-commands, much like `git(1)` and other popular tools. Merge pull request #366 from zhiyelee/typoZhiye Libefore adoption481e943
line 175why, one step back175The commander will try to search the executables in the directory of the entry script (like `./examples/pm`) with the name `program-command`, like `pm-install`, `pm-search`.Merge pull request #415 from Qix-/default-subcommandRandall Koutnikbefore adoption0af40a5
lines 176–177why, one step back176177Options can be passed with the call to `.command()`. Specifying `true` for `opts.noHelp` will remove the option from the generated help output. Specifying `true` for `opts.isDefault` will run the subcommand if no other subcommand is specified.Merge pull request #295 from zhiyelee/git-style-readmeZhiye Libefore adoptionfc543c8
line 178why, one step back178Merge pull request #381 from radiovisual/masterZhiye Libefore adoptionada4787
line 179why, one step back179If the program is designed to be installed globally, make sure the executables have proper modes, like `755`.Merge pull request #365 from zhiyelee/subcommandZhiye Libefore adoption0109a44
line 180why, one step back180Merge pull request #391 from zhiyelee/newversionZhiye Libefore adoption4dae21d
lines 181–186why, one step back181### `--harmony`182183You can enable `--harmony` option in two ways:184* Use `#! /usr/bin/env node --harmony` in the sub-commands scripts. Note some os version don’t support this pattern.185* Use the `--harmony` option when call the command, like `node --harmony examples/pm publish`. The `--harmony` option will be preserved when spawning sub-command process.186docsTj Holowaychukbefore adoption663b313
lines 187–195why, one step back187## Automated --help188189 The help information is auto-generated based on the information commander already knows about your program, so the following `--help` info is for free:190191``` 192 $ ./examples/pizza --help193194 Usage: pizza [options]195Merge pull request #316 from zhiyelee/updatereadmeZhiye Libefore adoption0b95ea2
lines 196–197why, one step back196 An application for pizzas ordering197docsTj Holowaychukbefore adoption663b313
lines 198–199why, one step back198 Options:199Merge pull request #316 from zhiyelee/updatereadmeZhiye Libefore adoption0b95ea2
line 200why, one step back200 -h, --help output usage informationMerge branch 'master' of github.com:visionmedia/commander.jsTJ Holowaychukbefore adoptionef02666
line 201why, one step back201 -V, --version output the version numberdocsTj Holowaychukbefore adoption663b313
line 202why, one step back202 -p, --peppers Add peppersMerge pull request #158 from ChrisWren/masterTJ Holowaychukbefore adoption62cd70c
line 203why, one step back203 -P, --pineapple Add pineappledocsTj Holowaychukbefore adoption663b313
line 204why, one step back204 -b, --bbq Add bbq sauceMerge pull request #397 from tj/revert-208-feature/descriptions-multiline-supportZhiye Libefore adoption64a5a5d
line 205why, one step back205 -c, --cheese <type> Add the specified type of cheese [marble]Merge pull request #316 from zhiyelee/updatereadmeZhiye Libefore adoption0b95ea2
line 206why, one step back206 -C, --no-cheese You do not want any cheesedocsTj Holowaychukbefore adoption663b313
lines 207–209why, one step back207208```209Added support for custom --help outputTj Holowaychukbefore adoptionda13783
lines 210–225why, one step back210## Custom help211212 You can display arbitrary `-h, --help` information213 by listening for "--help". Commander will automatically214 exit once you are done so that the remainder of your program215 does not execute causing undesired behaviours, for example216 in the following executable "stuff" will not output when217 `--help` is used.218219```js220#!/usr/bin/env node221222/**223 * Module dependencies.224 */225Updated Readme.md to make custom help example portableThomas Geraghtybefore adoption79ea120
line 226why, one step back226var program = require('commander');Added support for custom --help outputTj Holowaychukbefore adoptionda13783
lines 227–249why, one step back227228program229 .version('0.0.1')230 .option('-f, --foo', 'enable some foo')231 .option('-b, --bar', 'enable some bar')232 .option('-B, --baz', 'enable some baz');233234// must be before .parse() since235// node's emit() is immediate236237program.on('--help', function(){238 console.log(' Examples:');239 console.log('');240 console.log(' $ custom-help --help');241 console.log(' $ custom-help -h');242 console.log('');243});244245program.parse(process.argv);246247console.log('stuff');248```249Updated Readme.md to make custom help example portableThomas Geraghtybefore adoption79ea120
line 250why, one step back250Yields the following help output when `node script-name.js -h` or `node script-name.js --help` are run:Added support for custom --help outputTj Holowaychukbefore adoptionda13783
lines 251–258why, one step back251252```253254Usage: custom-help [options]255256Options:257258 -h, --help output usage informationMerge branch 'master' of github.com:visionmedia/commander.jsTJ Holowaychukbefore adoptionef02666
line 259why, one step back259 -V, --version output the version numberAdded support for custom --help outputTj Holowaychukbefore adoptionda13783
lines 260–270why, one step back260 -f, --foo enable some foo261 -b, --bar enable some bar262 -B, --baz enable some baz263264Examples:265266 $ custom-help --help267 $ custom-help -h268269```270add callback to allow filtering or post-processing of help textdjulienbefore adoption4d421f9
line 271why, one step back271## .outputHelp(cb)docsTJ Holowaychukbefore adoptionf5078e2
line 272why, one step back272add `outputhelp` usage tipzhiyeleebefore adoption0d842dc
line 273why, one step back273Output help information without exiting.add callback to allow filtering or post-processing of help textdjulienbefore adoption4d421f9
line 274why, one step back274Optional callback cb allows post-processing of help text before it is displayed.add `outputhelp` usage tipzhiyeleebefore adoption0d842dc
lines 275–279why, one step back275276If you want to display help by default (e.g. if no command was provided), you can use something like:277278```js279var program = require('commander');add callback to allow filtering or post-processing of help textdjulienbefore adoption4d421f9
line 280why, one step back280var colors = require('colors');add `outputhelp` usage tipzhiyeleebefore adoption0d842dc
lines 281–287why, one step back281282program283 .version('0.0.1')284 .command('getstream [url]', 'get stream URL')285 .parse(process.argv);286287 if (!process.argv.slice(2).length) {add callback to allow filtering or post-processing of help textdjulienbefore adoption4d421f9
line 288why, one step back288 program.outputHelp(make_red);add `outputhelp` usage tipzhiyeleebefore adoption0d842dc
line 289why, one step back289 }add callback to allow filtering or post-processing of help textdjulienbefore adoption4d421f9
lines 290–293why, one step back290291function make_red(txt) {292 return colors.red(txt); //display the help text in red on the console293}add `outputhelp` usage tipzhiyeleebefore adoption0d842dc
line 294why, one step back294```docsTJ Holowaychukbefore adoptionf5078e2
line 295why, one step back295add callback to allow filtering or post-processing of help textdjulienbefore adoption4d421f9
line 296why, one step back296## .help(cb)docsTJ Holowaychukbefore adoptionf5078e2
lines 297–298why, one step back297298 Output help information and exit immediately.add callback to allow filtering or post-processing of help textdjulienbefore adoption4d421f9
line 299why, one step back299 Optional callback cb allows post-processing of help text before it is displayed.docsTJ Holowaychukbefore adoptionf5078e2
line 300why, one step back300reorganize readmezhiyeleebefore adoption79f04b3
line 301why, one step back301## ExamplesdocsTj Holowaychukbefore adoption663b313
line 302why, one step back302reorganize readmezhiyeleebefore adoption79f04b3
lines 303–345why, one step back303```js304var program = require('commander');305306program307 .version('0.0.1')308 .option('-C, --chdir <path>', 'change the working directory')309 .option('-c, --config <path>', 'set config path. defaults to ./deploy.conf')310 .option('-T, --no-tests', 'ignore test hook')311312program313 .command('setup [env]')314 .description('run setup commands for all envs')315 .option("-s, --setup_mode [mode]", "Which setup mode to use")316 .action(function(env, options){317 var mode = options.setup_mode || "normal";318 env = env || 'all';319 console.log('setup for %s env(s) with %s mode', env, mode);320 });321322program323 .command('exec <cmd>')324 .alias('ex')325 .description('execute the given remote cmd')326 .option("-e, --exec_mode <mode>", "Which exec mode to use")327 .action(function(cmd, options){328 console.log('exec "%s" using %s mode', cmd, options.exec_mode);329 }).on('--help', function() {330 console.log(' Examples:');331 console.log();332 console.log(' $ deploy exec sequential');333 console.log(' $ deploy exec async');334 console.log();335 });336337program338 .command('*')339 .action(function(env){340 console.log('deploying "%s"', env);341 });342343program.parse(process.argv);344```345Merge pull request #366 from zhiyelee/typoZhiye Libefore adoption481e943
line 346why, one step back346More Demos can be found in the [examples](https://github.com/tj/commander.js/tree/master/examples) directory.docsTj Holowaychukbefore adoption663b313
line 347why, one step back347Merge pull request #277 from whitlockjc/fix-issue-53Zhiye Libefore adoptionaf05389
line 348why, one step back348## LicensedocsTj Holowaychukbefore adoption663b313
line 349why, one step back349Merge pull request #365 from zhiyelee/subcommandZhiye Libefore adoption0109a44
line 350why, one step back350MITdocsTj Holowaychukbefore adoption663b313
line 351why, one step back351