├── .npmignore
├── .travis.yml
├── CHANGES
├── LICENSE
├── README.md
├── examples
├── abbreviations.js
├── aliases.js
├── arguments.js
├── commands.js
├── custom-usages.js
├── events.js
├── fully-descriptive-help.js
├── help-usage-version.js
├── internal-data.js
├── mkdir.js
├── modifying-builtin-options.js
├── no-configuration.js
├── npm
│ ├── config.js
│ ├── install.js
│ ├── npm.js
│ └── whoami.js
├── options.js
├── read-package.js
└── to-upper-case.js
├── lib
├── argp.js
├── body.js
├── command.js
├── index.js
└── wrap.js
├── package.json
└── test
└── index.js
/.npmignore:
--------------------------------------------------------------------------------
1 | CHANGES
2 | examples
3 | test
4 | .npmignore
5 | .travis.yml
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: node_js
2 | node_js:
3 | - "0.11"
4 | - "0.10"
--------------------------------------------------------------------------------
/CHANGES:
--------------------------------------------------------------------------------
1 | v1.0.4 (31 Mar 2014)
2 | Fixed "text()" function with an empty string.
3 |
4 | v1.0.3 (19 Feb 2014)
5 | Bump version.
6 |
7 | v1.0.2 (17 Feb 2014)
8 | Added an "options" paramter to "readPackage()". The email, description and
9 | version found in the package.json can be ignored individually.
10 |
11 | v1.0.1 (21 Dec 2013)
12 | "printHelp()", "printUsage()" and "printVersion()" now exits correctly by
13 | default with code 0.
14 | When "argv()" is called with an input array, "printHelp()", "printUsage()" and
15 | "printVersion()" don't terminate the process.
16 |
17 | v1.0.0 (02 Dec 2013)
18 | Added support for multiple parsers. Now the parser is created using
19 | "createParser()".
20 | In previous versions, passing an array to "argv()" didn't uncache the module
21 | in order to reuse the parser. Now if you don't need to reuse it, pass an
22 | object { once: true } to "createParser()".
23 | Added an "error" event.
24 | Added "footer()". Now you can write text between the --version and email text
25 | lines when using the "readPackage()" function.
26 | When "argv()" was called with an input array from inside a Body or Command
27 | instance, the input array was not read.
28 | Removed the second parameter from the "end" event. Now the functions
29 | "printHelp()", "printUsage()" and "printVersion()" are accessible from the
30 | Argp instance.
31 | Minor bugfixes and improvements.
32 |
33 | v0.2.1 (25 Nov 2013)
34 | The "fail()" function from the "end" event now prints the string message
35 | correctly.
36 |
37 | v0.2.0 (25 Nov 2013)
38 | The "end" event now receives a second parameter with an object with the
39 | previous functions "printHelp()", "printUsage()", "printVersion()" and
40 | "fail()".
41 | Improved README.
42 | Added Travis integration.
43 | Some bugfixes.
44 |
45 | v0.1.3 (25 Oct 2013)
46 | Added a fifth parameter ("fail") to the "end" event.
47 | Minor improvements and bugfixes.
48 |
49 | v0.1.2 (04 Oct 2013)
50 | Minor speed improvements and bugfixes.
51 |
52 | v0.1.1 (30 Sep 2013)
53 | An array with options can be passed to "argv()".
54 |
55 | v0.1.0 (29 Sep 2013)
56 | Bump version.
57 |
58 | v0.0.16 (28 Sep 2013)
59 | Added a new parameter to "help()" and "version()" to disable the short option.
60 | Added "exitStatus()".
61 |
62 | v0.0.15 (27 Sep 2013)
63 | Renamed "help" to "synopsis", property of "argument()".
64 | Renamed "argument" to "metavar", property of "option()".
65 | Minor improvements.
66 |
67 | v0.0.14 (26 Sep 2013)
68 | Added "command()", "main()" and "argv()" to the Body instance.
69 | Removed "end()".
70 |
71 | v0.0.13 (26 Sep 2013)
72 | Removed "line()", "paragraph()", "group()".
73 | Added "text()".
74 |
75 | v0.0.12 (26 Sep 2013)
76 | Minor bugfixes.
77 |
78 | v0.0.11 (25 Sep 2013)
79 | Added commands ("trailing" and "help" properties to "argument()").
80 | The "end" event now receives 3 new parameters: "printHelp()", "printUsage()"
81 | and "printVersion()".
82 | Removed "_debug" and "_filename" properties from the final object.
83 | Minor improvements.
84 |
85 | v0.0.10 (23 Sep 2013)
86 | The default value of an option is now set with "default" instead of "value".
87 | Code inside the "end" event was preventing the parser from being gc'ed.
88 | Allowed negated flags with a short name.
89 | Added aliases.
90 | Added choices.
91 | Improved --usage message.
92 | Minor improvements.
93 |
94 | v0.0.9 (20 Sep 2013)
95 | Added "columns()".
96 | Minor bugfixes.
97 |
98 | v0.0.8 (19 Sep 2013)
99 | Fixed "readPackage()" with a missing default file.
100 | Added "prefix" parameter to the "text()" function.
101 | "usages()" now replaces the whole "usage" string.
102 | Added "line()" function. It differs from "text()" in that it isn't a new
103 | paragraph.
104 | Renamed "text()" to "paragraph()".
105 | Added "filter" parameter to "options()".
106 | Minor improvements.
107 |
108 | v0.0.7 (18 Sep 2013)
109 | The api has been refactored to be more fluent.
110 | Some bugfixes.
111 |
112 | v0.0.6 (16 Sep 2013)
113 | Options with a negative Number value are parsed correctly.
114 | The "argument()" function has been moved from the Argp to the Body and now
115 | accepts a second configuration parameter.
116 |
117 | v0.0.5 (15 Sep 2013)
118 | Added a "type" setting to the option configuration.
119 |
120 | v0.0.4 (15 Sep 2013)
121 | Added "footer()".
122 | The "fail()" function now prints the "try" message.
123 |
124 | v0.0.3 (15 Sep 2013)
125 | An 80 columns length was hardcoded.
126 |
127 | v0.0.2 (14 Sep 2013)
128 | Added automatic string conversion.
129 | Added "hidden" option configuration.
130 | When the input is parsed the first time "argv()" frees any resource; only
131 | the final object is needed.
132 | Minor bugfixes.
133 |
134 | v0.0.1 (13 Sep 2013)
135 | First release.
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 2014 Gabriel Llamas
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in
13 | all copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21 | THE SOFTWARE.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | argp
2 | ====
3 |
4 | #### Command-line option parser ####
5 |
6 | [](http://badge.fury.io/js/argp "Fury Version Badge")
7 | [](http://travis-ci.org/gagle/node-argp "Travis CI Badge")
8 |
9 | [](https://nodei.co/npm/argp "NodeICO Badge")
10 |
11 | Inspired by the extremly well-known [argp C library](http://www.gnu.org/software/libc/manual/html_node/Argp.html), this module parses GNU-style command-line options. Help, usage and version messages are automatically generated and line-wrapped at 80 columns. The module checks for errors, can be easily adapted to your needs thanks to its evented system and it also works when Node.js is in debug mode. The module is uncached and each property is deleted once all the input parameters have been parsed, so there's no memory footprint.
12 |
13 | This module it's made for you if you want:
14 |
15 | - Robust solution that reads GNU-style options.
16 | - Command configuration.
17 | - Basic error checking.
18 | - Nice help messages without caring about indentation, multilines, etc.
19 | - Zero memory footprint.
20 |
21 | A common configuration looks like this:
22 |
23 | ```javascript
24 | //If you're not going to use multiple parser instances or you don't need to
25 | //reuse a parser, don't cache the module, this will guarantee a zero memory
26 | //footprint
27 | var argv = require ("argp").createParser ({ once: true })
28 | .description ("Sample app.")
29 | .email ("a@b.c")
30 | .body ()
31 | //The object and argument definitions and the text of the --help message
32 | //are configured at the same time
33 | .text (" Arguments:")
34 | .argument ("arg", { description: "Sample argument" })
35 | .text ("\n Options:")
36 | .option ({ short: "o", long: "opt", description: "Sample option" })
37 | .help ()
38 | .version ("v1.2.3")
39 | .argv ();
40 |
41 | console.log (argv);
42 |
43 | /*
44 | $ node script.js
45 |
46 | {
47 | opt: false,
48 | help: false,
49 | version: false,
50 | arg: false
51 | }
52 |
53 | $ node script.js --help
54 |
55 | Usage: script [options] [arguments]
56 |
57 | Sample app.
58 |
59 | Arguments:
60 | arg Sample argument
61 |
62 | Options:
63 | -o, --opt Sample option
64 | -h, --help Display this help message and exit
65 | -v, --version Output version information and exit
66 |
67 | Report bugs to .
68 | */
69 | ```
70 |
71 | If you have a `package.json` file you can take from it the description, email and version using the `readPackage()` function. Take into account that this function calls a synchronous `fs` operation. Doesn't really matter because this module is one of the first things you're going to execute in your program.
72 |
73 | ```javascript
74 | var argv = require ("argp")
75 | //If no path is provided, it tries to read the "./package.json" file
76 | .readPackage ("path/to/package.json")
77 | .body ()
78 | .text (" Arguments:")
79 | .argument ("arg", { description: "Sample argument" })
80 | .text ("\n Options:")
81 | .option ({ short: "o", long: "opt", description: "Sample option" })
82 | .help ()
83 | .argv ();
84 | ```
85 |
86 | #### Documentation ####
87 |
88 | - [What's new in v1?](#new)
89 | - [Quick examples with no configuration](#quick)
90 | - [Configuring options](#options)
91 | - [Configuring arguments](#arguments)
92 | - [Configuring commands](#commands)
93 | - [Real examples](#examples)
94 |
95 | #### Functions ####
96 |
97 | - [_module_.createParser([options]) : Argp](#createparser)
98 |
99 | #### Objects ####
100 |
101 | - [Argp](#argp_object)
102 |
103 | ---
104 |
105 |
106 | __What's new in v1?__
107 |
108 | Two things will break your code:
109 |
110 | - Parser instances are introduced. To create one you need to call to [createParser()](#createparser).
111 | In most cases you only need to append `.createParser ({ once: true })`, for example:
112 |
113 | ```javascript
114 | var argv = require ("argp").createParser ({ once: true })
115 | ...
116 | argv ();
117 | ```
118 |
119 | The `once` option will uncache the module when [argv()](#argp_argv) is called.
120 |
121 | - The second argument from the [end](#event_end) event is removed.
122 |
123 | Before:
124 |
125 | ```javascript
126 | .on ("end", function (argv, fns){
127 | /*
128 | fns.printHelp ();
129 | fns.printUsage ();
130 | fns.printVersion ();
131 | fns.fail ();
132 | */
133 | })
134 | ```
135 |
136 | After:
137 |
138 | ```javascript
139 | .on ("end", function (argv){
140 | /*
141 | this.printHelp ();
142 | this.printUsage ();
143 | this.printVersion ();
144 | this.fail ();
145 | */
146 | })
147 | ```
148 |
149 | ---
150 |
151 |
152 | __Quick examples with no configuration__
153 |
154 | If an option has not been defined the type of the value is converted automatically from a string to a number, boolean, null or undefined.
155 |
156 | By default the parser doesn't allow undefined arguments and options because you typically want to have an absolute control over the calls to your program in order to avoid unexpected behaviours. Allowing undefined arguments and options is as simple as this:
157 |
158 | ```javascript
159 | var argv = require ("argp").createParser ({ once: true })
160 | .allowUndefinedArguments ()
161 | .allowUndefinedOptions ()
162 | .argv ();
163 | ```
164 |
165 | ```bash
166 | $ node script.js -a -b -c
167 | { a: true, b: true, c: true }
168 |
169 | $ node script.js a b c
170 | { a: true, b: true, c: true }
171 |
172 | $ node script.js -abc null
173 | { a: true, b: true, c: null }
174 |
175 | $ node script.js --a --b 1 --d=e
176 | { a: true, b: 1, d: "e" }
177 |
178 | $ node script.js --no-a b
179 | { a: false, b: true }
180 |
181 | $ node script.js --a -- -b --c d
182 | { a: true, "-b": true, "--c": true, d: true }
183 | ```
184 |
185 | ---
186 |
187 |
188 | __Configuring options__
189 |
190 | Example: [options.js](https://github.com/gagle/node-argp/blob/master/examples/options.js).
191 |
192 | Considerations:
193 |
194 | 1. By default the options are flags. If the option requires a value, the `metavar` property must be defined. This property is a string and can be seen when the --help and --usage messages are printed.
195 |
196 | ```bash
197 | $ node script.js --help
198 | ...
199 | o, --opt=STR Sample option
200 | ...
201 | ```
202 |
203 | Where `STR` is the `metavar` property.
204 |
205 | 2. By default, the value of the options is a string. Configure the `type` property if the value is a number, boolean (rarely used, use a flag instead) or array (comma-separated values and multiple assignments).
206 | 3. Each option has an id which is used to store the value in the final object. This id is the long name. If the long name has not been defined then the id is the short name.
207 |
208 | ```javascript
209 | .option ({ short: "a", long: "aa" })
210 | //{ aa: false }
211 | .option ({ long: "aa" })
212 | //{ aa: false }
213 | .option ({ short: "a" })
214 | //{ a: false }
215 | ```
216 | 4. Mandatory options (aka `required`) are not implemented because options are _optional_. Use a [command](#commands) if you need mandatory parameters.
217 |
218 | Common properties between flags and options with a value:
219 |
220 | - __description__ - _String_
221 | The description.
222 | - __hidden__ - _Boolean_
223 | If true, the option is not displayed in the --help and --usage messages. Default is false.
224 | - __long__ - _String_
225 | The long name. Cannot contain white spaces.
226 | - __short__ - _String_
227 | The short name. It must be an alphanumeric character.
228 |
229 | Flags:
230 |
231 | - __negate__ - _Boolean_
232 | If true, the flag is negated. The default value is true and it becomes false when the short name or the negated long name (eg. --no-flag) is present.
233 |
234 | ```javascript
235 | .option ({ short: "a", long: "aaa" })
236 | .option ({ short: "b", long: "bbb", negate: true })
237 | ```
238 | ```bash
239 | $ node script.js
240 | { aaa: false, bbb: true }
241 |
242 | $ node script.js -a -b
243 | { aaa: true, bbb: false }
244 |
245 | $ node script.js --aaa --bbb
246 | { aaa: true, bbb: true }
247 |
248 | $ node script.js --no-aaa --no-bbb
249 | { aaa: false, bbb: false }
250 | ```
251 |
252 | Options with a value:
253 |
254 | - __aliases__ - _Array_
255 | An alias it's a long-name option that points to another option.
256 |
257 | ```javascript
258 | .body ()
259 | .option ({ long: "name", aliases: ["foo", "bar"] })
260 | .help ()
261 | .usage ()
262 | ```
263 | ```bash
264 | $ node script.js --foo
265 | { name: true }
266 |
267 | $ node script.js --usage
268 | Usage: script [--name|--foo|--bar] [-h|--help] [--usage]
269 |
270 | $ node script.js --help
271 | Usage: script [options]
272 |
273 | --name, --foo, --bar
274 | -h, --help Display this help message and exit
275 | --usage Display a short usage message and exit
276 | ```
277 |
278 | The `options()` function returns an object with all the configured options:
279 |
280 | ```javascript
281 | {
282 | name: { ... },
283 | foo: { ... },
284 | bar: { ... },
285 | help: { ... },
286 | usage: { ... }
287 | }
288 | ```
289 | Where `name`, `foo` and `bar` point to the same object:
290 |
291 | ```javascript
292 | .on ("start", function (){
293 | var options = this.options ();
294 | assert.ok (options.name === options.foo && options.name === options.bar);
295 | })
296 | ```
297 | - __choices__ - _Array_
298 | The input value must be one of these choices. If the option is `optional`, the `choices` property is ignored.
299 |
300 | ```javascript
301 | .option ({ long: "opt", metavar: "NUM", type: Number, choices: [1, 2, 3] })
302 | ```
303 | ```bash
304 | $ node script.js --opt=1
305 | { opt: 1 }
306 |
307 | $ node script.js --opt=7 # Error!
308 | ```
309 |
310 | When `default` and `choices` are defined in the same option the default value doesn't need to match any choice:
311 |
312 | ```javascript
313 | .option ({ long: "opt", metavar: "STR", default: "d", choices: ["a", "b", "c"] })
314 | ```
315 | ```bash
316 | $ node script.js
317 | { opt: "d" }
318 | ```
319 | - __default__ - _Object_
320 | The default value.
321 |
322 | ```javascript
323 | .option ({ long: "name", metavar: "STR", default: "bar", optional: true })
324 | ```
325 | ```bash
326 | $ node script.js
327 | { name: "bar" }
328 |
329 | $ node script.js --name
330 | { name: "bar" }
331 |
332 | $ node script.js --name foo
333 | { name: "foo" }
334 | ```
335 | - __metavar__ - _String_
336 | Must be defined if the option requires a value. If `metavar` is not defined, the option is a flag. The string is used when the --help and --usage messages are printed.
337 |
338 | ```javascript
339 | .option ({ long: "name", metavar: "STR" })
340 | ```
341 | ```bash
342 | $ node script.js --help
343 | ...
344 | --name=STR
345 | ...
346 | ```
347 | - __optional__ - _Boolean_
348 | If true, the value is optional. Default is false. If the option doesn't receive any value the default value is set and it depends on the `default` and `type` properties.
349 |
350 | Types and default values:
351 | - String: `null`
352 | - Number: `0`
353 | - Array: `[]`
354 | - Boolean: `false`
355 |
356 | ```javascript
357 | .option ({ long: "name1", metavar: "STR", optional: true })
358 | .option ({ long: "name2", metavar: "STR", optional: true, type: String })
359 | .option ({ long: "name3", metavar: "NUM", optional: true, type: Number })
360 | .option ({ long: "name4", metavar: "ARR", optional: true, type: Array })
361 | //Boolean type is rarely used, use a flag instead
362 | .option ({ long: "name5", metavar: "BOOL", optional: true, type: Boolean })
363 | ```
364 | ```bash
365 | $ node script.js --name1 --name2 --name3 --name4 --name5
366 | { name1: null, name2: null, name3: 0, name4: [], name5: false }
367 | ```
368 | ```bash
369 | $ node script.js --name1 foo --name2 bar --name3 12 --name4 -12.34,foo,true --name4 false --name5 true
370 | { name1: "foo", ame2: "bar", name3: 12, name4: [-12.34, "foo", true, false], name5: true }
371 | ```
372 | - __reviver__ - _Function_
373 | The function is executed when the option is parsed. It is similar to the reviver parameter of the `JSON.parse()` function. This is the right place where you can validate the input data and `fail()` if it's not valid. For example, if the option requires a number you can validate the range here.
374 |
375 | ```javascript
376 | .option ({ long: "name", metavar: "STR", reviver: function (value){
377 | return value + "bar";
378 | }})
379 | ```
380 | ```bash
381 | $ node script.js --name foo
382 | { name: "foobar" }
383 | ```
384 | ```javascript
385 | .option ({ long: "opt", metavar: "NUM", type: Number,
386 | reviver: function (value){
387 | //The "value" parameter is already a number
388 | if (value < 1 || value > 3){
389 | this.fail ("Option 'opt': Invalid range.");
390 | }
391 | return value;
392 | }})
393 | ```
394 | - __type__ - _String | Number | Boolean | Array_
395 | The type of the value. Default is String.
396 |
397 | If the type is an Array, comma-separated values are automatically stored in an array and each element is converted to the type it represents. Multiple assignments are also supported.
398 |
399 | ```javascript
400 | .option ({ long: "name", metavar: "ARR", type: Array })
401 | ```
402 | ```bash
403 | $ node script.js --name 1,true,foo
404 | { name: [1, true, "foo"] }
405 |
406 | $ node script.js --name 1 --name true --name foo
407 | { name: [1, true, "foo"] }
408 |
409 | $ node script.js --name 1,2 --name true,false --name foo,bar
410 | { name: [1, 2, true, false, "foo", "bar"] }
411 | ```
412 |
413 | ---
414 |
415 |
416 | __Configuring arguments__
417 |
418 | Example: [arguments.js](https://github.com/gagle/node-argp/blob/master/examples/arguments.js).
419 |
420 | An argument is an individual name like `login`, `reset`, `build`, etc. They are basically flags.
421 |
422 | Properties:
423 |
424 | - __description__ - _String_
425 | The description.
426 | - __hidden__ - _Boolean_
427 | If true, the option is not displayed in the --help and --usage messages. Default is false.
428 |
429 | Note: `synopsis` and `trailing` properties can be also configured but they have meaning only with [commands](#commands).
430 |
431 | ```javascript
432 | .argument ("arg1")
433 | .argument ("arg2", { description: "foo" })
434 | .argument ("arg3", { description: "bar", hidden: true })
435 | ```
436 | ```bash
437 | $ node script.js arg1
438 | { arg1: true, arg2: false, arg3: false }
439 |
440 | $ node script.js --help
441 | ...
442 | arg1 foo
443 | arg2 bar
444 | ...
445 | ```
446 |
447 | Note that an argument is just a flag but it can be present without any prefixed hyphen. It is a flag with more weight, it is used to denote important actions.
448 |
449 | As you can see, the arguments are also stored in a hash like regular options, undefined arguments inclusive. For example:
450 |
451 | ```javascript
452 | var argv = require ("argp").createParser ({ once: true })
453 | .allowUndefinedArguments ()
454 | .allowUndefinedOptions ()
455 | .argv ();
456 |
457 | console.log (argv);
458 | ```
459 |
460 | ```bash
461 | $ node script.js a b c
462 | { a: true, b: true, c: true }
463 | ```
464 |
465 | This feature is different from other cli parsers that store the arguments in an array. If you need to read undefined arguments and save them in an array you can use the events. For more details: [to-upper-case.js](https://github.com/gagle/node-argp/blob/master/examples/to-upper-case.js)
466 |
467 | ---
468 |
469 |
470 | __Configuring commands__
471 |
472 | A command is an argument followed by other arguments and options. NPM is an example:
473 |
474 | ```
475 | npm config set []
476 | npm install [...] -g
477 | ```
478 |
479 | `config` is a command and `set` an argument with 2 trailing arguments: minimum 1, maximum 2.
480 | `install` is a command with infinite trailing arguments: minimum 0, maximum Infinity. `-g` is an option which only applies to the `install` command.
481 |
482 | If you have a very few commands you can configure them in the same file ([commands.js](https://github.com/gagle/node-argp/blob/master/examples/commands.js) example), but you typically want to modularize them, one command per file. Then you should check the [npm.js](https://github.com/gagle/node-argp/blob/master/examples/npm/npm.js) example.
483 |
484 | The commands are configured exactly the same way as the `Argp` instance with only one difference: `argument()` accepts 2 new properties:
485 |
486 | - __synopsis__ - _String_
487 | The string replaces the argument name in the --help and --usage messages.
488 |
489 | ```javascript
490 | .argument ("set", { description: "Sample argument" });
491 | /*
492 | ...
493 | set Sample argument
494 | ...
495 | */
496 |
497 | .argument ("set", { synopsis: "set []", description: "Sample argument" });
498 | /*
499 | ...
500 | set [] Sample argument
501 | ...
502 | */
503 | ```
504 | - __trailing__ - _Object_
505 | Configures how many trailing arguments must follow this argument.
506 |
507 | There are 3 properties: `eq`, `min` and `max`. `eq` cannot be used with `min` or `max`. If `min` and `max` are used, by default `min` is 0 and `max` is Infinity. A `trailing` object without any of these 3 properties defaults to `min` 0 and `max` Infinity.
508 |
509 | Some examples:
510 |
511 | - 2 trailing arguments required: `cmd arg `.
512 |
513 | ```javascript
514 | .argument ("arg", { trailing: { eq: 2 } })
515 | ```
516 | - 1 required, 1 optional: `cmd arg []`.
517 |
518 | ```javascript
519 | .argument ("arg", { trailing: { min 1, max: 2 } })
520 | ```
521 | - 1 optional: `cmd arg []`.
522 |
523 | ```javascript
524 | .argument ("arg", { trailing: { max: 1 } })
525 | ```
526 | - 1 required, infinite optional: `cmd arg [...]`.
527 |
528 | ```javascript
529 | .argument ("arg", { trailing: { min: 1 } })
530 | ```
531 | - Infinite: `cmd arg [...]`.
532 |
533 | ```javascript
534 | .argument ("arg", { trailing: {} })
535 | //Same as trailing: { min: 0, max: Infinity }
536 | ```
537 | - No trailing arguments: `cmd arg`.
538 |
539 | ```javascript
540 | .argument ("arg")
541 | ```
542 | - Multiple arguments with trailing in the same line. Argument `arg1` with 1 required, and argument `arg2` with infinite trailing arguments: `cmd arg1 arg2 [...]`. Note that writing `cmd arg1 arg2 [...]` is not the same as `cmd arg2 [...] arg1 `. In the latter case, `arg1 ` will be eaten by the trailing arguments of `arg2`.
543 |
544 | ```javascript
545 | .argument ("arg1", { trailing: { eq: 1 } })
546 | .argument ("arg2", { trailing: {} })
547 | ```
548 |
549 | ---
550 |
551 |
552 | __Real examples__
553 |
554 | - [brainfuck](https://github.com/gagle/node-brainfuck/blob/master/bin/brainfuck.js): Interpreter for the Brainfuck esoteric language.
555 | - [ntftp](https://github.com/gagle/node-ntftp/blob/master/bin/ntftp.js): Streaming TFTP client and server.
556 |
557 | ---
558 |
559 |
560 | ___module_.createParser([options]) : Argp__
561 |
562 | Returns a new [Argp](#argp_object) instance.
563 |
564 | Options:
565 |
566 | - __once__ - _Boolean_
567 | Set it to true if you want to uncache the whole module when [argv()](#argp_argv) finishes. This will guarantee a zero memory footprint. Default is false.
568 |
569 | ---
570 |
571 |
572 | __Argp__
573 |
574 | The module returns an instance of `Argp`. It inherits from an EventEmitter.
575 |
576 | The parser follows the GNU-style rules: `-a`, `-abc`, `--a`, `--no-a`, `--a=b`, `--`, etc. Long-option abbreviation is also supported.
577 |
578 | If you don't want to configure anything simply require the module, allow undefined arguments and options and call to `argv()`.
579 |
580 | ```javascript
581 | var argv = require ("argp").createParser ({ once: true })
582 | .allowUndefinedArguments ()
583 | .allowUndefinedOptions ()
584 | .argv ();
585 | ```
586 |
587 | Note: If no configuration is provided you cannot join a short name with its value in the same token, eg: `-Dvalue`, all the characters following a hyhen are interpreted as individual flags.
588 |
589 | __Events__
590 |
591 | With the event system you can fully adapt this module to yours needs. Examples: [to-upper-case.js](https://github.com/gagle/node-argp/blob/master/examples/to-upper-case.js), [mkdir.js](https://github.com/gagle/node-argp/blob/master/examples/mkdir.js).
592 |
593 | - [argument](#event_argument)
594 | - [end](#event_end)
595 | - [error](#event_error)
596 | - [option](#event_option)
597 | - [start](#event_start)
598 |
599 | __Methods__
600 |
601 | - [Argp#allowUndefinedArguments() : Argp](#argp_allowundefinedarguments)
602 | - [Argp#allowUndefinedOptions() : Argp](#argp_allowundefinedoptions)
603 | - [Argp#arguments() : Object](#argp_arguments)
604 | - [Argp#argv([input]) : Object](#argp_argv)
605 | - [Argp#body() : Body](#argp_body)
606 | - [Argp#columns(columns) : Argp](#argp_columns)
607 | - [Argp#command(name[, configuration]) : Command](#argp_command)
608 | - [Argp#commands() : Argp](#argp_commands)
609 | - [Argp#description(str) : Argp](#argp_description)
610 | - [Argp#email(str) : Argp](#argp_email)
611 | - [Argp#exitStatus(code) : Argp](#argp_exitstatus)
612 | - [Argp#fail(str[, code]) : undefined](#argp_fail)
613 | - [Argp#main() : Argp](#argp_main)
614 | - [Argp#options([filter]) : Object](#argp_options)
615 | - [Argp#printHelp([code]) : undefined](#argp_printhelp)
616 | - [Argp#printUsage([code]) : undefined](#argp_printusage)
617 | - [Argp#printVersion([code]) : undefined](#argp_printversion)
618 | - [Argp#readPackage([path]) : Argp](#argp_readpackage)
619 | - [Argp#sort() : Argp](#argp_sort)
620 | - [Argp#usages(usages) : Argp](#argp_usage)
621 |
622 | __Objects__
623 |
624 | - [Body](#body)
625 |
626 | ---
627 |
628 |
629 | __argument__
630 |
631 | Emitted when an argument is found.
632 |
633 | Parameters:
634 |
635 | - __argv__ - _Object_
636 | The final object.
637 | - __argument__ - _String_
638 | The name of the argument.
639 | - __ignore__ - _Function_
640 | When the function is called the parser ignores the argument, hence it isn't stored in the final object.
641 |
642 |
643 | __end__
644 |
645 | Emitted when all the options and arguments have been parsed.
646 |
647 | Parameters:
648 |
649 | - __argv__ - _Object_
650 | The final object.
651 |
652 |
653 | __error__
654 |
655 | Emitted when an error occurs. If you don't listen for `error` events, the message will be printed to stderr and the process will exit. If you attach an error handler and an error occurs, [argv()](#argp_argv) returns null.
656 |
657 | You typically want to listen for `error` events when you need to do something with the error and then quit the process, or simply because you want to continue executing the process (maybe because you are executing a shell prompt) and display the error in the console.
658 |
659 | ```javascript
660 | .on ("error", function (error){
661 | doSomethingWith (error);
662 | //This will end the process
663 | this.fail (error);
664 | })
665 | ```
666 |
667 | For example, the [ntftp](https://github.com/gagle/node-ntftp/blob/master/bin/ntftp.js) module uses two parsers. One is the main parser. If something is not correct, it prints the error to stderr and finishes. The second parser is used when the program is executing a shell prompt. It is being reused and the errors are simply printed to console.
668 |
669 |
670 | __option__
671 |
672 | Emitted when an option is found.
673 |
674 | Parameters:
675 |
676 | - __argv__ - _Object_
677 | The final object.
678 | - __option__ - _String_
679 | The name of the option.
680 | - __value__ - _String_
681 | The value of the option after calling the reviver, if any.
682 | - __long__ - _Boolean_
683 | True if the option is a long name, otherwise false.
684 | - __ignore__ - _Function_
685 | When the function is called the parser ignores the argument, hence it isn't stored in the final object.
686 |
687 |
688 | __start__
689 |
690 | Emitted just before the parser begins to read the cli parameters.
691 |
692 | Parameters:
693 |
694 | - __argv__ - _Object_
695 | The final object. The default values are already set.
696 |
697 | ---
698 |
699 |
700 | __Argp#allowUndefinedArguments() : Argp__
701 |
702 | Allows undefined arguments.
703 |
704 |
705 | __Argp#allowUndefinedOptions() : Argp__
706 |
707 | Allows undefined options.
708 |
709 |
710 | __Argp#arguments() : Object__
711 |
712 | Returns the configured arguments. Look at the [internal-data.js](https://github.com/gagle/node-argp/blob/master/examples/internal-data.js) example for further details.
713 |
714 |
715 | __Argp#argv([input]) : Object | null__
716 |
717 | Parses the `process.argv` array or the given input array.
718 |
719 | If you don't need to reuse the parser and want a zero memory footprint, you shouldn't cache the module and the parser instance. Remember to also set `once` to true.
720 |
721 | ```javascript
722 | var argv = require ("argp").createParser ({ once: true })
723 | ...
724 | argv ();
725 | ```
726 |
727 | If you need to reuse a parser, you probably want to listen for [error](#event_error) events. If an error occurs, [argv()](#arg_argv) returns null.
728 |
729 | ```javascript
730 | var argp = require ("argp");
731 |
732 | //Configuration
733 | var parser = argp.createParser ()
734 | .on ("error", ...)
735 | ...;
736 |
737 | var argv;
738 | argv = parser.argv (["-a", "--b", ...]);
739 | argv = parser.argv (["c", "d", ...]);
740 | ```
741 |
742 | If you pass an input array, then the functions [printHelp()](#argp_printhelp), [printUsage()](#argp_printusage) and [printVersion()](#argp_printversion) will print the message but won't terminate the process.
743 |
744 |
745 | __Argp#body() : Argp__
746 |
747 | Returns a `Body` instance.
748 |
749 |
750 | __Argp#columns(columns) : Argp__
751 |
752 | Sets the maximum line length. By default lines are wrapped at 80 columns.
753 |
754 |
755 | __Argp#command(name[, configuration]) : Command__
756 |
757 | Configures a command. A command it's like a new fresh cli program. It behaves exactly like an `Argp`. See [Configuring commands](#commands).
758 |
759 |
760 | __Argp#commands() : Object__
761 |
762 | Returns the configured commands.
763 |
764 | Look at the [internal-data.js](https://github.com/gagle/node-argp/blob/master/examples/internal-data.js) example for further details.
765 |
766 |
767 | __Argp#description(str) : Argp__
768 |
769 | Sets a description. The description is printed at the start of the --help message, after the "Usage" lines.
770 |
771 |
772 | __Argp#email(str) : Argp__
773 |
774 | Sets a contact email. The email is printed at the end of the --help message.
775 |
776 |
777 | __Argp#exitStatus(code) : Argp__
778 |
779 | Sets the exit code that will be used is some methods. Default is 1.
780 |
781 |
782 | __Argp#fail(str[, code]) : undefined__
783 |
784 | Prints a message to the stderr and exits with the given code number or if not given, uses the code configured with [exitStatus()](#argp_exitstatus) or if not configured, exits with code 1.
785 |
786 |
787 | __Argp#main() : Argp__
788 |
789 | Returns de main `Argp` instance. It's a no-op function, just for a better visual organization when configuring commands.
790 |
791 | Look at the [npm.js](https://github.com/gagle/node-argp/blob/master/examples/npm/npm.js) example for further details.
792 |
793 |
794 | __Argp#options([filter]) : Object__
795 |
796 | Returns the configured options. `filter` is an object which can be used to return the options that have a short name or a long name.
797 |
798 | ```javascript
799 | .options ()
800 | .options ({ short: true })
801 | .options ({ long: true })
802 | ```
803 |
804 | Look at the [internal-data.js](https://github.com/gagle/node-argp/blob/master/examples/internal-data.js) example for further details.
805 |
806 |
807 | __Argp#printHelp([code]) : undefined__
808 |
809 | Prints the help message and exits with the given code number or if not given, uses the code configured with [exitStatus()](#argp_exitstatus) or if not configured, exits with code 0.
810 |
811 | If [argv()](#argp_argv) is called with an input array, the process doesn't exit.
812 |
813 |
814 | __Argp#printUsage([code]) : undefined__
815 |
816 | Prints the usage message and exits with the given code number or if not given, uses the code configured with [exitStatus()](#argp_exitstatus) or if not configured, exits with code 0.
817 |
818 | If [argv()](#argp_argv) is called with an input array, the process doesn't exit.
819 |
820 |
821 | __Argp#printVersion([code]) : undefined__
822 |
823 | Prints the version message (if it was configured) and exits with the given code number or if not given, uses the code configured with [exitStatus()](#argp_exitstatus) or if not configured, exits with code 0.
824 |
825 | If [argv()](#argp_argv) is called with an input array, the process doesn't exit.
826 |
827 |
828 | __Argp#readPackage([path][, options]) : Argp__
829 |
830 | Reads a `package.json` file and configures the parser with the description, email and version. If no path is provided it tries to read the `./package.json` path. The description, email and version labels can be ignored individually with the `options` parameter. For example, if you only want to ignore the email and read the description and version:
831 |
832 | ```javascript
833 | .readPackage ("path/to/package.json", { email: false })
834 | ```
835 |
836 | Options are: `description`, `version`, `email`. By default they are true. Set them to false to ignore them.
837 |
838 |
839 | __Argp#usages(usages) : Argp__
840 |
841 | Changes the "Usage" line from the --help and --usage messages. `usages` is an array of strings.
842 |
843 | Look at the [custom-usages.js](https://github.com/gagle/node-argp/blob/master/examples/custom-usages.js) example for further details.
844 |
845 |
846 | __Argp#sort() : Argp__
847 |
848 | If `sort()` is enabled, the options are parsed before the arguments, if not, the options and arguments are parsed in the same order they come.
849 |
850 | ---
851 |
852 |
853 | __Body__
854 |
855 | The `Body` instance is returned by calling [Argp#body()](#argp_body). All the following functions (except `argv()`, `command()` and `main()`) print a message in the same order they are configured, this allows you to fully customize the --help message very easily.
856 |
857 | Look at [fully-descriptive-help.js](https://github.com/gagle/node-argp/blob/master/examples/fully-descriptive-help.js) for further details.
858 |
859 | __Methods__
860 |
861 | - [Body#argument(name[, configuration]) : Body](#body_argument)
862 | - [Body#argv([input]) : Object](#body_argv)
863 | - [Body#columns(column1, column2) : Body](#body_columns)
864 | - [Body#command(name[, configuration]) : Command](#body_command)
865 | - [Body#help([options]) : Body](#body_help)
866 | - [Body#main() : Argp](#body_main)
867 | - [Body#option(o) : Body](#body_option)
868 | - [Body#text(str[, prefix]) : Body](#body_text)
869 | - [Body#usage() : Body](#body_usage)
870 | - [Body#version(str[, options]) : Body](#body_version)
871 |
872 |
873 | __Body#argument(name[, configuration]) : Body__
874 |
875 | Defines an argument. See [Configuring arguments](#arguments).
876 |
877 |
878 | __Body#argv([input]) : Object__
879 |
880 | Same as [Argp#argv()](#argp_argv).
881 |
882 |
883 | __Body#columns(column1, column2) : Body__
884 |
885 | Prints a line with 2 columns. The first column shouldn't contain line breaks (`\n`). This functionality is used to print the options and arguments.
886 |
887 |
888 | __Body#command(name[, configuration]) : Command__
889 |
890 | Same as [Argp#command()](#argp_command).
891 |
892 |
893 | __Body#help([options]) : Body__
894 |
895 | Enables the `-h, --help` option. The short option can be disabled using the `options` parameter.
896 |
897 | ```javascript
898 | .help ({ short: false })
899 | ```
900 | ```bash
901 | $ node script.js --help
902 | ...
903 | --help Display this help message and exit
904 | ...
905 | ```
906 |
907 |
908 | __Body#main() : Argp__
909 |
910 | Same as [Argp#main()](#argp_main).
911 |
912 |
913 | __Body#option(o) : Body__
914 |
915 | Defines an option. See [Configuring options](#options).
916 |
917 |
918 | __Body#text(str[, prefix]) : Body__
919 |
920 | Prints a text message. By default it's line-wrapped at 80 columns and supports multilines (line breaks, `\n`). The `prefix` is a string that is printed before each line. It's mainly used to indent the text with some spaces.
921 |
922 |
923 | __Body#usage() : Body__
924 |
925 | Enables the `--usage` option.
926 |
927 |
928 | __Body#version(str[, options]) : Body__
929 |
930 | Enables the `-v, --version` option. `str` is the text to print when the option is called. The short option can be disabled using the `options` parameter.
931 |
932 | ```javascript
933 | .version ("v1.2.3", { short: false })
934 | ```
935 | ```bash
936 | $ node script.js --help
937 | ...
938 | --version Output version information and exit
939 | ...
940 | ```
--------------------------------------------------------------------------------
/examples/abbreviations.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
3 | require ("../lib").createParser ({ once: true })
4 | .description ("Sample app.")
5 | .body ()
6 | .help ()
7 | .usage ()
8 | .version ("v1.2.3")
9 | .argv ();
10 |
11 | /*
12 | $ node abbreviations.js --he
13 |
14 | Usage: abbreviations [options]
15 |
16 | Sample app.
17 |
18 | -h, --help Display this help message and exit
19 | --usage Display a short usage message and exit
20 | -v, --version Output version information and exit
21 |
22 | --------------------------------------------------------------------------------
23 |
24 | $ node abbreviations.js --u
25 |
26 | Usage: abbreviations [-h|--help] [--usage] [-v|--version]
27 |
28 | --------------------------------------------------------------------------------
29 |
30 | $ node abbreviations.js --ver
31 |
32 | v1.2.3
33 | */
--------------------------------------------------------------------------------
/examples/aliases.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
3 | /*
4 | This example shows 2 types of aliases:
5 | - Pure aliases: They are just a different name which points to the same option.
6 | - Defined aliases: They have their own option definition but they are related
7 | with other options.
8 |
9 | Say we have a --dot option. We want to also use the --point name to refer to the
10 | same option. By default it prints one dot. If we want to print an ellipsis we
11 | can pass the value of 3 or we can define an --ellipsis flag. When it is enabled
12 | it prints 3 dots.
13 |
14 | --point is a pure alias and --ellipsis is a defined alias.
15 | */
16 |
17 | var argv = require ("../lib").createParser ({ once: true })
18 | .on ("end", function (argv){
19 | if (argv.ellipsis) argv.dot = 3;
20 | })
21 | .body ()
22 | .option ({
23 | short: "d",
24 | long: "dot",
25 | aliases: ["point"],
26 | metavar: "N",
27 | optional: true,
28 | default: 1,
29 | type: Number,
30 | description: "Print N dots, default is 1"
31 | })
32 | .option ({
33 | long: "ellipsis",
34 | description: "Print 3 dots, same as --dots=3"
35 | })
36 | .argv ();
37 |
38 | console.log (argv);
39 |
40 | /*
41 | $ node aliases.js --po 2 # The aliases can be also abbreviated
42 |
43 | {
44 | dot: 2,
45 | ellipisis: false
46 | }
47 |
48 | --------------------------------------------------------------------------------
49 |
50 | $ node aliases.js --ellipsis
51 |
52 | {
53 | dot: 3,
54 | ellipisis: true
55 | }
56 | */
--------------------------------------------------------------------------------
/examples/arguments.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
3 | var argv = require ("../lib").createParser ({ once: true })
4 | .body ()
5 | //Argument
6 | .argument ("arg1")
7 |
8 | //Argument with a description
9 | .argument ("arg2", { description: "foo" })
10 |
11 | //Hidden argument
12 | .argument ("arg3", { hidden: true })
13 |
14 | .help ()
15 | .usage ()
16 | .argv ();
17 |
18 | console.log (argv);
19 |
20 | /*
21 | $ node options.js
22 |
23 | {
24 | help: false,
25 | usage: false,
26 | arg1: false,
27 | arg2: false,
28 | arg3: false
29 | }
30 |
31 | --------------------------------------------------------------------------------
32 |
33 | $ node options.js --help
34 |
35 | Usage: options [options] [arguments]
36 |
37 | arg1
38 | arg2 foo
39 | -h, --help Display this help message and exit
40 | --usage Display a short usage message and exit
41 |
42 | --------------------------------------------------------------------------------
43 |
44 | $ node options.js --usage
45 |
46 | Usage: options [-h|--help] [--usage] [arg1] [arg2]
47 | */
--------------------------------------------------------------------------------
/examples/commands.js:
--------------------------------------------------------------------------------
1 | "use script";
2 |
3 | var argv = require ("../lib").createParser ({ once: true })
4 | .main ()
5 | .description ("Main menu.")
6 | .body ()
7 | .help ()
8 | .usage ()
9 | .command ("config")
10 | .body ()
11 | .argument ("set", {
12 | synopsis: "set []",
13 | trailing: { min: 1, max: 2 }
14 | })
15 | .help ()
16 | .command ("install", { trailing: {} })
17 | .body ()
18 | .option ({ short: "g", long: "global" })
19 | .usage ()
20 | .argv ();
21 |
22 | console.log (argv);
23 |
24 | /*
25 | $ node commands.js -h
26 |
27 | Usage: commands [options]
28 |
29 | Main menu.
30 |
31 | -h, --help Display this help message and exit
32 | --usage Display a short usage message and exit
33 |
34 | --------------------------------------------------------------------------------
35 |
36 | $ node commands.js config -h
37 |
38 | Usage: commands config [options] [arguments]
39 |
40 | set []
41 | -h, --help Display this help message and exit
42 |
43 | --------------------------------------------------------------------------------
44 |
45 | $ node commands.js config set 1 2
46 |
47 | { config: [], set: [ 1, 2 ] }
48 |
49 | --------------------------------------------------------------------------------
50 |
51 | $ node commands.js install --usage
52 |
53 | Usage: commands install [-g|--global] [--usage]
54 |
55 | --------------------------------------------------------------------------------
56 |
57 | $ node commands.js install 1 2 3 -g
58 |
59 | { install: [ 1, 2, 3 ], global: true }
60 | */
--------------------------------------------------------------------------------
/examples/custom-usages.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 |
3 | /*
4 | By default when the --help and --usage messages are printed there is only one
5 | "usage" line. This line can be changed and multiple lines can be added with the
6 | usages() function.
7 | */
8 |
9 | require ("../lib").createParser ({ once: true })
10 | .usages ([
11 | "custom-usages