-
Notifications
You must be signed in to change notification settings - Fork 278
/
command.js
executable file
·577 lines (494 loc) · 11.3 KB
/
command.js
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
'use strict';
/**
* Module dependencies.
*/
var EventEmitter = require('events').EventEmitter;
var Option = require('./option');
var VorpalUtil = require('./util');
var _ = require('lodash');
/**
* Command prototype.
*/
var command = Command.prototype;
/**
* Expose `Command`.
*/
module.exports = exports = Command;
/**
* Initialize a new `Command` instance.
*
* @param {String} name
* @param {Vorpal} parent
* @return {Command}
* @api public
*/
function Command(name, parent) {
if (!(this instanceof Command)) {
return new Command();
}
this.commands = [];
this.options = [];
this._args = [];
this._aliases = [];
this._name = name;
this._relay = false;
this._hidden = false;
this._parent = parent;
this._mode = false;
this._catch = false;
this._help = undefined;
this._init = undefined;
this._after = undefined;
this._allowUnknownOptions = false;
}
/**
* Registers an option for given command.
*
* @param {String} flags
* @param {String} description
* @param {Function} fn
* @param {String} defaultValue
* @return {Command}
* @api public
*/
command.option = function (flags, description, autocomplete) {
var self = this;
var option = new Option(flags, description, autocomplete);
var oname = option.name();
var name = _camelcase(oname);
var defaultValue;
// preassign default value only for --no-*, [optional], or <required>
if (option.bool === false || option.optional || option.required) {
// when --no-* we make sure default is true
if (option.bool === false) {
defaultValue = true;
}
// preassign only if we have a default
if (defaultValue !== undefined) {
self[name] = defaultValue;
}
}
// register the option
this.options.push(option);
// when it's passed assign the value
// and conditionally invoke the callback
this.on(oname, function (val) {
// unassigned or bool
if (typeof self[name] === 'boolean' || typeof self[name] === 'undefined') {
// if no value, bool true, and we have a default, then use it!
if (val === null) {
self[name] = option.bool ? defaultValue || true : false;
} else {
self[name] = val;
}
} else if (val !== null) {
// reassign
self[name] = val;
}
});
return this;
};
/**
* Defines an action for a given command.
*
* @param {Function} fn
* @return {Command}
* @api public
*/
command.action = function (fn) {
var self = this;
self._fn = fn;
return this;
};
/**
* Let's you compose other funtions to extend the command.
*
* @param {Function} fn
* @return {Command}
* @api public
*/
command.use = function (fn) {
return fn(this);
};
/**
* Defines a function to validate arguments
* before action is performed. Arguments
* are valid if no errors are thrown from
* the function.
*
* @param fn
* @returns {Command}
* @api public
*/
command.validate = function (fn) {
var self = this;
self._validate = fn;
return this;
};
/**
* Defines a function to be called when the
* command is canceled.
*
* @param fn
* @returns {Command}
* @api public
*/
command.cancel = function (fn) {
this._cancel = fn;
return this;
};
/**
* Defines a method to be called when
* the command set has completed.
*
* @param {Function} fn
* @return {Command}
* @api public
*/
command.done = function (fn) {
this._done = fn;
return this;
};
/**
* Defines tabbed auto-completion
* for the given command. Favored over
* deprecated command.autocompletion.
*
* @param {Function} fn
* @return {Command}
* @api public
*/
command.autocomplete = function (obj) {
this._autocomplete = obj;
return this;
};
/**
* Defines tabbed auto-completion rules
* for the given command.
*
* @param {Function} fn
* @return {Command}
* @api public
*/
command.autocompletion = function (param) {
this._parent._useDeprecatedAutocompletion = true;
if (!_.isFunction(param) && !_.isObject(param)) {
throw new Error('An invalid object type was passed into the first parameter of command.autocompletion: function expected.');
}
this._autocompletion = param;
return this;
};
/**
* Defines an init action for a mode command.
*
* @param {Function} fn
* @return {Command}
* @api public
*/
command.init = function (fn) {
var self = this;
if (self._mode !== true) {
throw Error('Cannot call init from a non-mode action.');
}
self._init = fn;
return this;
};
/**
* Defines a prompt delimiter for a
* mode once entered.
*
* @param {String} delimiter
* @return {Command}
* @api public
*/
command.delimiter = function (delimiter) {
this._delimiter = delimiter;
return this;
};
/**
* Sets args for static typing of options
* using minimist.
*
* @param {Object} types
* @return {Command}
* @api public
*/
command.types = function (types) {
var supported = ['string', 'boolean'];
for (var item in types) {
if (supported.indexOf(item) === -1) {
throw new Error('An invalid type was passed into command.types(): ' + item);
}
types[item] = !_.isArray(types[item]) ? [types[item]] : types[item];
}
this._types = types;
return this;
};
/**
* Defines an alias for a given command.
*
* @param {String} alias
* @return {Command}
* @api public
*/
command.alias = function () {
var self = this;
for (var i = 0; i < arguments.length; ++i) {
var alias = arguments[i];
if (_.isArray(alias)) {
for (var j = 0; j < alias.length; ++j) {
this.alias(alias[j]);
}
return this;
}
this._parent.commands.forEach(function (cmd) {
if (!_.isEmpty(cmd._aliases)) {
if (_.includes(cmd._aliases, alias)) {
var msg = 'Duplicate alias "' + alias + '" for command "' + self._name + '" detected. Was first reserved by command "' + cmd._name + '".';
throw new Error(msg);
}
}
});
this._aliases.push(alias);
}
return this;
};
/**
* Defines description for given command.
*
* @param {String} str
* @return {Command}
* @api public
*/
command.description = function (str) {
if (arguments.length === 0) {
return this._description;
}
this._description = str;
return this;
};
/**
* Removes self from Vorpal instance.
*
* @return {Command}
* @api public
*/
command.remove = function () {
var self = this;
this._parent.commands = _.reject(this._parent.commands, function (command) {
if (command._name === self._name) {
return true;
}
});
return this;
};
/**
* Returns the commands arguments as string.
*
* @param {String} desc
* @return {String}
* @api public
*/
command.arguments = function (desc) {
return this._parseExpectedArgs(desc.split(/ +/));
};
/**
* Returns the help info for given command.
*
* @return {String}
* @api public
*/
command.helpInformation = function () {
var desc = [];
var cmdName = this._name;
var alias = '';
if (this._description) {
desc = [' ' + this._description, ''];
}
if (this._aliases.length > 0) {
alias = ' Alias: ' + this._aliases.join(' | ') + '\n';
}
var usage = ['', ' Usage: ' + cmdName + ' ' + this.usage(), ''];
var cmds = [];
var help = String(this.optionHelp().replace(/^/gm, ' '));
var options = [' Options:', '', help, ''];
var res = usage.concat(cmds).concat(alias).concat(desc).concat(options).join('\n');
res = res.replace(/\n\n\n/g, '\n\n');
return res;
};
/**
* Doesn't show command in the help menu.
*
* @return {Command}
* @api public
*/
command.hidden = function () {
this._hidden = true;
return this;
};
/**
* Allows undeclared options to be passed in with the command.
*
* @param {Boolean} [allowUnknownOptions=true]
* @return {Command}
* @api public
*/
command.allowUnknownOptions = function () {
var allowUnknownOptions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true;
allowUnknownOptions = allowUnknownOptions === "false" ? false : allowUnknownOptions;
this._allowUnknownOptions = !!allowUnknownOptions;
return this;
};
/**
* Returns the command usage string for help.
*
* @param {String} str
* @return {String}
* @api public
*/
command.usage = function (str) {
var args = this._args.map(function (arg) {
return VorpalUtil.humanReadableArgName(arg);
});
var usage = '[options]' + (this.commands.length ? ' [command]' : '') + (this._args.length ? ' ' + args.join(' ') : '');
if (arguments.length === 0) {
return this._usage || usage;
}
this._usage = str;
return this;
};
/**
* Returns the help string for the command's options.
*
* @return {String}
* @api public
*/
command.optionHelp = function () {
var width = this._largestOptionLength();
// Prepend the help information
return [VorpalUtil.pad('--help', width) + ' output usage information'].concat(this.options.map(function (option) {
return VorpalUtil.pad(option.flags, width) + ' ' + option.description;
})).join('\n');
};
/**
* Returns the length of the longest option.
*
* @return {Integer}
* @api private
*/
command._largestOptionLength = function () {
return this.options.reduce(function (max, option) {
return Math.max(max, option.flags.length);
}, 0);
};
/**
* Adds a custom handling for the --help flag.
*
* @param {Function} fn
* @return {Command}
* @api public
*/
command.help = function (fn) {
if (_.isFunction(fn)) {
this._help = fn;
}
return this;
};
/**
* Edits the raw command string before it
* is executed.
*
* @param {String} str
* @return {String} str
* @api public
*/
command.parse = function (fn) {
if (_.isFunction(fn)) {
this._parse = fn;
}
return this;
};
/**
* Adds a command to be executed after command completion.
*
* @param {Function} fn
* @return {Command}
* @api public
*/
command.after = function (fn) {
if (_.isFunction(fn)) {
this._after = fn;
}
return this;
};
/**
* Parses and returns expected command arguments.
*
* @param {String} args
* @return {Array}
* @api private
*/
command._parseExpectedArgs = function (args) {
if (!args.length) {
return;
}
var self = this;
args.forEach(function (arg) {
var argDetails = {
required: false,
name: '',
variadic: false
};
switch (arg[0]) {
case '<':
argDetails.required = true;
argDetails.name = arg.slice(1, -1);
break;
case '[':
argDetails.name = arg.slice(1, -1);
break;
default:
break;
}
if (argDetails.name.length > 3 && argDetails.name.slice(-3) === '...') {
argDetails.variadic = true;
argDetails.name = argDetails.name.slice(0, -3);
}
if (argDetails.name) {
self._args.push(argDetails);
}
});
// If the user entered args in a weird order,
// properly sequence them.
if (self._args.length > 1) {
self._args = self._args.sort(function (argu1, argu2) {
if (argu1.required && !argu2.required) {
return -1;
} else if (argu2.required && !argu1.required) {
return 1;
} else if (argu1.variadic && !argu2.variadic) {
return 1;
} else if (argu2.variadic && !argu1.variadic) {
return -1;
}
return 0;
});
}
return;
};
/**
* Converts string to camel case.
*
* @param {String} flag
* @return {String}
* @api private
*/
function _camelcase(flag) {
return flag.split('-').reduce(function (str, word) {
return str + word[0].toUpperCase() + word.slice(1);
});
}
/**
* Make command an EventEmitter.
*/
command.__proto__ = EventEmitter.prototype;