Source

JavaScript Utils / parseopt / README.md

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
parseopt
========

Parseopt is a command line optionparser loosely inspired by Python's optparse
module. This module was written for node.js but should work with any other
JavaScript framework. Only when some certain parameters are not provided,
parseopt uses node.js specific code in order to lookup meaningful defaults.

Used node.js API:

 * `process.argv`: array of strings
 * `process.stdout`: object with a `write` method that accepts a string argument
 * `process.exit`: method that accepts a number argument

See the demo folder the end of this file for example usage.

API Reference
-------------

### Option Definition ###

Option definitions are objects that specify an option. You use them to specify
the name(s), type and severall parameters of an option.

Option types:

 * `float`
 * `integer`
 * `string`
 * `boolean`
 * `object`
 * `option`
 * `enum`
 * `flag`
 * `record`
 * `custom`

Option definition object:

	{
	   // Only when passed to the OptionParser constructor:
	   name:        string or array
	   names:       string or array, alias of name
	                Only one of both may be used at the same time.

	                Names can be long options (e.g. '--foo') and short options
	                (e.g. '-f'). The first name is used to indentify the option.
	                Names musst be unique and may not contain '='.

	                Short options may be combined when passed to a programm. E.g.
	                the options '-f' and '-b' can be combined to '-fb'. Only one
	                of these combined options may require an argument.

	                Short options are separated from ther arguments by space,
	                long options per '='. If a long option requires an argument
	                and none is passed using '=' it also uses the next commandline
	                argument as it's argument (like short options).

	                If '--' is encountered all remaining arguments are treated as
	                arguments and not as options.

	   // General fields:
	   target:      string, per deflault inferred from first name
	                This defines the name used in the returned options object.
	                Multiple options may have the same target.
	   default:     any, default: undefined
	                The default value associated with a certain target and is
	                overwritten by each new option with the same target.
	   type:        string, default: 'string', see below
	   required:    boolean, default: false
	   redefinable: boolean, default: true
	   help:        string, optional
	   details:     array, optional
	                short list of details shown in braces after the option name
	                e.g. integer type options add 'base: '+base if base !== undefined
	   metavar:     string or array, per deflault inferred from type
	   onOption:    function (value) -> boolean, optional
	                Returning true canceles any further option parsing
	                and the parse() method returns null.

	   // Type: string  (alias: str)
	   // Type: boolean (alias: bool)
	   // Type: object  (alias: obj)

	   // Type: integer (alias: int)
	   min:         integer, optional
	   max:         integer, optional
	   NaN:         boolean, default: false
	   base:        integer, optional

	   // Type: float   (alias: number)
	   min:         float, optional
	   max:         float, optional
	   NaN:         boolean, default: false

	   // Type: flag
	   value:       boolean, default: true
	   default:     boolean, default: false

	   // Type: option
	   value:       any, per default inferred from first name

	   // Type: enum
	   ignoreCase:  boolean, default: true
	   values:      array or object where the user enteres the field name of
	                the object and you get the value of the field

	   // Type: record
	   create:      function () -> object, default: Array
	   args:        array of type definitions (type part of option definitions)

	   // Type: custom
	   argc:        integer, default: -1
	                Number of required arguments.
	                -1 means one optional argument.
	   parse:       function (string, ...) -> value
	   stringify:   function (value) -> string, optional
	}

#### Type: `float` ####

**Arguments:** `1`

**Alias:** `number`

Parse a `float` option argument. You can optionally specify `min` and `max`
parameters to the option definition in order to limit the range of allowed
values. Using the boolean `NaN` parameter it can be controlled if `NaN'
values are allowed (default: `false`).

Example:

	parser.add(['-n','-d','--float'], {
		type: 'float',
		min: 0
	});

#### Type: `integer` ####

**Arguments:** `1`

**Alias:** `int`

Parse an `integer` option argument. You can optionally specify `min` and `max`
parameters to the option definition in order to limit the range of allowed
values. Using the boolean `NaN` parameter it can be controlled if `NaN'
values are allowed (default: `false`). The `base` parameter controlls the
base of the parsed number. Per default integers are parsed like JavaScript
integer lieterals, meaning a `0x` prefix specifies a hexadecimal number, a
`0` prefix an octal number and otherwise it is interpreted as a decimal number.

Example:

	parser.add('--int32', {
		type: 'integer',
		min: -2147483648,
		max: 2147483647,
		metavar: 'INT32'
	});

#### Type: `string` ####

**Arguments:** `1`

**Alias:** `str`

This is the default type. It doesn't do any parsing but just passes through
the string option argument.

Example:

	parser.add('--foo', {type: 'string'});

#### Type: `boolean` ####

**Arguments:** `1`

**Alias:** `bool`

Parse a `boolean` option argument.

Values accepted as `true` (case is ignored):

 * `true`
 * `on`
 * `1`
 * `yes`

Values accepted as `false` (case is ignored):

 * `false`
 * `off`
 * `0`
 * `no`

Example:

	parser.add('--bar', {type: 'boolean'});

#### Type: `object` ####

**Arguments:** `1`

**Alias:** `obj`

Parse option argument as JSON string.

Example:

	parser.add('--obj', {
		type: 'object',
		default: {
			foo: 'bar',
			baz: [23, 42]
		}
	});

#### Type: `enum` ####

**Arguments:** `1`

With this option type you can define a list of option `values` as the allowed
option arguments. The `values` parameter can either be an array of strings or
a object, where the property names are used as the values for the allowed
option arguments. The value stored to the parsed parameter object will be the
according property value. The boolean `ignoreCase` parameter specifies whether
the case of the option argument is ignored (default: `true`).

Example:

	parser.add('--enum1', {
		type: 'enum',
		values: ['foo', 'bar', 'baz']
	});
	
	parser.add('--enum2', {
		type: 'enum',
		values: {
			foo: 'FOO',
			bar: [23, 42],
			baz: null
		}
	});

#### Type: `option` ####

**Arguments:** `0`

With the `option` type you can specify an option with a fixed value. It makes
most sense if you have several options without argument that write the same
`target`.

See also: `flag`

Example:

	parser.add('--opt1', {
		type: 'option',
		target: 'what',
		value: 555
	});

#### Type: `flag` ####

**Arguments:** `0-1`

Like `option` but only for boolean values. If no option argument is provided
the value specified by the `value` parameter is used.

Example:

	parser.add('--use-something', {type: 'falg'});

#### Type: `record` ####

**Arguments:** `*`

A `record` option accepts several option arguments. How many and which types
is specified through the `args` parameter. This parameter accepts an array of
option definitions (some parameters of these option definietions are ignored:
`name`, `default`, `required`, `redefinable`, `help`, `details`, `onOption`).
The type ot the record itself can be provided through the `create` parameter
(function, default: Array).

Example:

	parser.add('--record', {
		type: 'record',
		default: ['bla', [10, 'bleh']],
		args: [
			{type: 'string'},
			{type: 'record', args: [
				{type: 'integer'},
				{type: 'string'},
			]}
		]
	});
	
	parser.add('--named', {
		type: 'record',
		create: Object,
		default: {a: 0.5, b: 300, c: 'bla'},
		args: [
			{type: 'float',   target: 'a'},
			{type: 'integer', target: 'b'},
			{type: 'string',  target: 'c'}
	]});

#### Type: `custom` ####

**Arguments:** `*`

Example:

	parser.add('--b64', {
		type: 'custom',
		argc: 1,
		metavar: 'BASE64-STRING',
		parse: function (s) {
			return new Buffer(s, 'base64');
		},
		stringify: function (buffer) {
			return buffer.toString('base64');
		},
		help: 'Pass binary data as a base64 encoded string.'
	});

### OptionParser ###

#### Constructor ####

**Arguments:**

 * `params`: object, optional


##### params #####

	{
	   minargs: integer, optional
	   maxargs: integer, optional
	   program: string, per default inferred from process.argv
	   strings: object, optional
	            Table of strings used in the output. See below.
	   options: array, optional
	            Array of option definitions. See below.
	}

##### strings #####

	{
	   help:      string, default: 'No help available for this option.'
	   usage:     string, default: 'Usage'
	   options:   string, default: 'OPTIONS'
	   arguments: string, default: 'ARGUMENTS'
	   required:  string, default: 'required'
	   default:   string, default: 'default'
	   base:      string, default: 'base'
	   metavars:  object, optional
	              Table of default metavar names per type.
	              Per default the type name in capital letters or derived
	              from the possible values.
	}

#### Properties ####

Don't modifiy the properties unless you really know what you are doing.

##### optionsPerName #####

**Type:** `Object`

Map of option definitions. Option definitions may occur multiple times when
there are name aliases.

##### options #####

**Type:** `Array`

Array of option definitions.

##### defaultValues #####

**Type:** `Object`

Map of default values.

#### Methods ####

##### parse #####

**Arguments:** 

 * `args`: array of strings, default: `process.argv`

##### add #####

**Arguments:**

 * `names`: string or array of strings, optional
 * `optdef`: option definition, optional

##### error #####

**Arguments:**

 * `msg`: string
 * `out`: `WriteStream`, default: `process.stdout`
 
##### usage #####

**Arguments:**

 * `help`: string
 * `out`: `WriteStream`, default: `process.stdout`
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.