/
command.ts
716 lines (647 loc) · 21.4 KB
/
command.ts
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
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
import {
Dictionary,
assertNotStrictEqual,
RequireDirectoryOptions,
PlatformShim,
} from './typings/common-types.js';
import {isPromise} from './utils/is-promise.js';
import {
applyMiddleware,
commandMiddlewareFactory,
Middleware,
} from './middleware.js';
import {parseCommand, Positional} from './parse-command.js';
import {UsageInstance} from './usage.js';
import {ValidationInstance} from './validation.js';
import {
YargsInstance,
isYargsInstance,
Options,
OptionDefinition,
Context,
Configuration,
Arguments,
DetailedArguments,
} from './yargs-factory.js';
import whichModule from './utils/which-module.js';
const DEFAULT_MARKER = /(^\*)|(^\$0)/;
export type DefinitionOrCommandName = string | CommandHandlerDefinition;
// handles parsing positional arguments,
// and populating argv with said positional
// arguments.
export function command(
yargs: YargsInstance,
usage: UsageInstance,
validation: ValidationInstance,
globalMiddleware: Middleware[] = [],
shim: PlatformShim
) {
const self: CommandInstance = {} as CommandInstance;
let handlers: Dictionary<CommandHandler> = {};
let aliasMap: Dictionary<string> = {};
let defaultCommand: CommandHandler | undefined;
self.addHandler = function addHandler(
cmd: DefinitionOrCommandName | [DefinitionOrCommandName, ...string[]],
description?: string | false,
builder?: CommandBuilder,
handler?: CommandHandlerCallback,
commandMiddleware?: Middleware[],
deprecated?: boolean
) {
let aliases: string[] = [];
const middlewares = commandMiddlewareFactory(commandMiddleware);
handler = handler || (() => {});
// If an array is provided that is all CommandHandlerDefinitions, add
// each handler individually:
if (Array.isArray(cmd)) {
if (isCommandAndAliases(cmd)) {
[cmd, ...aliases] = cmd;
} else {
for (const command of cmd) {
self.addHandler(command);
}
}
} else if (isCommandHandlerDefinition(cmd)) {
let command =
Array.isArray(cmd.command) || typeof cmd.command === 'string'
? cmd.command
: moduleName(cmd);
if (cmd.aliases)
command = ([] as string[]).concat(command).concat(cmd.aliases);
self.addHandler(
command,
extractDesc(cmd),
cmd.builder,
cmd.handler,
cmd.middlewares,
cmd.deprecated
);
return;
} else if (isCommandBuilderDefinition(builder)) {
// Allow a module to be provided as builder, rather than function:
self.addHandler(
[cmd].concat(aliases),
description,
builder.builder,
builder.handler,
builder.middlewares,
builder.deprecated
);
return;
}
// The 'cmd' provided was a string, we apply the command DSL:
// https://github.com/yargs/yargs/blob/master/docs/advanced.md#advanced-topics
if (typeof cmd === 'string') {
// parse positionals out of cmd string
const parsedCommand = parseCommand(cmd);
// remove positional args from aliases only
aliases = aliases.map(alias => parseCommand(alias).cmd);
// check for default and filter out '*'
let isDefault = false;
const parsedAliases = [parsedCommand.cmd].concat(aliases).filter(c => {
if (DEFAULT_MARKER.test(c)) {
isDefault = true;
return false;
}
return true;
});
// standardize on $0 for default command.
if (parsedAliases.length === 0 && isDefault) parsedAliases.push('$0');
// shift cmd and aliases after filtering out '*'
if (isDefault) {
parsedCommand.cmd = parsedAliases[0];
aliases = parsedAliases.slice(1);
cmd = cmd.replace(DEFAULT_MARKER, parsedCommand.cmd);
}
// populate aliasMap
aliases.forEach(alias => {
aliasMap[alias] = parsedCommand.cmd;
});
if (description !== false) {
usage.command(cmd, description, isDefault, aliases, deprecated);
}
handlers[parsedCommand.cmd] = {
original: cmd,
description,
handler,
builder: builder || {},
middlewares,
deprecated,
demanded: parsedCommand.demanded,
optional: parsedCommand.optional,
};
if (isDefault) defaultCommand = handlers[parsedCommand.cmd];
}
};
self.addDirectory = function addDirectory(
dir,
context,
req,
callerFile,
opts
) {
opts = opts || {};
// disable recursion to support nested directories of subcommands
if (typeof opts.recurse !== 'boolean') opts.recurse = false;
// exclude 'json', 'coffee' from require-directory defaults
if (!Array.isArray(opts.extensions)) opts.extensions = ['js'];
// allow consumer to define their own visitor function
const parentVisit =
typeof opts.visit === 'function' ? opts.visit : (o: any) => o;
// call addHandler via visitor function
opts.visit = function visit(obj, joined, filename) {
const visited = parentVisit(obj, joined, filename);
// allow consumer to skip modules with their own visitor
if (visited) {
// check for cyclic reference
// each command file path should only be seen once per execution
if (~context.files.indexOf(joined)) return visited;
// keep track of visited files in context.files
context.files.push(joined);
self.addHandler(visited);
}
return visited;
};
shim.requireDirectory({require: req, filename: callerFile}, dir, opts);
};
// lookup module object from require()d command and derive name
// if module was not require()d and no name given, throw error
function moduleName(obj: CommandHandlerDefinition) {
const mod = whichModule(obj);
if (!mod)
throw new Error(`No command name given for module: ${shim.inspect(obj)}`);
return commandFromFilename(mod.filename);
}
// derive command name from filename
function commandFromFilename(filename: string) {
return shim.path.basename(filename, shim.path.extname(filename));
}
function extractDesc({
describe,
description,
desc,
}: CommandHandlerDefinition) {
for (const test of [describe, description, desc]) {
if (typeof test === 'string' || test === false) return test;
assertNotStrictEqual(test, true as const, shim);
}
return false;
}
self.getCommands = () => Object.keys(handlers).concat(Object.keys(aliasMap));
self.getCommandHandlers = () => handlers;
self.hasDefaultCommand = () => !!defaultCommand;
self.runCommand = function runCommand(
command,
yargs,
parsed,
commandIndex = 0,
helpOnly = false
) {
let aliases = parsed.aliases;
const commandHandler =
handlers[command!] || handlers[aliasMap[command!]] || defaultCommand;
const currentContext = yargs.getContext();
let numFiles = currentContext.files.length;
const parentCommands = currentContext.commands.slice();
// what does yargs look like after the builder is run?
let innerArgv: Arguments | Promise<Arguments> = parsed.argv;
let positionalMap: Dictionary<string[]> = {};
if (command) {
currentContext.commands.push(command);
currentContext.fullCommands.push(commandHandler.original);
}
const builder = commandHandler.builder;
if (isCommandBuilderCallback(builder)) {
// a function can be provided, which builds
// up a yargs chain and possibly returns it.
const builderOutput = builder(yargs.reset(parsed.aliases));
const innerYargs = isYargsInstance(builderOutput) ? builderOutput : yargs;
// A null command indicates we are running the default command,
// if this is the case, we should show the root usage instructions
// rather than the usage instructions for the nested default command:
if (!command) innerYargs.getUsageInstance().unfreeze();
if (shouldUpdateUsage(innerYargs)) {
innerYargs
.getUsageInstance()
.usage(
usageFromParentCommandsCommandHandler(
parentCommands,
commandHandler
),
commandHandler.description
);
}
innerArgv = innerYargs._parseArgs(
null,
undefined,
true,
commandIndex,
helpOnly
);
aliases = (innerYargs.parsed as DetailedArguments).aliases;
} else if (isCommandBuilderOptionDefinitions(builder)) {
// as a short hand, an object can instead be provided, specifying
// the options that a command takes.
const innerYargs = yargs.reset(parsed.aliases);
// A null command indicates we are running the default command,
// if this is the case, we should show the root usage instructions
// rather than the usage instructions for the nested default command:
if (!command) innerYargs.getUsageInstance().unfreeze();
if (shouldUpdateUsage(innerYargs)) {
innerYargs
.getUsageInstance()
.usage(
usageFromParentCommandsCommandHandler(
parentCommands,
commandHandler
),
commandHandler.description
);
}
Object.keys(commandHandler.builder).forEach(key => {
innerYargs.option(key, builder[key]);
});
innerArgv = innerYargs._parseArgs(
null,
undefined,
true,
commandIndex,
helpOnly
);
aliases = (innerYargs.parsed as DetailedArguments).aliases;
}
if (!yargs._hasOutput()) {
positionalMap = populatePositionals(
commandHandler,
innerArgv as Arguments,
currentContext
);
}
// If showHelp() or getHelp() is being run, we should not
// execute middleware or handlers (these may perform expensive operations
// like creating a DB connection).
if (helpOnly) return innerArgv;
const middlewares = globalMiddleware
.slice(0)
.concat(commandHandler.middlewares);
innerArgv = applyMiddleware(innerArgv, yargs, middlewares, true);
// we apply validation post-hoc, so that custom
// checks get passed populated positional arguments.
if (!yargs._hasOutput()) {
const validation = yargs._runValidation(
aliases,
positionalMap,
(yargs.parsed as DetailedArguments).error,
!command
);
if (isPromise(innerArgv)) {
// If the middlware returned a promise, resolve the middleware
// before applying the validation:
innerArgv = innerArgv.then(argv => {
validation(argv);
return argv;
});
} else {
validation(innerArgv);
}
}
if (commandHandler.handler && !yargs._hasOutput()) {
yargs._setHasOutput();
// to simplify the parsing of positionals in commands,
// we temporarily populate '--' rather than _, with arguments
const populateDoubleDash = !!yargs.getOptions().configuration[
'populate--'
];
yargs._postProcess(innerArgv, populateDoubleDash, false, false);
innerArgv = applyMiddleware(innerArgv, yargs, middlewares, false);
if (isPromise(innerArgv)) {
const innerArgvRef = innerArgv;
innerArgv = innerArgv
.then(argv => commandHandler.handler(argv))
.then(() => innerArgvRef);
} else {
const handlerResult = commandHandler.handler(innerArgv);
if (isPromise(handlerResult)) {
const innerArgvRef = innerArgv;
innerArgv = handlerResult.then(() => innerArgvRef);
}
}
yargs.getUsageInstance().cacheHelpMessage();
if (isPromise(innerArgv) && !yargs._hasParseCallback()) {
innerArgv.catch(error => {
try {
yargs.getUsageInstance().fail(null, error);
} catch (_err) {
// If .fail(false) is not set, and no parse cb() has been
// registered, run usage's default fail method.
}
});
}
}
if (command) {
currentContext.commands.pop();
currentContext.fullCommands.pop();
}
numFiles = currentContext.files.length - numFiles;
if (numFiles > 0) currentContext.files.splice(numFiles * -1, numFiles);
return innerArgv;
};
function shouldUpdateUsage(yargs: YargsInstance) {
return (
!yargs.getUsageInstance().getUsageDisabled() &&
yargs.getUsageInstance().getUsage().length === 0
);
}
function usageFromParentCommandsCommandHandler(
parentCommands: string[],
commandHandler: CommandHandler
) {
const c = DEFAULT_MARKER.test(commandHandler.original)
? commandHandler.original.replace(DEFAULT_MARKER, '').trim()
: commandHandler.original;
const pc = parentCommands.filter(c => {
return !DEFAULT_MARKER.test(c);
});
pc.push(c);
return `$0 ${pc.join(' ')}`;
}
self.runDefaultBuilderOn = function (yargs) {
assertNotStrictEqual(defaultCommand, undefined, shim);
if (shouldUpdateUsage(yargs)) {
// build the root-level command string from the default string.
const commandString = DEFAULT_MARKER.test(defaultCommand.original)
? defaultCommand.original
: defaultCommand.original.replace(/^[^[\]<>]*/, '$0 ');
yargs.getUsageInstance().usage(commandString, defaultCommand.description);
}
const builder = defaultCommand.builder;
if (isCommandBuilderCallback(builder)) {
builder(yargs);
} else if (!isCommandBuilderDefinition(builder)) {
Object.keys(builder).forEach(key => {
yargs.option(key, builder[key]);
});
}
};
// transcribe all positional arguments "command <foo> <bar> [apple]"
// onto argv.
function populatePositionals(
commandHandler: CommandHandler,
argv: Arguments,
context: Context
) {
argv._ = argv._.slice(context.commands.length); // nuke the current commands
const demanded = commandHandler.demanded.slice(0);
const optional = commandHandler.optional.slice(0);
const positionalMap: Dictionary<string[]> = {};
validation.positionalCount(demanded.length, argv._.length);
while (demanded.length) {
const demand = demanded.shift()!;
populatePositional(demand, argv, positionalMap);
}
while (optional.length) {
const maybe = optional.shift()!;
populatePositional(maybe, argv, positionalMap);
}
argv._ = context.commands.concat(argv._.map(a => '' + a));
postProcessPositionals(
argv,
positionalMap,
self.cmdToParseOptions(commandHandler.original)
);
return positionalMap;
}
function populatePositional(
positional: Positional,
argv: Arguments,
positionalMap: Dictionary<string[]>
) {
const cmd = positional.cmd[0];
if (positional.variadic) {
positionalMap[cmd] = argv._.splice(0).map(String);
} else {
if (argv._.length) positionalMap[cmd] = [String(argv._.shift())];
}
}
// we run yargs-parser against the positional arguments
// applying the same parsing logic used for flags.
function postProcessPositionals(
argv: Arguments,
positionalMap: Dictionary<string[]>,
parseOptions: Positionals
) {
// combine the parsing hints we've inferred from the command
// string with explicitly configured parsing hints.
const options = Object.assign({}, yargs.getOptions());
options.default = Object.assign(parseOptions.default, options.default);
for (const key of Object.keys(parseOptions.alias)) {
options.alias[key] = (options.alias[key] || []).concat(
parseOptions.alias[key]
);
}
options.array = options.array.concat(parseOptions.array);
options.config = {}; // don't load config when processing positionals.
const unparsed: string[] = [];
Object.keys(positionalMap).forEach(key => {
positionalMap[key].map(value => {
if (options.configuration['unknown-options-as-args'])
options.key[key] = true;
unparsed.push(`--${key}`);
unparsed.push(value);
});
});
// short-circuit parse.
if (!unparsed.length) return;
const config: Configuration = Object.assign({}, options.configuration, {
'populate--': true,
});
const parsed = shim.Parser.detailed(
unparsed,
Object.assign({}, options, {
configuration: config,
})
);
if (parsed.error) {
yargs.getUsageInstance().fail(parsed.error.message, parsed.error);
} else {
// only copy over positional keys (don't overwrite
// flag arguments that were already parsed).
const positionalKeys = Object.keys(positionalMap);
Object.keys(positionalMap).forEach(key => {
positionalKeys.push(...parsed.aliases[key]);
});
Object.keys(parsed.argv).forEach(key => {
if (positionalKeys.indexOf(key) !== -1) {
// any new aliases need to be placed in positionalMap, which
// is used for validation.
if (!positionalMap[key]) positionalMap[key] = parsed.argv[key];
argv[key] = parsed.argv[key];
}
});
}
}
self.cmdToParseOptions = function (cmdString) {
const parseOptions: Positionals = {
array: [],
default: {},
alias: {},
demand: {},
};
const parsed = parseCommand(cmdString);
parsed.demanded.forEach(d => {
const [cmd, ...aliases] = d.cmd;
if (d.variadic) {
parseOptions.array.push(cmd);
parseOptions.default[cmd] = [];
}
parseOptions.alias[cmd] = aliases;
parseOptions.demand[cmd] = true;
});
parsed.optional.forEach(o => {
const [cmd, ...aliases] = o.cmd;
if (o.variadic) {
parseOptions.array.push(cmd);
parseOptions.default[cmd] = [];
}
parseOptions.alias[cmd] = aliases;
});
return parseOptions;
};
self.reset = () => {
handlers = {};
aliasMap = {};
defaultCommand = undefined;
return self;
};
// used by yargs.parse() to freeze
// the state of commands such that
// we can apply .parse() multiple times
// with the same yargs instance.
const frozens: FrozenCommandInstance[] = [];
self.freeze = () => {
frozens.push({
handlers,
aliasMap,
defaultCommand,
});
};
self.unfreeze = () => {
const frozen = frozens.pop();
assertNotStrictEqual(frozen, undefined, shim);
({handlers, aliasMap, defaultCommand} = frozen);
};
return self;
}
/** Instance of the command module. */
export interface CommandInstance {
addDirectory(
dir: string,
context: Context,
req: Function,
callerFile: string,
opts?: RequireDirectoryOptions
): void;
addHandler(
cmd: string | CommandHandlerDefinition | DefinitionOrCommandName[],
description?: CommandHandler['description'],
builder?: CommandBuilderDefinition | CommandBuilder,
handler?: CommandHandlerCallback,
commandMiddleware?: Middleware[],
deprecated?: boolean
): void;
cmdToParseOptions(cmdString: string): Positionals;
freeze(): void;
getCommandHandlers(): Dictionary<CommandHandler>;
getCommands(): string[];
hasDefaultCommand(): boolean;
reset(): CommandInstance;
runCommand(
command: string | null,
yargs: YargsInstance,
parsed: DetailedArguments,
commandIndex: number,
helpOnly: boolean
): Arguments | Promise<Arguments>;
runDefaultBuilderOn(yargs: YargsInstance): void;
unfreeze(): void;
}
export interface CommandHandlerDefinition
extends Partial<
Pick<
CommandHandler,
'deprecated' | 'description' | 'handler' | 'middlewares'
>
> {
aliases?: string[];
builder?: CommandBuilder | CommandBuilderDefinition;
command?: string | string[];
desc?: CommandHandler['description'];
describe?: CommandHandler['description'];
}
export interface CommandBuilderDefinition {
builder?: CommandBuilder;
deprecated?: boolean;
handler: CommandHandlerCallback;
middlewares?: Middleware[];
}
export function isCommandBuilderDefinition(
builder?: CommandBuilder | CommandBuilderDefinition
): builder is CommandBuilderDefinition {
return (
typeof builder === 'object' &&
!!(builder as CommandBuilderDefinition).builder &&
typeof (builder as CommandBuilderDefinition).handler === 'function'
);
}
export interface CommandHandlerCallback {
(argv: Arguments): any;
}
export interface CommandHandler {
builder: CommandBuilder;
demanded: Positional[];
deprecated?: boolean;
description?: string | false;
handler: CommandHandlerCallback;
middlewares: Middleware[];
optional: Positional[];
original: string;
}
// To be completed later with other CommandBuilder flavours
export type CommandBuilder =
| CommandBuilderCallback
| Dictionary<OptionDefinition>;
interface CommandBuilderCallback {
(y: YargsInstance): YargsInstance | void;
}
function isCommandAndAliases(
cmd: DefinitionOrCommandName[]
): cmd is [CommandHandlerDefinition, ...string[]] {
if (cmd.every(c => typeof c === 'string')) {
return true;
} else {
return false;
}
}
export function isCommandBuilderCallback(
builder: CommandBuilder
): builder is CommandBuilderCallback {
return typeof builder === 'function';
}
function isCommandBuilderOptionDefinitions(
builder: CommandBuilder
): builder is Dictionary<OptionDefinition> {
return typeof builder === 'object';
}
export function isCommandHandlerDefinition(
cmd: DefinitionOrCommandName | [DefinitionOrCommandName, ...string[]]
): cmd is CommandHandlerDefinition {
return typeof cmd === 'object' && !Array.isArray(cmd);
}
interface Positionals extends Pick<Options, 'alias' | 'array' | 'default'> {
demand: Dictionary<boolean>;
}
type FrozenCommandInstance = {
handlers: Dictionary<CommandHandler>;
aliasMap: Dictionary<string>;
defaultCommand: CommandHandler | undefined;
};