Version 1
[yaffs-website] / node_modules / commander / Readme.md
1 # Commander.js
2
3
4 [![Build Status](https://api.travis-ci.org/tj/commander.js.svg)](http://travis-ci.org/tj/commander.js)
5 [![NPM Version](http://img.shields.io/npm/v/commander.svg?style=flat)](https://www.npmjs.org/package/commander)
6 [![NPM Downloads](https://img.shields.io/npm/dm/commander.svg?style=flat)](https://www.npmjs.org/package/commander)
7 [![Join the chat at https://gitter.im/tj/commander.js](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/tj/commander.js?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
8
9   The complete solution for [node.js](http://nodejs.org) command-line interfaces, inspired by Ruby's [commander](https://github.com/tj/commander).  
10   [API documentation](http://tj.github.com/commander.js/)
11
12
13 ## Installation
14
15     $ npm install commander
16
17 ## Option parsing
18
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.
20
21 ```js
22 #!/usr/bin/env node
23
24 /**
25  * Module dependencies.
26  */
27
28 var program = require('commander');
29
30 program
31   .version('0.0.1')
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);
37
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);
43 ```
44
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.
46
47
48 ## Coercion
49
50 ```js
51 function range(val) {
52   return val.split('..').map(Number);
53 }
54
55 function list(val) {
56   return val.split(',');
57 }
58
59 function collect(val, memo) {
60   memo.push(val);
61   return memo;
62 }
63
64 function increaseVerbosity(v, total) {
65   return total + 1;
66 }
67
68 program
69   .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);
79
80 console.log(' int: %j', program.integer);
81 console.log(' float: %j', program.float);
82 console.log(' optional: %j', program.optional);
83 program.range = program.range || [];
84 console.log(' range: %j..%j', program.range[0], program.range[1]);
85 console.log(' list: %j', program.list);
86 console.log(' collect: %j', program.collect);
87 console.log(' verbosity: %j', program.verbose);
88 console.log(' args: %j', program.args);
89 ```
90
91 ## Regular Expression
92 ```js
93 program
94   .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   
99 console.log(' size: %j', program.size);
100 console.log(' drink: %j', program.drink);
101 ```
102
103 ## Variadic arguments
104
105  The last argument of a command can be variadic, and only the last argument.  To make an argument variadic you have to
106  append `...` to the argument name.  Here is an example:
107
108 ```js
109 #!/usr/bin/env node
110
111 /**
112  * Module dependencies.
113  */
114
115 var program = require('commander');
116
117 program
118   .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     }
127   });
128
129 program.parse(process.argv);
130 ```
131
132  An `Array` is used for the value of a variadic argument.  This applies to `program.args` as well as the argument passed
133  to your action as demonstrated above.
134
135 ## Specify the argument syntax
136
137 ```js
138 #!/usr/bin/env node
139
140 var program = require('../');
141
142 program
143   .version('0.0.1')
144   .arguments('<cmd> [env]')
145   .action(function (cmd, env) {
146      cmdValue = cmd;
147      envValue = env;
148   });
149
150 program.parse(process.argv);
151
152 if (typeof cmdValue === 'undefined') {
153    console.error('no command given!');
154    process.exit(1);
155 }
156 console.log('command:', cmdValue);
157 console.log('environment:', envValue || "no environment given");
158 ```
159
160 ## Git-style sub-commands
161
162 ```js
163 // file: ./examples/pm
164 var program = require('..');
165
166 program
167   .version('0.0.1')
168   .command('install [name]', 'install one or more packages')
169   .command('search [query]', 'search with optional query')
170   .command('list', 'list packages installed', {isDefault: true})
171   .parse(process.argv);
172 ```
173
174 When `.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.  
175 The 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`.
176
177 Options 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.
178
179 If the program is designed to be installed globally, make sure the executables have proper modes, like `755`.
180
181 ### `--harmony`
182
183 You 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.
186
187 ## Automated --help
188
189  The help information is auto-generated based on the information commander already knows about your program, so the following `--help` info is for free:
190
191 ```  
192  $ ./examples/pizza --help
193
194    Usage: pizza [options]
195
196    An application for pizzas ordering
197
198    Options:
199
200      -h, --help           output usage information
201      -V, --version        output the version number
202      -p, --peppers        Add peppers
203      -P, --pineapple      Add pineapple
204      -b, --bbq            Add bbq sauce
205      -c, --cheese <type>  Add the specified type of cheese [marble]
206      -C, --no-cheese      You do not want any cheese
207
208 ```
209
210 ## Custom help
211
212  You can display arbitrary `-h, --help` information
213  by listening for "--help". Commander will automatically
214  exit once you are done so that the remainder of your program
215  does not execute causing undesired behaviours, for example
216  in the following executable "stuff" will not output when
217  `--help` is used.
218
219 ```js
220 #!/usr/bin/env node
221
222 /**
223  * Module dependencies.
224  */
225
226 var program = require('commander');
227
228 program
229   .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');
233
234 // must be before .parse() since
235 // node's emit() is immediate
236
237 program.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 });
244
245 program.parse(process.argv);
246
247 console.log('stuff');
248 ```
249
250 Yields the following help output when `node script-name.js -h` or `node script-name.js --help` are run:
251
252 ```
253
254 Usage: custom-help [options]
255
256 Options:
257
258   -h, --help     output usage information
259   -V, --version  output the version number
260   -f, --foo      enable some foo
261   -b, --bar      enable some bar
262   -B, --baz      enable some baz
263
264 Examples:
265
266   $ custom-help --help
267   $ custom-help -h
268
269 ```
270
271 ## .outputHelp(cb)
272
273 Output help information without exiting.
274 Optional callback cb allows post-processing of help text before it is displayed.
275
276 If you want to display help by default (e.g. if no command was provided), you can use something like:
277
278 ```js
279 var program = require('commander');
280 var colors = require('colors');
281
282 program
283   .version('0.0.1')
284   .command('getstream [url]', 'get stream URL')
285   .parse(process.argv);
286
287   if (!process.argv.slice(2).length) {
288     program.outputHelp(make_red);
289   }
290
291 function make_red(txt) {
292   return colors.red(txt); //display the help text in red on the console
293 }
294 ```
295
296 ## .help(cb)
297
298   Output help information and exit immediately.
299   Optional callback cb allows post-processing of help text before it is displayed.
300
301 ## Examples
302
303 ```js
304 var program = require('commander');
305
306 program
307   .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')
311
312 program
313   .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   });
321
322 program
323   .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   });
336
337 program
338   .command('*')
339   .action(function(env){
340     console.log('deploying "%s"', env);
341   });
342
343 program.parse(process.argv);
344 ```
345
346 More Demos can be found in the [examples](https://github.com/tj/commander.js/tree/master/examples) directory.
347
348 ## License
349
350 MIT
351