flags 0.1.3 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/flags.js DELETED
@@ -1,505 +0,0 @@
1
- /**
2
- * @fileoverview Flag parsing library for node.js. See ../README.md for info.
3
- *
4
- * @author dan@pupi.us (Daniel Pupius)
5
- */
6
-
7
- var util = require('util');
8
-
9
-
10
- /**
11
- * An object containing a map of flag objects. If different modules are
12
- * importing different versions of the library we want them to use the same
13
- * FLAGS object. This does mean that the flags library needs to be backwards
14
- * compatible. This is a pretty ugly solution, should look for a better one.
15
- * @type {!Object}
16
- */
17
- if (typeof GLOBAL_FLAGS == 'undefined') {
18
- var registerFlags = true;
19
- GLOBAL_FLAGS = {};
20
- }
21
- var FLAGS = exports.FLAGS = GLOBAL_FLAGS;
22
-
23
-
24
- /**
25
- * If true, then the process will be nicely exit on a parse error. If false,
26
- * an Error will be thrown. Set to false in tests.
27
- * @type {boolean}
28
- */
29
- exports.exitOnError = true;
30
-
31
-
32
- /**
33
- * Allows an app to add extra usage information that will be shown in the help
34
- * message, above the flags.
35
- * @type {string}
36
- */
37
- exports.usageInfo = 'Usage: node ' +
38
- (process.argv[1] || '').split('/').pop() + ' [options]';
39
-
40
-
41
- /**
42
- * Defines a string flag. e.g. --servername=bob
43
- * @param {string} name The flag name, should be [a-zA-Z0-9]+.
44
- * @param {string=} opt_default The default value, should the flag not be
45
- * explicitly specified.
46
- * @param {string=} opt_description Optional description to use in help text.
47
- * @return {!Flag} The flag object.
48
- */
49
- exports.defineString = function(name, opt_default, opt_description) {
50
- return addFlag(name, new Flag(name, opt_default, opt_description));
51
- };
52
-
53
-
54
- /**
55
- * Defines a boolean flag. e.g. --turnonlights
56
- * @param {string} name The flag name, should be [a-zA-Z0-9]+.
57
- * @param {boolean=} opt_default The default value, should the flag not be
58
- * explicitly specified.
59
- * @param {string=} opt_description Optional description to use in help text.
60
- * @return {!BooleanFlag} The flag object.
61
- */
62
- exports.defineBoolean = function(name, opt_default, opt_description) {
63
- return addFlag(name, new BooleanFlag(name, opt_default, opt_description));
64
- };
65
-
66
-
67
- /**
68
- * Defines an integer flag. e.g. --age=12
69
- * @param {string} name The flag name, should be [a-zA-Z0-9]+.
70
- * @param {number=} opt_default The default value, should the flag not be
71
- * explicitly specified.
72
- * @param {string=} opt_description Optional description to use in help text.
73
- * @return {!IntegerFlag} The flag object.
74
- */
75
- exports.defineInteger = function(name, opt_default, opt_description) {
76
- return addFlag(name, new IntegerFlag(name, opt_default, opt_description));
77
- };
78
-
79
-
80
- /**
81
- * Defines a number flag. e.g. --number=1.345
82
- * @param {string} name The flag name, should be [a-zA-Z0-9]+.
83
- * @param {number=} opt_default The default value, should the flag not be
84
- * explicitly specified.
85
- * @param {string=} opt_description Optional description to use in help text.
86
- * @return {!NumberFlag} The flag object.
87
- */
88
- exports.defineNumber = function(name, opt_default, opt_description) {
89
- return addFlag(name, new NumberFlag(name, opt_default, opt_description));
90
- };
91
-
92
-
93
- /**
94
- * Defines a string list flag. e.g. --anmial=frog,bat,chicken
95
- * @param {string} name The flag name, should be [a-zA-Z0-9]+.
96
- * @param {!Array.<string>=} opt_default The default value, should the flag not
97
- * be explicitly specified.
98
- * @param {string=} opt_description Optional description to use in help text.
99
- * @return {!StringListFlag} The flag object.
100
- */
101
- exports.defineStringList = function(name, opt_default, opt_description) {
102
- return addFlag(name, new StringListFlag(name, opt_default, opt_description));
103
- };
104
-
105
-
106
- /**
107
- * Defines a multi string flag. e.g. --allowedip=127.0.0.1 --allowedip=127.0.0.2
108
- * @param {string} name The flag name, should be [a-zA-Z0-9]+.
109
- * @param {!Array.<string>=} opt_default The default value, should the flag not
110
- * be explicitly specified.
111
- * @param {string=} opt_description Optional description to use in help text.
112
- * @return {!MultiStringFlag} The flag object.
113
- */
114
- exports.defineMultiString = function(name, opt_default, opt_description) {
115
- return addFlag(name, new MultiStringFlag(name, opt_default, opt_description));
116
- };
117
-
118
-
119
- /**
120
- * Dumps the help text to the console.
121
- */
122
- exports.help = function() {
123
- if (exports.usageInfo) {
124
- console.log(exports.usageInfo + '\n');
125
- }
126
- console.log('Options:');
127
- for (var flag in FLAGS) {
128
- if (!FLAGS[flag].isSecret) {
129
- console.log(FLAGS[flag].toHelpString());
130
- }
131
- }
132
- };
133
-
134
-
135
- /**
136
- * Resets the flag values.
137
- */
138
- exports.reset = function() {
139
- parseCalled = false;
140
- FLAGS = exports.FLAGS = GLOBAL_FLAGS = {};
141
- registerInternalFlags();
142
- };
143
-
144
-
145
- /**
146
- * Gets the current value of the given flag.
147
- * @param {string} name The flag name.
148
- * @return {*}
149
- */
150
- exports.get = function(name) {
151
- if (!FLAGS[name]) throw Error('Unknown flag "' + name + '"');
152
- return FLAGS[name].get(name);
153
- };
154
-
155
-
156
- /**
157
- * Gets whether or not the flag was set.
158
- * @param {string} name The flag name.
159
- * @return {boolean}
160
- */
161
- exports.isSet = function(name) {
162
- if (!FLAGS[name]) throw Error('Unknown flag "' + name + '"');
163
- return FLAGS[name].isSet;
164
- };
165
-
166
- /**
167
- * Parses process.argv for flags. Idempotent if called multiple times.
168
- * @param {Array.<string>=} opt_args Optional arguments array to use instead of
169
- * process.argv.
170
- * @param {boolean} opt_ignoreUnrecognized Don't throw errors if unrecognized
171
- * flags are encountered.
172
- */
173
- exports.parse = function(opt_args, opt_ignoreUnrecognized) {
174
- var args = opt_args || process.argv.slice(2);
175
- if (parseCalled) return;
176
-
177
- var parsedFlags = {};
178
- var lastflag = null;
179
- for (var i = 0; i < args.length; i++) {
180
- var arg = args[i];
181
-
182
- // Terminate any flag processing
183
- if (arg == '--') {
184
- break;
185
-
186
- // Handle a typical long form flag --foo or --foo=bar.
187
- } else if (arg.substr(0, 2) == '--') {
188
- var flag = arg.substr(2);
189
- var value = null;
190
- if (flag.indexOf('=') > -1) {
191
- var parts = flag.split('=');
192
- flag = parts[0];
193
- value = parts.slice(1).join('=');
194
- }
195
-
196
- // Hacky munging of the args to handle space separated flags.
197
- if (value == null && args[i + 1] && args[i + 1].substr(0, 2) != '--') {
198
- args[i] = args[i] + ' ' + args[i + 1];
199
- value = args[i + 1];
200
- args.splice(i + 1, 1);
201
- }
202
-
203
- // Special case boolean flags of the form '--noflagname'.
204
- if (!FLAGS[flag] && value == null && flag.substr(0, 2) == 'no') {
205
- flag = flag.substr(2);
206
- value = '0';
207
- }
208
-
209
- if (FLAGS[flag]) {
210
- try {
211
- FLAGS[flag].set(value);
212
- } catch (e) {
213
- throwFlagParseError(args, i, e.message);
214
- }
215
- } else if (!opt_ignoreUnrecognized) {
216
- throwFlagParseError(args, i, 'Unrecognized flag name "' + arg + '"');
217
- }
218
-
219
- // For now we only handle simple flags like --foo=bar, so fail out.
220
- } else {
221
- throwFlagParseError(args, i, 'Invalid argument "' + arg + '"');
222
- }
223
- }
224
-
225
- parseCalled = true;
226
-
227
- // Intercept the --help flag.
228
- if (FLAGS.help.get()) {
229
- exports.help();
230
- process.exit(0);
231
- }
232
-
233
- if (i != args.length) {
234
- return args.slice(i + 1);
235
- } else {
236
- return [];
237
- }
238
- };
239
-
240
-
241
- // Private helpers
242
- //==================
243
-
244
- var parseCalled = false;
245
-
246
-
247
- function throwFlagParseError(args, i, msg) {
248
- // Show a nice error message with the offending arg underlined.
249
- var msg = 'FLAG PARSING ERROR: ' + msg + '\n ' +
250
- args.join(' ') + '\n ' +
251
- new Array(args.slice(0, i).join(' ').length + 2).join(' ') +
252
- new Array(args[i].length + 1).join('^');
253
-
254
- if (exports.exitOnError) {
255
- console.error(msg);
256
- process.exit(1);
257
- } else {
258
- throw Error(msg);
259
- }
260
- }
261
-
262
-
263
- function addFlag(name, flag) {
264
- if (parseCalled) throw Error('Can not register new flags after parse()');
265
- if (FLAGS[name]) throw Error('Flag already defined: "' + flag + '"')
266
- FLAGS[name] = flag;
267
- return flag;
268
- }
269
-
270
-
271
- function wrapText(text, maxLen) {
272
- var lines = text.split('\n');
273
- var out = [];
274
- for (var i = 0; i < lines.length; i++) {
275
- // Adjust the maxLength for to take into account the lack of indent on the
276
- // first line.
277
- var maxLenx = maxLen + (out.length == 0 ? 4 : 0);
278
- var line = lines[i];
279
- if (line.length < maxLenx) {
280
- // Line doesn't exceed length so just push it.
281
- out.push(line)
282
- } else {
283
- // Wrap the line on spaces.
284
- // TODO : Would be nice to split URLs and long phrases that have no
285
- // natural spaces.
286
- var current = wrapLine(line, ' ', maxLenx, out);
287
- if (current != '') {
288
- out.push(current);
289
- }
290
- }
291
- }
292
- return out.join('\n ');
293
- }
294
-
295
-
296
- function wrapLine(line, delimiter, maxLen, out) {
297
- var parts = line.split(delimiter);
298
- var current = '';
299
- for (var i = 0; i < parts.length; i++) {
300
- var part = parts[i];
301
- var next = current + part + delimiter;
302
- if (next.length > maxLen) {
303
- out.push(current);
304
- current = part + delimiter;
305
- } else {
306
- current = next;
307
- }
308
- }
309
- return current;
310
- }
311
-
312
-
313
- /**
314
- * @constructor
315
- */
316
- function Flag(name, defaultValue, description) {
317
- this.name = name;
318
- this.defaultValue = defaultValue;
319
- this.description = description;
320
- this.currentValue = null;
321
- this.validator = null;
322
- this.isSecret = false;
323
- this.isSet = false;
324
- }
325
-
326
-
327
- Flag.prototype.setDefault = function(defaultValue) {
328
- this.defaultValue = defaultValue;
329
- return this;
330
- };
331
-
332
-
333
- Flag.prototype.setDescription = function(description) {
334
- this.description = description;
335
- return this;
336
- };
337
-
338
-
339
- Flag.prototype.setValidator = function(validator) {
340
- this.validator = validator;
341
- return this;
342
- };
343
-
344
-
345
- Flag.prototype.setSecret = function(isSecret) {
346
- this.isSecret = isSecret;
347
- return this;
348
- };
349
-
350
-
351
- Flag.prototype.set = function(input) {
352
- if (this.isSet) {
353
- throw Error('Flag already set');
354
- }
355
- if (this.validator) this.validator.call(null, input);
356
- this.currentValue = this.parseInput(input);
357
- this.isSet = true;
358
- };
359
-
360
-
361
- Flag.prototype.get = function() {
362
- return this.isSet ? this.currentValue : this.defaultValue;
363
- };
364
-
365
-
366
- Flag.prototype.parseInput = function(inp) {
367
- return inp;
368
- };
369
-
370
-
371
- Flag.prototype.toHelpString = function() {
372
- return wrapText(' --' + this.name + ': ' + this.description, 70) + '\n' +
373
- ' (default: ' + JSON.stringify(this.defaultValue) + ')';
374
- };
375
-
376
-
377
- /**
378
- * @constructor
379
- */
380
- function BooleanFlag() {
381
- BooleanFlag.super_.apply(this, arguments);
382
- }
383
- util.inherits(BooleanFlag, Flag);
384
-
385
-
386
- BooleanFlag.prototype.parseInput = function(inp) {
387
- if (inp === null) {
388
- return true;
389
- }
390
- inp = inp.toLowerCase();
391
- if (inp === '1' || inp === 'true' || inp == 't') {
392
- return true;
393
- } else if (inp === '0' || inp === 'false' || inp == 'f') {
394
- return false;
395
- } else {
396
- throw Error('Invalid Boolean flag "' + inp + '"')
397
- }
398
- };
399
-
400
-
401
- BooleanFlag.prototype.get = function() {
402
- return !!BooleanFlag.super_.prototype.get.call(this);
403
- };
404
-
405
-
406
- BooleanFlag.prototype.toHelpString = function() {
407
- return wrapText(' --[no]' + this.name + ': ' + this.description, 70) + '\n' +
408
- ' (default: ' + JSON.stringify(this.defaultValue) + ')';
409
- };
410
-
411
-
412
-
413
- /**
414
- * @constructor
415
- */
416
- function IntegerFlag() {
417
- IntegerFlag.super_.apply(this, arguments);
418
- }
419
- util.inherits(IntegerFlag, Flag);
420
-
421
-
422
- IntegerFlag.prototype.parseInput = function(inp) {
423
- if (isNaN(inp) || parseInt(inp, 10) !== Number(inp)) {
424
- throw Error('Invalid Integer flag "' + inp + '"');
425
- }
426
- return Number(inp);
427
- };
428
-
429
-
430
- IntegerFlag.prototype.toHelpString = function() {
431
- return IntegerFlag.super_.prototype.toHelpString.call(this) +
432
- '\n (an integer)';
433
- };
434
-
435
-
436
- /**
437
- * @constructor
438
- */
439
- function NumberFlag() {
440
- NumberFlag.super_.apply(this, arguments);
441
- }
442
- util.inherits(NumberFlag, Flag);
443
-
444
-
445
- NumberFlag.prototype.parseInput = function(inp) {
446
- if (isNaN(inp)) {
447
- throw Error('Invalid Number flag "' + inp + '"');
448
- }
449
- return Number(inp);
450
- };
451
-
452
-
453
- NumberFlag.prototype.toHelpString = function() {
454
- return NumberFlag.super_.prototype.toHelpString.call(this) +
455
- '\n (a number)';
456
- };
457
-
458
-
459
-
460
- /**
461
- * @constructor
462
- */
463
- function StringListFlag() {
464
- StringListFlag.super_.apply(this, arguments);
465
- }
466
- util.inherits(StringListFlag, Flag);
467
-
468
-
469
- StringListFlag.prototype.parseInput = function(inp) {
470
- return inp.split(',');
471
- };
472
-
473
-
474
-
475
- /**
476
- * @constructor
477
- */
478
- function MultiStringFlag() {
479
- MultiStringFlag.super_.apply(this, arguments);
480
- this.currentValue = [];
481
- }
482
- util.inherits(MultiStringFlag, Flag);
483
-
484
-
485
- MultiStringFlag.prototype.set = function(input) {
486
- if (this.validator) this.validator.call(null, input);
487
- this.currentValue.push(input);
488
- this.isSet = true;
489
- };
490
-
491
-
492
-
493
- // Internal flags
494
- //=================
495
-
496
- function registerInternalFlags() {
497
- exports.defineBoolean('help').
498
- setDescription('Shows this help text.').
499
- setSecret(true);
500
- // TODO: --flagsfile
501
- }
502
-
503
- if (registerFlags) {
504
- registerInternalFlags();
505
- }
package/lib/flags_test.js DELETED
@@ -1,214 +0,0 @@
1
-
2
- var flags = require('./flags');
3
- flags.exitOnError = false;
4
-
5
- exports.testGlobalFlagsObject = function(test) {
6
- flags.defineString('one', '111');
7
- flags.defineString('two', '222');
8
- test.deepEqual(global.GLOBAL_FLAGS, flags.FLAGS);
9
- test.done();
10
- };
11
-
12
- exports.testStringFlagParsing = function(test) {
13
- flags.reset();
14
- flags.defineString('one', '111');
15
- flags.defineString('two', '222');
16
- flags.defineString('three', '333');
17
- flags.parse(['--one', '--two=dos']);
18
-
19
- test.strictEqual(null, flags.get('one'));
20
- test.strictEqual('dos', flags.get('two'));
21
- test.strictEqual('333', flags.get('three'));
22
-
23
- test.ok(flags.FLAGS.one.isSet === true);
24
- test.ok(flags.FLAGS.two.isSet === true);
25
- test.ok(flags.FLAGS.three.isSet === false);
26
-
27
- test.done();
28
- };
29
-
30
- exports.testStringFlagParsingWithSpaces = function(test) {
31
- flags.reset();
32
- flags.defineString('one', '111');
33
- flags.defineString('two', '222');
34
- flags.parse(['--one', 'aaa', '--two', 'bbb']);
35
- test.strictEqual('aaa', flags.get('one'));
36
- test.strictEqual('bbb', flags.get('two'));
37
- test.done();
38
- };
39
-
40
- exports.testIntegerFlagParsing = function(test) {
41
- flags.reset();
42
- flags.defineInteger('one', 11);
43
- flags.defineInteger('two', 22);
44
- flags.parse(['--one=111']);
45
- test.strictEqual(111, flags.get('one'));
46
- test.strictEqual(22, flags.get('two'));
47
- test.done();
48
- };
49
-
50
- exports.testIntegerFlagParsing_stringInput = function(test) {
51
- flags.reset();
52
- flags.defineInteger('one', 11);
53
- test.throws(function() {
54
- flags.parse(['--one=xxx']);
55
- });
56
- test.done();
57
- };
58
-
59
- exports.testIntegerFlagParsing_nonIntInput = function(test) {
60
- flags.reset();
61
- flags.defineInteger('one', 11);
62
- test.throws(function() {
63
- flags.parse(['--one=1.123']);
64
- });
65
- test.done();
66
- };
67
-
68
- exports.testNumberFlagParsing = function(test) {
69
- flags.reset();
70
- flags.defineNumber('one', 1.1);
71
- flags.defineNumber('two', 2.2);
72
- flags.parse(['--one=1.234']);
73
- test.strictEqual(1.234, flags.get('one'));
74
- test.strictEqual(2.2, flags.get('two'));
75
- test.done();
76
- };
77
-
78
- exports.testNumberFlagParsing_stringInput = function(test) {
79
- flags.reset();
80
- flags.defineNumber('one', 1.1);
81
- test.throws(function() {
82
- flags.parse(['--one=xxx']);
83
- });
84
- test.done();
85
- };
86
-
87
- exports.testBooleanFlagParsing = function(test) {
88
- flags.reset();
89
- flags.defineBoolean('a');
90
- flags.defineBoolean('b', false);
91
- flags.defineBoolean('c').setDefault(false);
92
- flags.defineBoolean('d', false);
93
- flags.defineBoolean('e').setDefault(true);
94
- flags.defineBoolean('f', true);
95
- flags.defineBoolean('g', true);
96
- flags.defineBoolean('h', true);
97
- flags.defineBoolean('i');
98
- flags.parse(['--a', '--b=true', '--c=t', '--d=1', '--noe', '--f=false',
99
- '--g=0', '--h=f']);
100
- test.strictEqual(true, flags.get('a'));
101
- test.strictEqual(true, flags.get('b'));
102
- test.strictEqual(true, flags.get('c'));
103
- test.strictEqual(true, flags.get('d'));
104
- test.strictEqual(false, flags.get('e'));
105
- test.strictEqual(false, flags.get('f'));
106
- test.strictEqual(false, flags.get('g'));
107
- test.strictEqual(false, flags.get('h'));
108
- test.strictEqual(false, flags.get('i'));
109
- test.done();
110
- };
111
-
112
- exports.testBooleanFlagParsing_badInput = function(test) {
113
- flags.reset();
114
- flags.defineBoolean('a', false);
115
- test.throws(function() {
116
- flags.parse(['--a=xxx']);
117
- });
118
- test.done();
119
- };
120
-
121
- exports.testStringListFlagParsing = function(test) {
122
- flags.reset();
123
- flags.defineStringList('one', []);
124
- flags.parse(['--one=a,b,c,d']);
125
- test.deepEqual(['a', 'b', 'c', 'd'], flags.get('one'));
126
- test.done();
127
- };
128
-
129
- exports.testMultiStringFlagParsing = function(test) {
130
- flags.reset();
131
- flags.defineMultiString('one', []);
132
- flags.parse(['--one=a', '--one=b', '--one=c', '--one=d']);
133
- test.deepEqual(['a', 'b', 'c', 'd'], flags.get('one'));
134
- test.done();
135
- };
136
-
137
- exports.testUnrecognizedFlags = function(test) {
138
- flags.reset();
139
- test.throws(function() {
140
- flags.parse(['--one']);
141
- });
142
- test.done();
143
- };
144
-
145
- exports.testDuplicateFlags = function(test) {
146
- flags.reset();
147
- flags.defineString('one', '');
148
- test.throws(function() {
149
- flags.defineString('one', '');
150
- });
151
- test.done();
152
- };
153
-
154
- exports.testThrowIfDefineAfterParse = function(test) {
155
- flags.reset();
156
- flags.parse([]);
157
- test.throws(function() {
158
- flags.defineString('one', '');
159
- });
160
- test.done();
161
- };
162
-
163
- exports.testValidators = function(test) {
164
- function setUp() {
165
- flags.reset();
166
- flags.defineString('one').setValidator(function(inp) {
167
- if (inp.substr(0, 3) != 'xxx') throw Error('Bad Input');
168
- });
169
- }
170
- setUp();
171
- flags.parse(['--one=xxxyyy']);
172
- setUp();
173
- test.throws(function() {
174
- flags.parse(['--one=yyyxxx']);
175
- });
176
- test.done();
177
- };
178
-
179
- exports.testBreakFlag = function(test) {
180
- flags.reset();
181
- flags.defineString('one', '');
182
- flags.defineString('two', '');
183
- var rv = flags.parse(['--one=2', '--two=3', '--', 'something', 'else']);
184
- test.deepEqual(['something', 'else'], rv);
185
- test.done();
186
- };
187
-
188
- exports.testBreakFlag_nothingElse = function(test) {
189
- flags.reset();
190
- flags.defineString('one', '');
191
- flags.defineString('two', '');
192
- var rv = flags.parse(['--one=2', '--two=3', '--']);
193
- test.deepEqual([], rv);
194
- test.done();
195
- };
196
-
197
- exports.testReturnValue = function(test) {
198
- flags.reset();
199
- flags.defineString('one', '');
200
- flags.defineString('two', '');
201
- var rv = flags.parse(['--one=2', '--two=3']);
202
- test.deepEqual([], rv);
203
- test.done();
204
- };
205
-
206
- exports.testIsSet = function(test) {
207
- flags.reset();
208
- flags.defineInteger('one', 1);
209
- flags.defineInteger('two', 2);
210
- flags.parse(['--one=11']);
211
- test.strictEqual(true, flags.isSet('one'));
212
- test.strictEqual(false, flags.isSet('two'));
213
- test.done();
214
- };