Initial commit
[yaffs-website] / node_modules / yargs / README.md
1 yargs
2 ========
3
4 Yargs be a node.js library fer hearties tryin' ter parse optstrings.
5
6 With yargs, ye be havin' a map that leads straight to yer treasure! Treasure of course, being a simple option hash.
7
8 [![Build Status][travis-image]][travis-url]
9 [![Dependency Status][gemnasium-image]][gemnasium-url]
10 [![Coverage Status][coveralls-image]][coveralls-url]
11 [![NPM version][npm-image]][npm-url]
12 [![Windows Tests][windows-image]][windows-url]
13 [![js-standard-style][standard-image]][standard-url]
14 [![standard-version][standard-version-image]][standard-version-url]
15
16 > Yargs is the official successor to optimist. Please feel free to submit issues and pull requests. If you'd like to contribute and don't know where to start, have a look at [the issue list](https://github.com/yargs/yargs/issues) :)
17
18 examples
19 ========
20
21 With yargs, the options be just a hash!
22 -------------------------------------------------------------------
23
24 plunder.js:
25
26 ````javascript
27 #!/usr/bin/env node
28 var argv = require('yargs').argv;
29
30 if (argv.ships > 3 && argv.distance < 53.5) {
31     console.log('Plunder more riffiwobbles!');
32 } else {
33     console.log('Retreat from the xupptumblers!');
34 }
35 ````
36
37 ***
38
39     $ ./plunder.js --ships=4 --distance=22
40     Plunder more riffiwobbles!
41
42     $ ./plunder.js --ships 12 --distance 98.7
43     Retreat from the xupptumblers!
44
45 ![Joe was one optimistic pirate.](http://i.imgur.com/4WFGVJ9.png)
46
47 But don't walk the plank just yet! There be more! You can do short options:
48 -------------------------------------------------
49
50 short.js:
51
52 ````javascript
53 #!/usr/bin/env node
54 var argv = require('yargs').argv;
55 console.log('(%d,%d)', argv.x, argv.y);
56 ````
57
58 ***
59
60     $ ./short.js -x 10 -y 21
61     (10,21)
62
63 And booleans, both long, short, and even grouped:
64 ----------------------------------
65
66 bool.js:
67
68 ````javascript
69 #!/usr/bin/env node
70 var argv = require('yargs').argv;
71
72 if (argv.s) {
73     process.stdout.write(argv.fr ? 'Le perroquet dit: ' : 'The parrot says: ');
74 }
75 console.log(
76     (argv.fr ? 'couac' : 'squawk') + (argv.p ? '!' : '')
77 );
78 ````
79
80 ***
81
82     $ ./bool.js -s
83     The parrot says: squawk
84
85     $ ./bool.js -sp
86     The parrot says: squawk!
87
88     $ ./bool.js -sp --fr
89     Le perroquet dit: couac!
90
91 And non-hyphenated options too! Just use `argv._`!
92 -------------------------------------------------
93
94 nonopt.js:
95
96 ````javascript
97 #!/usr/bin/env node
98 var argv = require('yargs').argv;
99 console.log('(%d,%d)', argv.x, argv.y);
100 console.log(argv._);
101 ````
102
103 ***
104
105     $ ./nonopt.js -x 6.82 -y 3.35 rum
106     (6.82,3.35)
107     [ 'rum' ]
108
109     $ ./nonopt.js "me hearties" -x 0.54 yo -y 1.12 ho
110     (0.54,1.12)
111     [ 'me hearties', 'yo', 'ho' ]
112
113 Yargs even counts your booleans!
114 ----------------------------------------------------------------------
115
116 count.js:
117
118 ````javascript
119 #!/usr/bin/env node
120 var argv = require('yargs')
121     .count('verbose')
122     .alias('v', 'verbose')
123     .argv;
124
125 VERBOSE_LEVEL = argv.verbose;
126
127 function WARN()  { VERBOSE_LEVEL >= 0 && console.log.apply(console, arguments); }
128 function INFO()  { VERBOSE_LEVEL >= 1 && console.log.apply(console, arguments); }
129 function DEBUG() { VERBOSE_LEVEL >= 2 && console.log.apply(console, arguments); }
130
131 WARN("Showing only important stuff");
132 INFO("Showing semi-important stuff too");
133 DEBUG("Extra chatty mode");
134 ````
135
136 ***
137     $ node count.js
138     Showing only important stuff
139
140     $ node count.js -v
141     Showing only important stuff
142     Showing semi-important stuff too
143
144     $ node count.js -vv
145     Showing only important stuff
146     Showing semi-important stuff too
147     Extra chatty mode
148
149     $ node count.js -v --verbose
150     Showing only important stuff
151     Showing semi-important stuff too
152     Extra chatty mode
153
154 Tell users how to use yer options and make demands.
155 -------------------------------------------------
156
157 area.js:
158
159 ````javascript
160 #!/usr/bin/env node
161 var argv = require('yargs')
162     .usage('Usage: $0 -w [num] -h [num]')
163     .demand(['w','h'])
164     .argv;
165
166 console.log("The area is:", argv.w * argv.h);
167 ````
168
169 ***
170
171     $ ./area.js -w 55 -h 11
172     The area is: 605
173
174     $ node ./area.js -w 4.91 -w 2.51
175     Usage: area.js -w [num] -h [num]
176
177     Options:
178       -w  [required]
179       -h  [required]
180
181     Missing required arguments: h
182
183 After yer demands have been met, demand more! Ask for non-hyphenated arguments!
184 -----------------------------------------
185
186 demand_count.js:
187
188 ````javascript
189 #!/usr/bin/env node
190 var argv = require('yargs')
191     .demand(2)
192     .argv;
193 console.dir(argv);
194 ````
195
196 ***
197
198         $ ./demand_count.js a
199
200         Not enough non-option arguments: got 1, need at least 2
201
202         $ ./demand_count.js a b
203         { _: [ 'a', 'b' ], '$0': 'demand_count.js' }
204
205         $ ./demand_count.js a b c
206         { _: [ 'a', 'b', 'c' ], '$0': 'demand_count.js' }
207
208 EVEN MORE SHIVER ME TIMBERS!
209 ------------------
210
211 default_singles.js:
212
213 ````javascript
214 #!/usr/bin/env node
215 var argv = require('yargs')
216     .default('x', 10)
217     .default('y', 10)
218     .argv
219 ;
220 console.log(argv.x + argv.y);
221 ````
222
223 ***
224
225     $ ./default_singles.js -x 5
226     15
227
228 default_hash.js:
229
230 ````javascript
231 #!/usr/bin/env node
232 var argv = require('yargs')
233     .default({ x : 10, y : 10 })
234     .argv
235 ;
236 console.log(argv.x + argv.y);
237 ````
238
239 ***
240
241     $ ./default_hash.js -y 7
242     17
243
244 And if you really want to get all descriptive about it...
245 ---------------------------------------------------------
246
247 boolean_single.js:
248
249 ````javascript
250 #!/usr/bin/env node
251 var argv = require('yargs')
252     .boolean('v')
253     .argv
254 ;
255 console.dir(argv.v);
256 console.dir(argv._);
257 ````
258
259 ***
260
261     $ ./boolean_single.js -v "me hearties" yo ho
262     true
263     [ 'me hearties', 'yo', 'ho' ]
264
265
266 boolean_double.js:
267
268 ````javascript
269 #!/usr/bin/env node
270 var argv = require('yargs')
271     .boolean(['x','y','z'])
272     .argv
273 ;
274 console.dir([ argv.x, argv.y, argv.z ]);
275 console.dir(argv._);
276 ````
277
278 ***
279
280     $ ./boolean_double.js -x -z one two three
281     [ true, false, true ]
282     [ 'one', 'two', 'three' ]
283
284 Yargs is here to help you...
285 ---------------------------
286
287 Ye can describe parameters fer help messages and set aliases. Yargs figures
288 out how ter format a handy help string automatically.
289
290 line_count.js:
291
292 ````javascript
293 #!/usr/bin/env node
294 var argv = require('yargs')
295     .usage('Usage: $0 <command> [options]')
296     .command('count', 'Count the lines in a file')
297     .demand(1)
298     .example('$0 count -f foo.js', 'count the lines in the given file')
299     .demand('f')
300     .alias('f', 'file')
301     .nargs('f', 1)
302     .describe('f', 'Load a file')
303     .help('h')
304     .alias('h', 'help')
305     .epilog('copyright 2015')
306     .argv;
307
308 var fs = require('fs');
309 var s = fs.createReadStream(argv.file);
310
311 var lines = 0;
312 s.on('data', function (buf) {
313     lines += buf.toString().match(/\n/g).length;
314 });
315
316 s.on('end', function () {
317     console.log(lines);
318 });
319 ````
320
321 ***
322     $ node line_count.js count
323     Usage: line_count.js <command> [options]
324
325     Commands:
326       count    Count the lines in a file
327
328     Options:
329       -f, --file  Load a file        [required]
330       -h, --help  Show help           [boolean]
331
332     Examples:
333       line_count.js count -f foo.js  count the lines in the given file
334
335     copyright 2015
336
337     Missing required arguments: f
338
339     $ node line_count.js count --file line_count.js
340     26
341
342     $ node line_count.js count -f line_count.js
343     26
344
345 methods
346 =======
347
348 By itself,
349
350 ````javascript
351 require('yargs').argv
352 ````
353
354 will use the `process.argv` array to construct the `argv` object.
355
356 You can pass in the `process.argv` yourself:
357
358 ````javascript
359 require('yargs')([ '-x', '1', '-y', '2' ]).argv
360 ````
361
362 or use `.parse()` to do the same thing:
363
364 ````javascript
365 require('yargs').parse([ '-x', '1', '-y', '2' ])
366 ````
367
368 The rest of these methods below come in just before the terminating `.argv`.
369
370 <a name="alias"></a>.alias(key, alias)
371 ------------------
372
373 Set key names as equivalent such that updates to a key will propagate to aliases
374 and vice-versa.
375
376 Optionally `.alias()` can take an object that maps keys to aliases.
377 Each key of this object should be the canonical version of the option, and each
378 value should be a string or an array of strings.
379
380 .argv
381 -----
382
383 Get the arguments as a plain old object.
384
385 Arguments without a corresponding flag show up in the `argv._` array.
386
387 The script name or node command is available at `argv.$0` similarly to how `$0`
388 works in bash or perl.
389
390 If `yargs` is executed in an environment that embeds node and there's no script name (e.g.
391 [Electron](http://electron.atom.io/) or [nw.js](http://nwjs.io/)), it will ignore the first parameter since it
392 expects it to be the script name. In order to override this behavior, use `.parse(process.argv.slice(1))`
393 instead of `.argv` and the first parameter won't be ignored.
394
395 <a name="array"></a>.array(key)
396 ----------
397
398 Tell the parser to interpret `key` as an array. If `.array('foo')` is set,
399 `--foo foo bar` will be parsed as `['foo', 'bar']` rather than as `'foo'`.
400
401 <a name="boolean"></a>.boolean(key)
402 -------------
403
404 Interpret `key` as a boolean. If a non-flag option follows `key` in
405 `process.argv`, that string won't get set as the value of `key`.
406
407 `key` will default to `false`, unless a `default(key, undefined)` is
408 explicitly set.
409
410 If `key` is an array, interpret all the elements as booleans.
411
412 .check(fn)
413 ----------
414
415 Check that certain conditions are met in the provided arguments.
416
417 `fn` is called with two arguments, the parsed `argv` hash and an array of options and their aliases.
418
419 If `fn` throws or returns a non-truthy value, show the thrown error, usage information, and
420 exit.
421
422 <a name="choices"></a>.choices(key, choices)
423 ----------------------
424
425 Limit valid values for `key` to a predefined set of `choices`, given as an array
426 or as an individual value.
427
428 ```js
429 var argv = require('yargs')
430   .alias('i', 'ingredient')
431   .describe('i', 'choose your sandwich ingredients')
432   .choices('i', ['peanut-butter', 'jelly', 'banana', 'pickles'])
433   .help('help')
434   .argv
435 ```
436
437 If this method is called multiple times, all enumerated values will be merged
438 together. Choices are generally strings or numbers, and value matching is
439 case-sensitive.
440
441 Optionally `.choices()` can take an object that maps multiple keys to their
442 choices.
443
444 Choices can also be specified as `choices` in the object given to `option()`.
445
446 ```js
447 var argv = require('yargs')
448   .option('size', {
449     alias: 's',
450     describe: 'choose a size',
451     choices: ['xs', 's', 'm', 'l', 'xl']
452   })
453   .argv
454 ```
455
456 .command(cmd, desc, [builder], [handler])
457 -----------------------------------------
458 .command(cmd, desc, [module])
459 -----------------------------
460 .command(module)
461 ----------------
462
463 Document the commands exposed by your application.
464
465 Use `desc` to provide a description for each command your application accepts (the
466 values stored in `argv._`).  Set `desc` to `false` to create a hidden command.
467 Hidden commands don't show up in the help output and aren't available for
468 completion.
469
470 Optionally, you can provide a `builder` object to give hints about the
471 options that your command accepts:
472
473 ```js
474 yargs.command('get', 'make a get HTTP request', {
475     url: {
476       alias: 'u',
477       default: 'http://yargs.js.org/'
478     }
479   })
480   .help()
481   .argv
482 ```
483
484 Note that commands will not automatically inherit configuration _or_ options
485 of their parent context. This means you'll have to re-apply configuration
486 if necessary, and make options global manually using the [global](#global) method.
487
488 Additionally, the [`help`](#help) and [`version`](#version)
489 options (if used) **always** apply globally, just like the
490 [`.wrap()`](#wrap) configuration.
491
492 `builder` can also be a function. This function is executed
493 with a `yargs` instance, and can be used to provide _advanced_ command specific help:
494
495 ```js
496 yargs.command('get', 'make a get HTTP request', function (yargs) {
497     return yargs.option('url', {
498       alias: 'u',
499       default: 'http://yargs.js.org/'
500     })
501   })
502   .help()
503   .argv
504 ```
505
506 You can also provide a handler function, which will be executed with the
507 parsed `argv` object:
508
509 ```js
510 yargs
511   .command(
512     'get',
513     'make a get HTTP request',
514     function (yargs) {
515       return yargs.option('u', {
516         alias: 'url',
517         describe: 'the URL to make an HTTP request to'
518       })
519     },
520     function (argv) {
521       console.log(argv.url)
522     }
523   )
524   .help()
525   .argv
526 ```
527
528 ### Positional Arguments
529
530 Commands can accept _optional_ and _required_ positional arguments. Required
531 positional arguments take the form `<foo>`, and optional arguments
532 take the form `[bar]`. The parsed positional arguments will be populated in
533 `argv`:
534
535 ```js
536 yargs.command('get <source> [proxy]', 'make a get HTTP request')
537   .help()
538   .argv
539 ```
540
541 #### Variadic Positional Arguments
542
543 The last positional argument can optionally accept an array of
544 values, by using the `..` operator:
545
546 ```js
547 yargs.command('download <url> [files..]', 'download several files')
548   .help()
549   .argv
550 ```
551
552 ### Providing a Command Module
553
554 For complicated commands you can pull the logic into a module. A module
555 simply needs to export:
556
557 * `exports.command`: string that executes this command when given on the command line, may contain positional args
558 * `exports.describe`: string used as the description for the command in help text, use `false` for a hidden command
559 * `exports.builder`: object declaring the options the command accepts, or a function accepting and returning a yargs instance
560 * `exports.handler`: a function which will be passed the parsed argv.
561
562 ```js
563 // my-module.js
564 exports.command = 'get <source> [proxy]'
565
566 exports.describe = 'make a get HTTP request'
567
568 exports.builder = {
569   banana: {
570     default: 'cool'
571   },
572   batman: {
573     default: 'sad'
574   }
575 }
576
577 exports.handler = function (argv) {
578   // do something with argv.
579 }
580 ```
581
582 You then register the module like so:
583
584 ```js
585 yargs.command(require('my-module'))
586   .help()
587   .argv
588 ```
589
590 Or if the module does not export `command` and `describe` (or if you just want to override them):
591
592 ```js
593 yargs.command('get <source> [proxy]', 'make a get HTTP request', require('my-module'))
594   .help()
595   .argv
596 ```
597
598 .commandDir(directory, [opts])
599 ------------------------------
600
601 Apply command modules from a directory relative to the module calling this method.
602
603 This allows you to organize multiple commands into their own modules under a
604 single directory and apply all of them at once instead of calling
605 `.command(require('./dir/module'))` multiple times.
606
607 By default, it ignores subdirectories. This is so you can use a directory
608 structure to represent your command hierarchy, where each command applies its
609 subcommands using this method in its builder function. See the example below.
610
611 Note that yargs assumes all modules in the given directory are command modules
612 and will error if non-command modules are encountered. In this scenario, you
613 can either move your module to a different directory or use the `exclude` or
614 `visit` option to manually filter it out. More on that below.
615
616 `directory` is a relative directory path as a string (required).
617
618 `opts` is an options object (optional). The following options are valid:
619
620 - `recurse`: boolean, default `false`
621
622     Look for command modules in all subdirectories and apply them as a flattened
623     (non-hierarchical) list.
624
625 - `extensions`: array of strings, default `['js']`
626
627     The types of files to look for when requiring command modules.
628
629 - `visit`: function
630
631     A synchronous function called for each command module encountered. Accepts
632     `commandObject`, `pathToFile`, and `filename` as arguments. Returns
633     `commandObject` to include the command; any falsy value to exclude/skip it.
634
635 - `include`: RegExp or function
636
637     Whitelist certain modules. See [`require-directory` whitelisting](https://www.npmjs.com/package/require-directory#whitelisting) for details.
638
639 - `exclude`: RegExp or function
640
641     Blacklist certain modules. See [`require-directory` blacklisting](https://www.npmjs.com/package/require-directory#blacklisting) for details.
642
643 ### Example command hierarchy using `.commandDir()`
644
645 Desired CLI:
646
647 ```sh
648 $ myapp --help
649 $ myapp init
650 $ myapp remote --help
651 $ myapp remote add base http://yargs.js.org
652 $ myapp remote prune base
653 $ myapp remote prune base fork whatever
654 ```
655
656 Directory structure:
657
658 ```
659 myapp/
660 ├─ cli.js
661 └─ cmds/
662    â”œâ”€ init.js
663    â”œâ”€ remote.js
664    â””─ remote_cmds/
665       â”œâ”€ add.js
666       â””─ prune.js
667 ```
668
669 cli.js:
670
671 ```js
672 #!/usr/bin/env node
673 require('yargs')
674   .commandDir('cmds')
675   .demand(1)
676   .help()
677   .argv
678 ```
679
680 cmds/init.js:
681
682 ```js
683 exports.command = 'init [dir]'
684 exports.desc = 'Create an empty repo'
685 exports.builder = {
686   dir: {
687     default: '.'
688   }
689 }
690 exports.handler = function (argv) {
691   console.log('init called for dir', argv.dir)
692 }
693 ```
694
695 cmds/remote.js:
696
697 ```js
698 exports.command = 'remote <command>'
699 exports.desc = 'Manage set of tracked repos'
700 exports.builder = function (yargs) {
701   return yargs.commandDir('remote_cmds')
702 }
703 exports.handler = function (argv) {}
704 ```
705
706 cmds/remote_cmds/add.js:
707
708 ```js
709 exports.command = 'add <name> <url>'
710 exports.desc = 'Add remote named <name> for repo at url <url>'
711 exports.builder = {}
712 exports.handler = function (argv) {
713   console.log('adding remote %s at url %s', argv.name, argv.url)
714 }
715 ```
716
717 cmds/remote_cmds/prune.js:
718
719 ```js
720 exports.command = 'prune <name> [names..]'
721 exports.desc = 'Delete tracked branches gone stale for remotes'
722 exports.builder = {}
723 exports.handler = function (argv) {
724   console.log('pruning remotes %s', [].concat(argv.name).concat(argv.names).join(', '))
725 }
726 ```
727
728 .completion([cmd], [description], [fn])
729 ---------------------------------------
730
731 Enable bash-completion shortcuts for commands and options.
732
733 `cmd`: When present in `argv._`, will result in the `.bashrc` completion script
734 being outputted. To enable bash completions, concat the generated script to your
735 `.bashrc` or `.bash_profile`.
736
737 `description`: Provide a description in your usage instructions for the command
738 that generates bash completion scripts.
739
740 `fn`: Rather than relying on yargs' default completion functionality, which
741 shiver me timbers is pretty awesome, you can provide your own completion
742 method.
743
744 If invoked without parameters, `.completion()` will make `completion` the command to output
745 the completion script.
746
747 ```js
748 var argv = require('yargs')
749   .completion('completion', function(current, argv) {
750     // 'current' is the current command being completed.
751     // 'argv' is the parsed arguments so far.
752     // simply return an array of completions.
753     return [
754       'foo',
755       'bar'
756     ];
757   })
758   .argv;
759 ```
760
761 You can also provide asynchronous completions.
762
763 ```js
764 var argv = require('yargs')
765   .completion('completion', function(current, argv, done) {
766     setTimeout(function() {
767       done([
768         'apple',
769         'banana'
770       ]);
771     }, 500);
772   })
773   .argv;
774 ```
775
776 But wait, there's more! You can return an asynchronous promise.
777
778 ```js
779 var argv = require('yargs')
780   .completion('completion', function(current, argv, done) {
781     return new Promise(function (resolve, reject) {
782       setTimeout(function () {
783         resolve(['apple', 'banana'])
784       }, 10)
785     })
786   })
787   .argv;
788 ```
789
790 <a name="config"></a>.config([key], [description], [parseFn])
791 -------------------------------------------------------------
792 .config(object)
793 ---------------
794
795 Tells the parser that if the option specified by `key` is passed in, it
796 should be interpreted as a path to a JSON config file. The file is loaded
797 and parsed, and its properties are set as arguments.
798
799 If invoked without parameters, `.config()` will make `--config` the option to pass the JSON config file.
800
801 An optional `description` can be provided to customize the config (`key`) option
802 in the usage string.
803
804 An optional `parseFn` can be used to provide a custom parser. The parsing
805 function must be synchronous, and should return an object containing
806 key value pairs or an error.
807
808 ```js
809 var argv = require('yargs')
810   .config('settings', function (configPath) {
811     return JSON.parse(fs.readFileSync(configPath, 'utf-8'))
812   })
813   .argv
814 ```
815
816 You can also pass an explicit configuration `object`, it will be parsed
817 and its properties will be set as arguments.
818
819 ```js
820 var argv = require('yargs')
821   .config({foo: 1, bar: 2})
822   .argv
823 console.log(argv)
824 ```
825
826 ```
827 $ node test.js
828 { _: [],
829   foo: 1,
830   bar: 2,
831   '$0': 'test.js' }
832 ```
833
834 <a name="count"></a>.count(key)
835 ------------
836
837 Interpret `key` as a boolean flag, but set its parsed value to the number of
838 flag occurrences rather than `true` or `false`. Default value is thus `0`.
839
840 <a name="default"></a>.default(key, value, [description])
841 ---------------------------------------------------------
842 .defaults(key, value, [description])
843 ------------------------------------
844
845 **Note:** The `.defaults()` alias is deprecated. It will be
846 removed in the next major version.
847
848 Set `argv[key]` to `value` if no option was specified in `process.argv`.
849
850 Optionally `.default()` can take an object that maps keys to default values.
851
852 But wait, there's more! The default value can be a `function` which returns
853 a value. The name of the function will be used in the usage string:
854
855 ```js
856 var argv = require('yargs')
857   .default('random', function randomValue() {
858     return Math.random() * 256;
859   }).argv;
860 ```
861
862 Optionally, `description` can also be provided and will take precedence over
863 displaying the value in the usage instructions:
864
865 ```js
866 .default('timeout', 60000, '(one-minute)')
867 ```
868
869 <a name="demand"></a>.demand(key, [msg | boolean])
870 ------------------------------
871 .demand(count, [max], [msg])
872 ------------------------------
873
874 If `key` is a string, show the usage information and exit if `key` wasn't
875 specified in `process.argv`.
876
877 If `key` is a number, demand at least as many non-option arguments, which show
878 up in `argv._`. A second number can also optionally be provided, which indicates
879 the maximum number of non-option arguments.
880
881 If `key` is an array, demand each element.
882
883 If a `msg` string is given, it will be printed when the argument is missing,
884 instead of the standard error message. This is especially helpful for the non-option arguments in `argv._`.
885
886 If a `boolean` value is given, it controls whether the option is demanded;
887 this is useful when using `.options()` to specify command line parameters.
888
889 A combination of `.demand(1)` and `.strict()` will allow you to require a user to pass at least one command:
890
891 ```js
892 var argv = require('yargs')
893   .command('install', 'tis a mighty fine package to install')
894   .demand(1)
895   .strict()
896   .argv
897 ```
898
899 Similarly, you can require a command and arguments at the same time:
900
901 ```js
902 var argv = require('yargs')
903   .command('install', 'tis a mighty fine package to install')
904   .demand(1, ['w', 'm'])
905   .strict()
906   .argv
907 ```
908
909 <a name="describe"></a>.describe(key, desc)
910 --------------------
911
912 Describe a `key` for the generated usage information.
913
914 Optionally `.describe()` can take an object that maps keys to descriptions.
915
916 .detectLocale(boolean)
917 -----------
918
919 Should yargs attempt to detect the os' locale? Defaults to `true`.
920
921 .env([prefix])
922 --------------
923
924 Tell yargs to parse environment variables matching the given prefix and apply
925 them to argv as though they were command line arguments.
926
927 Use the "__" separator in the environment variable to indicate nested options.
928 (e.g. prefix_nested__foo => nested.foo)
929
930 If this method is called with no argument or with an empty string or with `true`,
931 then all env vars will be applied to argv.
932
933 Program arguments are defined in this order of precedence:
934
935 1. Command line args
936 2. Config file
937 3. Env var
938 4. Configured defaults
939
940 ```js
941 var argv = require('yargs')
942   .env('MY_PROGRAM')
943   .option('f', {
944     alias: 'fruit-thing',
945     default: 'apple'
946   })
947   .argv
948 console.log(argv)
949 ```
950
951 ```
952 $ node fruity.js
953 { _: [],
954   f: 'apple',
955   'fruit-thing': 'apple',
956   fruitThing: 'apple',
957   '$0': 'fruity.js' }
958 ```
959
960 ```
961 $ MY_PROGRAM_FRUIT_THING=banana node fruity.js
962 { _: [],
963   fruitThing: 'banana',
964   f: 'banana',
965   'fruit-thing': 'banana',
966   '$0': 'fruity.js' }
967 ```
968
969 ```
970 $ MY_PROGRAM_FRUIT_THING=banana node fruity.js -f cat
971 { _: [],
972   f: 'cat',
973   'fruit-thing': 'cat',
974   fruitThing: 'cat',
975   '$0': 'fruity.js' }
976 ```
977
978 Env var parsing is disabled by default, but you can also explicitly disable it
979 by calling `.env(false)`, e.g. if you need to undo previous configuration.
980
981 .epilog(str)
982 ------------
983 .epilogue(str)
984 --------------
985
986 A message to print at the end of the usage instructions, e.g.
987
988 ```js
989 var argv = require('yargs')
990   .epilogue('for more information, find our manual at http://example.com');
991 ```
992
993 .example(cmd, desc)
994 -------------------
995
996 Give some example invocations of your program. Inside `cmd`, the string
997 `$0` will get interpolated to the current script name or node command for the
998 present script similar to how `$0` works in bash or perl.
999 Examples will be printed out as part of the help message.
1000
1001 .exitProcess(enable)
1002 ----------------------------------
1003
1004 By default, yargs exits the process when the user passes a help flag, uses the
1005 `.version` functionality, or when validation fails. Calling
1006 `.exitProcess(false)` disables this behavior, enabling further actions after
1007 yargs have been validated.
1008
1009 .fail(fn)
1010 ---------
1011
1012 Method to execute when a failure occurs, rather than printing the failure message.
1013
1014 `fn` is called with the failure message that would have been printed and the
1015 `Error` instance originally thrown, if any.
1016
1017 ```js
1018 var argv = require('yargs')
1019   .fail(function (msg, err) {
1020     if (err) throw err // preserve stack
1021     console.error('You broke it!')
1022     console.error(msg)
1023     process.exit(1)
1024   })
1025   .argv
1026 ```
1027
1028 .getCompletion(args, done);
1029 ---------------------------
1030
1031 Allows to programmatically get completion choices for any line.
1032
1033 `args`: An array of the words in the command line to complete.
1034
1035 `done`: The callback to be called with the resulting completions.
1036
1037 For example:
1038
1039 ```js
1040 require('yargs')
1041   .option('foobar', {})
1042   .option('foobaz', {})
1043   .completion()
1044   .getCompletion(['./test.js', '--foo'], function (completions) {
1045     console.log(completions)
1046   })
1047 ```
1048
1049 Outputs the same completion choices as `./test.js --foo`<kbd>TAB</kbd>: `--foobar` and `--foobaz`
1050
1051 <a name="global"></a>.global(globals)
1052 ------------
1053
1054 Indicate that an option (or group of options) should not be reset when a command
1055 is executed, as an example:
1056
1057 ```js
1058 var argv = require('yargs')
1059   .option('a', {
1060     alias: 'all',
1061     default: true
1062   })
1063   .option('n', {
1064     alias: 'none',
1065     default: true
1066   })
1067   .command('foo', 'foo command', function (yargs) {
1068     return yargs.option('b', {
1069       alias: 'bar'
1070     })
1071   })
1072   .help('help')
1073   .global('a')
1074   .argv
1075 ```
1076
1077 If the `foo` command is executed the `all` option will remain, but the `none`
1078 option will have been eliminated.
1079
1080 `help`, `version`, and `completion` options default to being global.
1081
1082 <a name="group"></a>.group(key(s), groupName)
1083 --------------------
1084
1085 Given a key, or an array of keys, places options under an alternative heading
1086 when displaying usage instructions, e.g.,
1087
1088 ```js
1089 var yargs = require('yargs')(['--help'])
1090   .help()
1091   .group('batman', 'Heroes:')
1092   .describe('batman', "world's greatest detective")
1093   .wrap(null)
1094   .argv
1095 ```
1096 ***
1097     Heroes:
1098       --batman  world's greatest detective
1099
1100     Options:
1101       --help  Show help  [boolean]
1102
1103 <a name="help"></a>.help([option, [description]])
1104 ------------------------------
1105
1106 Add an option (e.g. `--help`) that displays the usage string and exits the
1107 process. If present, the `description` parameter customizes the description of
1108 the help option in the usage string.
1109
1110 If invoked without parameters, `.help()` will make `--help` the option to trigger
1111 help output.
1112
1113 Example:
1114
1115 ```js
1116 var yargs = require("yargs")(['--help'])
1117   .usage("$0 -operand1 number -operand2 number -operation [add|subtract]")
1118   .help()
1119   .argv
1120 ```
1121
1122 Later on, `argv` can be retrieved with `yargs.argv`.
1123
1124 .implies(x, y)
1125 --------------
1126
1127 Given the key `x` is set, it is required that the key `y` is set.
1128
1129 Optionally `.implies()` can accept an object specifying multiple implications.
1130
1131 .locale()
1132 ---------
1133
1134 Return the locale that yargs is currently using.
1135
1136 By default, yargs will auto-detect the operating system's locale so that
1137 yargs-generated help content will display in the user's language.
1138
1139 To override this behavior with a static locale, pass the desired locale as a
1140 string to this method (see below).
1141
1142 .locale(locale)
1143 ---------------
1144
1145 Override the auto-detected locale from the user's operating system with a static
1146 locale. Note that the OS locale can be modified by setting/exporting the `LC_ALL`
1147 environment variable.
1148
1149 ```js
1150 var argv = require('yargs')
1151   .usage('./$0 - follow ye instructions true')
1152   .option('option', {
1153     alias: 'o',
1154     describe: "'tis a mighty fine option",
1155     demand: true
1156   })
1157   .command('run', "Arrr, ya best be knowin' what yer doin'")
1158   .example('$0 run foo', "shiver me timbers, here's an example for ye")
1159   .help('help')
1160   .wrap(70)
1161   .locale('pirate')
1162   .argv
1163 ```
1164
1165 ***
1166
1167 ```shell
1168 ./test.js - follow ye instructions true
1169
1170 Choose yer command:
1171   run  Arrr, ya best be knowin' what yer doin'
1172
1173 Options for me hearties!
1174   --option, -o  'tis a mighty fine option               [requi-yar-ed]
1175   --help        Parlay this here code of conduct             [boolean]
1176
1177 Ex. marks the spot:
1178   test.js run foo  shiver me timbers, here's an example for ye
1179
1180 Ye be havin' to set the followin' argument land lubber: option
1181 ```
1182
1183 Locales currently supported:
1184
1185 * **de:** German.
1186 * **en:** American English.
1187 * **es:** Spanish.
1188 * **fr:** French.
1189 * **id:** Indonesian.
1190 * **it:** Italian.
1191 * **ja:** Japanese.
1192 * **ko:** Korean.
1193 * **nb:** Norwegian BokmÃ¥l.
1194 * **pirate:** American Pirate.
1195 * **pl:** Polish.
1196 * **pt:** Portuguese.
1197 * **pt_BR:** Brazilian Portuguese.
1198 * **tr:** Turkish.
1199 * **zh:** Chinese.
1200
1201 To submit a new translation for yargs:
1202
1203 1. use `./locales/en.json` as a starting point.
1204 2. submit a pull request with the new locale file.
1205
1206 *The [Microsoft Terminology Search](http://www.microsoft.com/Language/en-US/Search.aspx) can be useful for finding the correct terminology in your locale.*
1207
1208 <a name="nargs"></a>.nargs(key, count)
1209 -----------
1210
1211 The number of arguments that should be consumed after a key. This can be a
1212 useful hint to prevent parsing ambiguity. For example:
1213
1214 ```js
1215 var argv = require('yargs')
1216   .nargs('token', 1)
1217   .parse(['--token', '-my-token']);
1218 ```
1219
1220 parses as:
1221
1222 `{ _: [], token: '-my-token', '$0': 'node test' }`
1223
1224 Optionally `.nargs()` can take an object of `key`/`narg` pairs.
1225
1226 <a name="normalize"></a>.normalize(key)
1227 ---------------
1228
1229 The key provided represents a path and should have `path.normalize()` applied.
1230
1231 <a name="number"></a>.number(key)
1232 ------------
1233
1234 Tell the parser to always interpret `key` as a number.
1235
1236 If `key` is an array, all elements will be parsed as numbers.
1237
1238 If the option is given on the command line without a value, `argv` will be
1239 populated with `undefined`.
1240
1241 If the value given on the command line cannot be parsed as a number, `argv` will
1242 be populated with `NaN`.
1243
1244 Note that decimals, hexadecimals, and scientific notation are all accepted.
1245
1246 ```js
1247 var argv = require('yargs')
1248   .number('n')
1249   .number(['width', 'height'])
1250   .argv
1251 ```
1252
1253 .option(key, opt)
1254 -----------------
1255 .options(key, opt)
1256 ------------------
1257
1258 Instead of chaining together `.alias().demand().default().describe().string()`, you can specify
1259 keys in `opt` for each of the chainable methods.
1260
1261 For example:
1262
1263 ````javascript
1264 var argv = require('yargs')
1265     .option('f', {
1266         alias: 'file',
1267         demand: true,
1268         default: '/etc/passwd',
1269         describe: 'x marks the spot',
1270         type: 'string'
1271     })
1272     .argv
1273 ;
1274 ````
1275
1276 is the same as
1277
1278 ````javascript
1279 var argv = require('yargs')
1280     .alias('f', 'file')
1281     .demand('f')
1282     .default('f', '/etc/passwd')
1283     .describe('f', 'x marks the spot')
1284     .string('f')
1285     .argv
1286 ;
1287 ````
1288
1289 Optionally `.options()` can take an object that maps keys to `opt` parameters.
1290
1291 ````javascript
1292 var argv = require('yargs')
1293     .options({
1294       'f': {
1295         alias: 'file',
1296         demand: true,
1297         default: '/etc/passwd',
1298         describe: 'x marks the spot',
1299         type: 'string'
1300       }
1301     })
1302     .argv
1303 ;
1304 ````
1305
1306 Valid `opt` keys include:
1307
1308 - `alias`: string or array of strings, alias(es) for the canonical option key, see [`alias()`](#alias)
1309 - `array`: boolean, interpret option as an array, see [`array()`](#array)
1310 - `boolean`: boolean, interpret option as a boolean flag, see [`boolean()`](#boolean)
1311 - `choices`: value or array of values, limit valid option arguments to a predefined set, see [`choices()`](#choices)
1312 - `config`: boolean, interpret option as a path to a JSON config file, see [`config()`](#config)
1313 - `configParser`: function, provide a custom config parsing function, see [`config()`](#config)
1314 - `count`: boolean, interpret option as a count of boolean flags, see [`count()`](#count)
1315 - `default`: value, set a default value for the option, see [`default()`](#default)
1316 - `defaultDescription`: string, use this description for the default value in help content, see [`default()`](#default)
1317 - `demand`/`require`/`required`: boolean or string, demand the option be given, with optional error message, see [`demand()`](#demand)
1318 - `desc`/`describe`/`description`: string, the option description for help content, see [`describe()`](#describe)
1319 - `global`: boolean, indicate that this key should not be [reset](#reset) when a command is invoked, see [`global()`](#global)
1320 - `group`: string, when displaying usage instructions place the option under an alternative group heading, see [`group()`](#group)
1321 - `nargs`: number, specify how many arguments should be consumed for the option, see [`nargs()`](#nargs)
1322 - `normalize`: boolean, apply `path.normalize()` to the option, see [`normalize()`](#normalize)
1323 - `number`: boolean, interpret option as a number, [`number()`](#number)
1324 - `requiresArg`: boolean, require the option be specified with a value, see [`requiresArg()`](#requiresArg)
1325 - `skipValidation`: boolean, skips validation if the option is present, see [`skipValidation()`](#skipValidation)
1326 - `string`: boolean, interpret option as a string, see [`string()`](#string)
1327 - `type`: one of the following strings
1328     - `'array'`: synonymous for `array: true`, see [`array()`](#array)
1329     - `'boolean'`: synonymous for `boolean: true`, see [`boolean()`](#boolean)
1330     - `'count'`: synonymous for `count: true`, see [`count()`](#count)
1331     - `'number'`: synonymous for `number: true`, see [`number()`](#number)
1332     - `'string'`: synonymous for `string: true`, see [`string()`](#string)
1333
1334 .parse(args)
1335 ------------
1336
1337 Parse `args` instead of `process.argv`. Returns the `argv` object.
1338
1339 `args` may either be a pre-processed argv array, or a raw argument string.
1340
1341 .pkgConf(key, [cwd])
1342 ------------
1343
1344 Similar to [`config()`](#config), indicates that yargs should interpret the object from the specified key in package.json
1345 as a configuration object.
1346
1347 `cwd` can optionally be provided, the package.json will be read
1348 from this location.
1349
1350 .require(key, [msg | boolean])
1351 ------------------------------
1352 .required(key, [msg | boolean])
1353 ------------------------------
1354
1355 An alias for [`demand()`](#demand). See docs there.
1356
1357 <a name="requiresArg"></a>.requiresArg(key)
1358 -----------------
1359
1360 Specifies either a single option key (string), or an array of options that
1361 must be followed by option values. If any option value is missing, show the
1362 usage information and exit.
1363
1364 The default behavior is to set the value of any key not followed by an
1365 option value to `true`.
1366
1367 <a name="reset"></a>.reset()
1368 --------
1369
1370 Reset the argument object built up so far. This is useful for
1371 creating nested command line interfaces. Use [global](#global)
1372 to specify keys that should not be reset.
1373
1374 ```js
1375 var yargs = require('yargs')
1376   .usage('$0 command')
1377   .command('hello', 'hello command')
1378   .command('world', 'world command')
1379   .demand(1, 'must provide a valid command'),
1380   argv = yargs.argv,
1381   command = argv._[0];
1382
1383 if (command === 'hello') {
1384   yargs.reset()
1385     .usage('$0 hello')
1386     .help('h')
1387     .example('$0 hello', 'print the hello message!')
1388     .argv
1389
1390   console.log('hello!');
1391 } else if (command === 'world'){
1392   yargs.reset()
1393     .usage('$0 world')
1394     .help('h')
1395     .example('$0 world', 'print the world message!')
1396     .argv
1397
1398   console.log('world!');
1399 } else {
1400   yargs.showHelp();
1401 }
1402 ```
1403
1404 .showCompletionScript()
1405 ----------------------
1406
1407 Generate a bash completion script. Users of your application can install this
1408 script in their `.bashrc`, and yargs will provide completion shortcuts for
1409 commands and options.
1410
1411 .showHelp(consoleLevel='error')
1412 ---------------------------
1413
1414 Print the usage data using the [`console`](https://nodejs.org/api/console.html) function `consoleLevel` for printing.
1415
1416 Example:
1417
1418 ```js
1419 var yargs = require("yargs")
1420   .usage("$0 -operand1 number -operand2 number -operation [add|subtract]");
1421 yargs.showHelp(); //prints to stderr using console.error()
1422 ```
1423
1424 Or, to print the usage data to `stdout` instead, you can specify the use of `console.log`:
1425
1426 ```js
1427 yargs.showHelp("log"); //prints to stdout using console.log()
1428 ```
1429
1430 Later on, `argv` can be retrieved with `yargs.argv`.
1431
1432 .showHelpOnFail(enable, [message])
1433 ----------------------------------
1434
1435 By default, yargs outputs a usage string if any error is detected. Use the
1436 `.showHelpOnFail()` method to customize this behavior. If `enable` is `false`,
1437 the usage string is not output. If the `message` parameter is present, this
1438 message is output after the error message.
1439
1440 line_count.js:
1441
1442 ````javascript
1443 #!/usr/bin/env node
1444 var argv = require('yargs')
1445     .usage('Count the lines in a file.\nUsage: $0 -f <file>')
1446     .demand('f')
1447     .alias('f', 'file')
1448     .describe('f', 'Load a file')
1449     .string('f')
1450     .showHelpOnFail(false, 'Specify --help for available options')
1451     .help('help')
1452     .argv;
1453
1454 // etc.
1455 ````
1456
1457 ***
1458
1459 ```
1460 $ node line_count.js
1461 Missing argument value: f
1462
1463 Specify --help for available options
1464 ```
1465
1466 <a name="skipValidation"></a>.skipValidation(key)
1467 -----------------
1468
1469 Specifies either a single option key (string), or an array of options.
1470 If any of the options is present, yargs validation is skipped.
1471
1472 .strict()
1473 ---------
1474
1475 Any command-line argument given that is not demanded, or does not have a
1476 corresponding description, will be reported as an error.
1477
1478 <a name="string"></a>.string(key)
1479 ------------
1480
1481 Tell the parser logic not to interpret `key` as a number or boolean.
1482 This can be useful if you need to preserve leading zeros in an input.
1483
1484 If `key` is an array, interpret all the elements as strings.
1485
1486 `.string('_')` will result in non-hyphenated arguments being interpreted as strings,
1487 regardless of whether they resemble numbers.
1488
1489 .updateLocale(obj)
1490 ------------------
1491 .updateStrings(obj)
1492 ------------------
1493
1494 Override the default strings used by yargs with the key/value
1495 pairs provided in `obj`:
1496
1497 ```js
1498 var argv = require('yargs')
1499   .command('run', 'the run command')
1500   .help('help')
1501   .updateStrings({
1502     'Commands:': 'My Commands -->\n'
1503   })
1504   .wrap(null)
1505   .argv
1506 ```
1507
1508 ***
1509
1510 ```shell
1511 My Commands -->
1512
1513   run  the run command
1514
1515 Options:
1516   --help  Show help  [boolean]
1517 ```
1518
1519 If you explicitly specify a `locale()`, you should do so *before* calling
1520 `updateStrings()`.
1521
1522 .usage(message, [opts])
1523 ---------------------
1524
1525 Set a usage message to show which commands to use. Inside `message`, the string
1526 `$0` will get interpolated to the current script name or node command for the
1527 present script similar to how `$0` works in bash or perl.
1528
1529 `opts` is optional and acts like calling `.options(opts)`.
1530
1531 <a name="version"></a>.version([option], [description], [version])
1532 ----------------------------------------
1533
1534 Add an option (e.g. `--version`) that displays the version number (given by the
1535 `version` parameter) and exits the process.
1536
1537 If no arguments are passed to `version` (`.version()`), yargs will parse the `package.json`
1538 of your module and use its `version` value. The default value of `option` is `--version`.
1539
1540 You can provide a `function` for version, rather than a string.
1541 This is useful if you want to use a version stored in a location other than package.json:
1542
1543 ```js
1544 var argv = require('yargs')
1545   .version(function() {
1546     return require('../lib/version').version;
1547   })
1548   .argv;
1549 ```
1550
1551 <a name="wrap"></a>.wrap(columns)
1552 --------------
1553
1554 Format usage output to wrap at `columns` many columns.
1555
1556 By default wrap will be set to `Math.min(80, windowWidth)`. Use `.wrap(null)` to
1557 specify no column limit (no right-align). Use `.wrap(yargs.terminalWidth())` to
1558 maximize the width of yargs' usage instructions.
1559
1560 parsing tricks
1561 ==============
1562
1563 stop parsing
1564 ------------
1565
1566 Use `--` to stop parsing flags and stuff the remainder into `argv._`.
1567
1568     $ node examples/reflect.js -a 1 -b 2 -- -c 3 -d 4
1569     { _: [ '-c', '3', '-d', '4' ],
1570       a: 1,
1571       b: 2,
1572       '$0': 'examples/reflect.js' }
1573
1574 negate fields
1575 -------------
1576
1577 If you want to explicitly set a field to false instead of just leaving it
1578 undefined or to override a default you can do `--no-key`.
1579
1580     $ node examples/reflect.js -a --no-b
1581     { _: [], a: true, b: false, '$0': 'examples/reflect.js' }
1582
1583 numbers
1584 -------
1585
1586 Every argument that looks like a number (`!isNaN(Number(arg))`) is converted to
1587 one. This way you can just `net.createConnection(argv.port)` and you can add
1588 numbers out of `argv` with `+` without having that mean concatenation,
1589 which is super frustrating.
1590
1591 duplicates
1592 ----------
1593
1594 If you specify a flag multiple times it will get turned into an array containing
1595 all the values in order.
1596
1597     $ node examples/reflect.js -x 5 -x 8 -x 0
1598     { _: [], x: [ 5, 8, 0 ], '$0': 'examples/reflect.js' }
1599
1600 dot notation
1601 ------------
1602
1603 When you use dots (`.`s) in argument names, an implicit object path is assumed.
1604 This lets you organize arguments into nested objects.
1605
1606     $ node examples/reflect.js --foo.bar.baz=33 --foo.quux=5
1607     { _: [],
1608       foo: { bar: { baz: 33 }, quux: 5 },
1609       '$0': 'examples/reflect.js' }
1610
1611 short numbers
1612 -------------
1613
1614 Short numeric `-n5` style arguments work too:
1615
1616     $ node examples/reflect.js -n123 -m456
1617     { _: [], n: 123, m: 456, '$0': 'examples/reflect.js' }
1618
1619 installation
1620 ============
1621
1622 With [npm](https://github.com/npm/npm), just do:
1623
1624     npm install yargs
1625
1626 or clone this project on github:
1627
1628     git clone http://github.com/yargs/yargs.git
1629
1630 To run the tests with npm, just do:
1631
1632     npm test
1633
1634 configuration
1635 =============
1636
1637 Using the `yargs` stanza in your `package.json` you can turn on and off
1638 some of yargs' parsing features:
1639
1640 ```json
1641 {
1642   "yargs": {
1643     "short-option-groups": true,
1644     "camel-case-expansion": true,
1645     "dot-notation": true,
1646     "parse-numbers": true,
1647     "boolean-negation": true
1648   }
1649 }
1650 ```
1651
1652 See the [yargs-parser](https://github.com/yargs/yargs-parser#configuration) module
1653 for detailed documentation of this feature.
1654
1655 inspired by
1656 ===========
1657
1658 This module is loosely inspired by Perl's
1659 [Getopt::Casual](http://search.cpan.org/~photo/Getopt-Casual-0.13.1/Casual.pm).
1660
1661 [travis-url]: https://travis-ci.org/yargs/yargs
1662 [travis-image]: https://img.shields.io/travis/yargs/yargs/master.svg
1663 [gemnasium-url]: https://gemnasium.com/yargs/yargs
1664 [gemnasium-image]: https://img.shields.io/gemnasium/yargs/yargs.svg
1665 [coveralls-url]: https://coveralls.io/github/yargs/yargs
1666 [coveralls-image]: https://img.shields.io/coveralls/yargs/yargs.svg
1667 [npm-url]: https://www.npmjs.com/package/yargs
1668 [npm-image]: https://img.shields.io/npm/v/yargs.svg
1669 [windows-url]: https://ci.appveyor.com/project/bcoe/yargs-ljwvf
1670 [windows-image]: https://img.shields.io/appveyor/ci/bcoe/yargs-ljwvf/master.svg?label=Windows%20Tests
1671 [standard-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg
1672 [standard-url]: http://standardjs.com/
1673 [standard-version-image]: https://img.shields.io/badge/release-standard%20version-brightgreen.svg
1674 [standard-version-url]: https://github.com/conventional-changelog/standard-version