Websocket
[VSoRC/.git] / node_modules / wscat / node_modules / commander / Readme.md
1 # Commander.js
2
3
4 [![Build Status](https://api.travis-ci.org/tj/commander.js.svg?branch=master)](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://npmcharts.com/compare/commander?minimal=true)
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/commander-rb/commander).  
10   [API documentation](http://tj.github.com/commander.js/)
11
12
13 ## Installation
14
15     $ npm install commander --save
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.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);
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 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. 
48
49 ```js
50 #!/usr/bin/env node
51
52 /**
53  * Module dependencies.
54  */
55
56 var program = require('commander');
57
58 program
59   .option('--no-sauce', 'Remove sauce')
60   .parse(process.argv);
61
62 console.log('you ordered a pizza');
63 if (program.sauce) console.log('  with sauce');
64 else console.log(' without sauce');
65 ```
66
67 ## Version option
68
69 Calling the `version` implicitly adds the `-V` and `--version` options to the command.
70 When either of these options is present, the command prints the version number and exits.
71
72     $ ./examples/pizza -V
73     0.0.1
74
75 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.
76
77 ```js
78 program
79   .version('0.0.1', '-v, --version')
80 ```
81
82 The version flags can be named anything, but the long option is required.
83
84 ## Command-specific options
85
86 You can attach options to a command.
87
88 ```js
89 #!/usr/bin/env node
90
91 var program = require('commander');
92
93 program
94   .command('rm <dir>')
95   .option('-r, --recursive', 'Remove recursively')
96   .action(function (dir, cmd) {
97     console.log('remove ' + dir + (cmd.recursive ? ' recursively' : ''))
98   })
99
100 program.parse(process.argv)
101 ```
102
103 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.
104
105 ## Coercion
106
107 ```js
108 function range(val) {
109   return val.split('..').map(Number);
110 }
111
112 function list(val) {
113   return val.split(',');
114 }
115
116 function collect(val, memo) {
117   memo.push(val);
118   return memo;
119 }
120
121 function increaseVerbosity(v, total) {
122   return total + 1;
123 }
124
125 program
126   .version('0.1.0')
127   .usage('[options] <file ...>')
128   .option('-i, --integer <n>', 'An integer argument', parseInt)
129   .option('-f, --float <n>', 'A float argument', parseFloat)
130   .option('-r, --range <a>..<b>', 'A range', range)
131   .option('-l, --list <items>', 'A list', list)
132   .option('-o, --optional [value]', 'An optional value')
133   .option('-c, --collect [value]', 'A repeatable value', collect, [])
134   .option('-v, --verbose', 'A value that can be increased', increaseVerbosity, 0)
135   .parse(process.argv);
136
137 console.log(' int: %j', program.integer);
138 console.log(' float: %j', program.float);
139 console.log(' optional: %j', program.optional);
140 program.range = program.range || [];
141 console.log(' range: %j..%j', program.range[0], program.range[1]);
142 console.log(' list: %j', program.list);
143 console.log(' collect: %j', program.collect);
144 console.log(' verbosity: %j', program.verbose);
145 console.log(' args: %j', program.args);
146 ```
147
148 ## Regular Expression
149 ```js
150 program
151   .version('0.1.0')
152   .option('-s --size <size>', 'Pizza size', /^(large|medium|small)$/i, 'medium')
153   .option('-d --drink [drink]', 'Drink', /^(coke|pepsi|izze)$/i)
154   .parse(process.argv);
155   
156 console.log(' size: %j', program.size);
157 console.log(' drink: %j', program.drink);
158 ```
159
160 ## Variadic arguments
161
162  The last argument of a command can be variadic, and only the last argument.  To make an argument variadic you have to
163  append `...` to the argument name.  Here is an example:
164
165 ```js
166 #!/usr/bin/env node
167
168 /**
169  * Module dependencies.
170  */
171
172 var program = require('commander');
173
174 program
175   .version('0.1.0')
176   .command('rmdir <dir> [otherDirs...]')
177   .action(function (dir, otherDirs) {
178     console.log('rmdir %s', dir);
179     if (otherDirs) {
180       otherDirs.forEach(function (oDir) {
181         console.log('rmdir %s', oDir);
182       });
183     }
184   });
185
186 program.parse(process.argv);
187 ```
188
189  An `Array` is used for the value of a variadic argument.  This applies to `program.args` as well as the argument passed
190  to your action as demonstrated above.
191
192 ## Specify the argument syntax
193
194 ```js
195 #!/usr/bin/env node
196
197 var program = require('commander');
198
199 program
200   .version('0.1.0')
201   .arguments('<cmd> [env]')
202   .action(function (cmd, env) {
203      cmdValue = cmd;
204      envValue = env;
205   });
206
207 program.parse(process.argv);
208
209 if (typeof cmdValue === 'undefined') {
210    console.error('no command given!');
211    process.exit(1);
212 }
213 console.log('command:', cmdValue);
214 console.log('environment:', envValue || "no environment given");
215 ```
216 Angled brackets (e.g. `<cmd>`) indicate required input. Square brackets (e.g. `[env]`) indicate optional input.
217
218 ## Git-style sub-commands
219
220 ```js
221 // file: ./examples/pm
222 var program = require('commander');
223
224 program
225   .version('0.1.0')
226   .command('install [name]', 'install one or more packages')
227   .command('search [query]', 'search with optional query')
228   .command('list', 'list packages installed', {isDefault: true})
229   .parse(process.argv);
230 ```
231
232 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.  
233 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`.
234
235 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.
236
237 If the program is designed to be installed globally, make sure the executables have proper modes, like `755`.
238
239 ### `--harmony`
240
241 You can enable `--harmony` option in two ways:
242 * Use `#! /usr/bin/env node --harmony` in the sub-commands scripts. Note some os version don’t support this pattern.
243 * 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.
244
245 ## Automated --help
246
247  The help information is auto-generated based on the information commander already knows about your program, so the following `--help` info is for free:
248
249 ```  
250  $ ./examples/pizza --help
251
252    Usage: pizza [options]
253
254    An application for pizzas ordering
255
256    Options:
257
258      -h, --help           output usage information
259      -V, --version        output the version number
260      -p, --peppers        Add peppers
261      -P, --pineapple      Add pineapple
262      -b, --bbq            Add bbq sauce
263      -c, --cheese <type>  Add the specified type of cheese [marble]
264      -C, --no-cheese      You do not want any cheese
265
266 ```
267
268 ## Custom help
269
270  You can display arbitrary `-h, --help` information
271  by listening for "--help". Commander will automatically
272  exit once you are done so that the remainder of your program
273  does not execute causing undesired behaviours, for example
274  in the following executable "stuff" will not output when
275  `--help` is used.
276
277 ```js
278 #!/usr/bin/env node
279
280 /**
281  * Module dependencies.
282  */
283
284 var program = require('commander');
285
286 program
287   .version('0.1.0')
288   .option('-f, --foo', 'enable some foo')
289   .option('-b, --bar', 'enable some bar')
290   .option('-B, --baz', 'enable some baz');
291
292 // must be before .parse() since
293 // node's emit() is immediate
294
295 program.on('--help', function(){
296   console.log('  Examples:');
297   console.log('');
298   console.log('    $ custom-help --help');
299   console.log('    $ custom-help -h');
300   console.log('');
301 });
302
303 program.parse(process.argv);
304
305 console.log('stuff');
306 ```
307
308 Yields the following help output when `node script-name.js -h` or `node script-name.js --help` are run:
309
310 ```
311
312 Usage: custom-help [options]
313
314 Options:
315
316   -h, --help     output usage information
317   -V, --version  output the version number
318   -f, --foo      enable some foo
319   -b, --bar      enable some bar
320   -B, --baz      enable some baz
321
322 Examples:
323
324   $ custom-help --help
325   $ custom-help -h
326
327 ```
328
329 ## .outputHelp(cb)
330
331 Output help information without exiting.
332 Optional callback cb allows post-processing of help text before it is displayed.
333
334 If you want to display help by default (e.g. if no command was provided), you can use something like:
335
336 ```js
337 var program = require('commander');
338 var colors = require('colors');
339
340 program
341   .version('0.1.0')
342   .command('getstream [url]', 'get stream URL')
343   .parse(process.argv);
344
345 if (!process.argv.slice(2).length) {
346   program.outputHelp(make_red);
347 }
348
349 function make_red(txt) {
350   return colors.red(txt); //display the help text in red on the console
351 }
352 ```
353
354 ## .help(cb)
355
356   Output help information and exit immediately.
357   Optional callback cb allows post-processing of help text before it is displayed.
358
359 ## Examples
360
361 ```js
362 var program = require('commander');
363
364 program
365   .version('0.1.0')
366   .option('-C, --chdir <path>', 'change the working directory')
367   .option('-c, --config <path>', 'set config path. defaults to ./deploy.conf')
368   .option('-T, --no-tests', 'ignore test hook');
369
370 program
371   .command('setup [env]')
372   .description('run setup commands for all envs')
373   .option("-s, --setup_mode [mode]", "Which setup mode to use")
374   .action(function(env, options){
375     var mode = options.setup_mode || "normal";
376     env = env || 'all';
377     console.log('setup for %s env(s) with %s mode', env, mode);
378   });
379
380 program
381   .command('exec <cmd>')
382   .alias('ex')
383   .description('execute the given remote cmd')
384   .option("-e, --exec_mode <mode>", "Which exec mode to use")
385   .action(function(cmd, options){
386     console.log('exec "%s" using %s mode', cmd, options.exec_mode);
387   }).on('--help', function() {
388     console.log('  Examples:');
389     console.log();
390     console.log('    $ deploy exec sequential');
391     console.log('    $ deploy exec async');
392     console.log();
393   });
394
395 program
396   .command('*')
397   .action(function(env){
398     console.log('deploying "%s"', env);
399   });
400
401 program.parse(process.argv);
402 ```
403
404 More Demos can be found in the [examples](https://github.com/tj/commander.js/tree/master/examples) directory.
405
406 ## License
407
408 MIT