-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathevent-handler.ts
More file actions
608 lines (500 loc) · 16.1 KB
/
event-handler.ts
File metadata and controls
608 lines (500 loc) · 16.1 KB
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
import { type Command, getCommandNameWithParents } from './command-core';
import type {
BuilderConfig,
GenericBuilderInternals,
OptionType,
OutputType,
ProcessedBuilderConfig,
ProcessedOptions,
} from './option-builder';
export type CommandHelpEvent = {
type: 'command_help';
name: string | undefined;
description: string | undefined;
command: Command;
globals?: ProcessedOptions<Record<string, GenericBuilderInternals>>;
};
export type GlobalHelpEvent = {
type: 'global_help';
description: string | undefined;
name: string | undefined;
commands: Command[];
globals?: ProcessedOptions<Record<string, GenericBuilderInternals>>;
};
export type MissingArgsEvent = {
type: 'error';
violation: 'missing_args_error';
name: string | undefined;
description: string | undefined;
command: Command | 'globals';
missing: [string[], ...string[][]];
};
export type UnrecognizedArgsEvent = {
type: 'error';
violation: 'unrecognized_args_error';
name: string | undefined;
description: string | undefined;
command: Command;
unrecognized: [string, ...string[]];
};
export type UnknownCommandEvent = {
type: 'error';
violation: 'unknown_command_error';
name: string | undefined;
description: string | undefined;
commands: Command[];
offender: string;
};
export type UnknownSubcommandEvent = {
type: 'error';
violation: 'unknown_subcommand_error';
name: string | undefined;
description: string | undefined;
command: Command;
offender: string;
};
export type UnknownErrorEvent = {
type: 'error';
violation: 'unknown_error';
name: string | undefined;
description: string | undefined;
error: unknown;
};
export type VersionEvent = {
type: 'version';
name: string | undefined;
description: string | undefined;
};
export type GenericValidationViolation =
| 'above_max'
| 'below_min'
| 'expected_int'
| 'invalid_boolean_syntax'
| 'invalid_string_syntax'
| 'invalid_number_syntax'
| 'invalid_number_value'
| 'enum_violation';
export type ValidationViolation = BroCliEvent extends infer Event
? Event extends { violation: string } ? Event['violation'] : never
: never;
export type ValidationErrorEvent = {
type: 'error';
violation: GenericValidationViolation;
name: string | undefined;
description: string | undefined;
command: Command | 'globals';
option: ProcessedBuilderConfig;
offender: {
namePart?: string;
dataPart?: string;
};
};
export type BroCliEvent =
| CommandHelpEvent
| GlobalHelpEvent
| MissingArgsEvent
| UnrecognizedArgsEvent
| UnknownCommandEvent
| UnknownSubcommandEvent
| ValidationErrorEvent
| VersionEvent
| UnknownErrorEvent;
export type BroCliEventType = BroCliEvent['type'];
const getOptionTypeText = (option: BuilderConfig) => {
let result = '';
if (option.optionTypeText) {
result = option.optionTypeText;
} else {
switch (option.type) {
case 'boolean':
result = '';
break;
case 'number': {
if ((option.minVal ?? option.maxVal) !== undefined) {
let text = '';
if (option.isInt) text = text + `integer `;
if (option.minVal !== undefined) text = text + `[${option.minVal};`;
else text = text + `(∞;`;
if (option.maxVal !== undefined) text = text + `${option.maxVal}]`;
else text = text + `∞)`;
result = text;
break;
}
if (option.isInt) {
result = 'integer';
break;
}
result = 'number';
break;
}
case 'string': {
if (option.enumVals) {
result = '[ ' + option.enumVals.join(' | ') + ' ]';
break;
}
result = 'string';
break;
}
case 'positional': {
result = `${option.isRequired ? '<' : '['}${option.enumVals ? option.enumVals.join('|') : option.name}${
option.isRequired ? '>' : ']'
}`;
break;
}
}
}
if (option.isRequired && option.type !== 'positional') result = '!' + (result.length ? '' + result : ' ');
return result;
};
/**
* Return `true` if your handler processes the event
*
* Return `false` to process event with a built-in handler
*
* @param options - Global options. `undefined` if globals failed to parse.
*/
export type EventHandler<TOpts = unknown> = (
event: BroCliEvent,
/** Global options. `undefined` if globals failed to parse. */
options?: TOpts | undefined,
) => boolean | Promise<boolean>;
export const defaultEventHandler: EventHandler = async (event) => {
switch (event.type) {
case 'command_help': {
const command = event.command;
const commandName = getCommandNameWithParents(command);
const cliName = event.name;
const desc = command.desc ?? command.shortDesc;
const subs = command.subcommands?.filter((s) => !s.hidden);
const subcommands = subs && subs.length ? subs : undefined;
const defaultGlobals = [
{
config: {
name: '--help',
aliases: ['-h'],
type: 'boolean' as OptionType,
description: `help for ${commandName}`,
default: undefined,
},
$output: undefined as any as boolean,
},
{
config: {
name: '--version',
aliases: ['-v'],
type: 'boolean' as OptionType,
description: `version${cliName ? ` for ${cliName}` : ''}`,
default: undefined,
},
$output: undefined as any as boolean,
},
];
const globals: {
config: ProcessedBuilderConfig;
$output: OutputType;
}[] = event.globals
? [...Object.values(event.globals), ...defaultGlobals]
: defaultGlobals;
if (desc !== undefined) {
console.log(`\n${desc}`);
}
const opts = Object.values(command.options ?? {} as Exclude<typeof command.options, undefined>).filter((opt) =>
!opt.config.isHidden
);
const positionals = opts.filter((opt) => opt.config.type === 'positional');
const options = [...opts.filter((opt) => opt.config.type !== 'positional'), ...globals];
console.log('\nUsage:');
if (command.handler) {
console.log(
` ${cliName ? cliName + ' ' : ''}${commandName}${
positionals.length
? ' '
+ positionals.map(({ config: p }) => getOptionTypeText(p)).join(' ')
: ''
} [flags]`,
);
} else console.log(` ${cliName ? cliName + ' ' : ''}${commandName} [command]`);
if (command.aliases) {
console.log(`\nAliases:`);
console.log(` ${[command.name, ...command.aliases].join(', ')}`);
}
if (subcommands) {
console.log('\nAvailable Commands:');
const padding = 3;
const maxLength = subcommands.reduce((p, e) => e.name.length > p ? e.name.length : p, 0);
const paddedLength = maxLength + padding;
const preDescPad = 2 + paddedLength;
const data = subcommands.map((s) =>
` ${s.name.padEnd(paddedLength)}${
(() => {
const description = s.shortDesc ?? s.desc;
if (!description?.length) return '';
const split = description.split('\n');
const first = split.shift()!;
const final = [first, ...split.map((s) => ''.padEnd(preDescPad) + s)].join('\n');
return final;
})()
}`
)
.join('\n');
console.log(data);
}
if (options.length) {
const aliasLength = options.reduce((p, e) => {
const currentLength = e.config.aliases.reduce((pa, a) => pa + a.length, 0)
+ ((e.config.aliases.length - 1) * 2) + 1; // Names + coupling symbols ", " + ending coma
return currentLength > p ? currentLength : p;
}, 0);
const paddedAliasLength = aliasLength > 0 ? aliasLength + 1 : 0;
const nameLength = options.reduce((p, e) => {
const typeLen = getOptionTypeText(e.config).length;
const length = typeLen > 0 ? e.config.name.length + 1 + typeLen : e.config.name.length;
return length > p ? length : p;
}, 0) + 3;
const preDescPad = paddedAliasLength + nameLength + 2;
const data = options.map(({ config: opt }) =>
` ${`${opt.aliases.length ? opt.aliases.join(', ') + ',' : ''}`.padEnd(paddedAliasLength)}${
`${opt.name}${
(() => {
const typeText = getOptionTypeText(opt);
return typeText.length ? ' ' + typeText : '';
})()
}`.padEnd(nameLength)
}${
(() => {
if (!opt.description?.length) {
return opt.default !== undefined
? `default: ${JSON.stringify(opt.default)}`
: '';
}
const split = opt.description.split('\n');
const first = split.shift()!;
const def = opt.default !== undefined ? ` (default: ${JSON.stringify(opt.default)})` : '';
const final = [first, ...split.map((s) => ''.padEnd(preDescPad) + s)].join('\n') + def;
return final;
})()
}`
).join('\n');
console.log('\nFlags:');
console.log(data);
}
if (subcommands) {
console.log(
`\nUse "${
cliName ? cliName + ' ' : ''
}${commandName} [command] --help" for more information about a command.\n`,
);
}
return true;
}
case 'global_help': {
const cliName = event.name;
const desc = event.description;
const commands = event.commands.filter((c) => !c.hidden);
const defaultGlobals = [
{
config: {
name: '--help',
aliases: ['-h'],
type: 'boolean' as OptionType,
description: `help${cliName ? ` for ${cliName}` : ''}`,
default: undefined,
},
$output: undefined as any as boolean,
},
{
config: {
name: '--version',
aliases: ['-v'],
type: 'boolean' as OptionType,
description: `version${cliName ? ` for ${cliName}` : ''}`,
default: undefined,
},
$output: undefined as any as boolean,
},
];
const globals = event.globals
? [...defaultGlobals, ...Object.values(event.globals)]
: defaultGlobals;
if (desc !== undefined) {
console.log(`${desc}\n`);
}
console.log('Usage:');
console.log(` ${cliName ? cliName + ' ' : ''}[command]`);
if (commands.length) {
console.log('\nAvailable Commands:');
const padding = 3;
const maxLength = commands.reduce((p, e) => e.name.length > p ? e.name.length : p, 0);
const paddedLength = maxLength + padding;
const data = commands.map((c) =>
` ${c.name.padEnd(paddedLength)}${
(() => {
const desc = c.shortDesc ?? c.desc;
if (!desc?.length) return '';
const split = desc.split('\n');
const first = split.shift()!;
const final = [first, ...split.map((s) => ''.padEnd(paddedLength + 2) + s)].join('\n');
return final;
})()
}`
)
.join('\n');
console.log(data);
} else {
console.log('\nNo available commands.');
}
const aliasLength = globals.reduce((p, e) => {
const currentLength = e.config.aliases.reduce((pa, a) => pa + a.length, 0)
+ ((e.config.aliases.length - 1) * 2) + 1; // Names + coupling symbols ", " + ending coma
return currentLength > p ? currentLength : p;
}, 0);
const paddedAliasLength = aliasLength > 0 ? aliasLength + 1 : 0;
const nameLength = globals.reduce((p, e) => {
const typeLen = getOptionTypeText(e.config).length;
const length = typeLen > 0 ? e.config.name.length + 1 + typeLen : e.config.name.length;
return length > p ? length : p;
}, 0) + 3;
const preDescPad = paddedAliasLength + nameLength + 2;
const gData = globals.map(({ config: opt }) =>
` ${`${opt.aliases.length ? opt.aliases.join(', ') + ',' : ''}`.padEnd(paddedAliasLength)}${
`${opt.name}${
(() => {
const typeText = getOptionTypeText(opt);
return typeText.length ? ' ' + typeText : '';
})()
}`.padEnd(nameLength)
}${
(() => {
if (!opt.description?.length) {
return opt.default !== undefined
? `default: ${JSON.stringify(opt.default)}`
: '';
}
const split = opt.description.split('\n');
const first = split.shift()!;
const def = opt.default !== undefined ? ` (default: ${JSON.stringify(opt.default)})` : '';
const final = [first, ...split.map((s) => ''.padEnd(preDescPad) + s)].join('\n') + def;
return final;
})()
}`
).join('\n');
console.log('\nFlags:');
console.log(gData);
return true;
}
case 'version': {
return true;
}
case 'error': {
let msg: string;
switch (event.violation) {
case 'above_max': {
const matchedName = event.offender.namePart;
const data = event.offender.dataPart;
const option = event.option;
const max = option.maxVal!;
msg =
`Invalid value: number type argument '${matchedName}' expects maximal value of ${max} as an input, got: ${data}`;
break;
}
case 'below_min': {
const matchedName = event.offender.namePart;
const data = event.offender.dataPart;
const option = event.option;
const min = option.minVal;
msg =
`Invalid value: number type argument '${matchedName}' expects minimal value of ${min} as an input, got: ${data}`;
break;
}
case 'expected_int': {
const matchedName = event.offender.namePart;
const data = event.offender.dataPart;
msg = `Invalid value: number type argument '${matchedName}' expects an integer as an input, got: ${data}`;
break;
}
case 'invalid_boolean_syntax': {
const matchedName = event.offender.namePart;
const data = event.offender.dataPart;
msg =
`Invalid syntax: boolean type argument '${matchedName}' must have it's value passed in the following formats: ${matchedName}=<value> | ${matchedName} <value> | ${matchedName}.\nAllowed values: true, false, 0, 1`;
break;
}
case 'invalid_string_syntax': {
const matchedName = event.offender.namePart;
msg =
`Invalid syntax: string type argument '${matchedName}' must have it's value passed in the following formats: ${matchedName}=<value> | ${matchedName} <value>`;
break;
}
case 'invalid_number_syntax': {
const matchedName = event.offender.namePart;
msg =
`Invalid syntax: number type argument '${matchedName}' must have it's value passed in the following formats: ${matchedName}=<value> | ${matchedName} <value>`;
break;
}
case 'invalid_number_value': {
const matchedName = event.offender.namePart;
const data = event.offender.dataPart;
msg = `Invalid value: number type argument '${matchedName}' expects a number as an input, got: ${data}`;
break;
}
case 'enum_violation': {
const matchedName = event.offender.namePart;
const data = event.offender.dataPart;
const option = event.option;
const values = option.enumVals!;
msg = option.type === 'positional'
? `Invalid value: value for the positional argument '${option.name}' must be either one of the following: ${
values.join(', ')
}; Received: ${data}`
: `Invalid value: value for the argument '${matchedName}' must be either one of the following: ${
values.join(', ')
}; Received: ${data}`;
break;
}
case 'unknown_command_error': {
const msg = `Unknown command: '${event.offender}'.\nType '--help' to get help on the cli.`;
console.error(msg);
return true;
}
case 'unknown_subcommand_error': {
const cName = getCommandNameWithParents(event.command);
const msg =
`Unknown command: ${cName} ${event.offender}.\nType '${cName} --help' to get the help on command.`;
console.error(msg);
return true;
}
case 'missing_args_error': {
const { missing: missingOpts, command } = event;
msg = command === 'globals'
? `Missing`
: `Command '${command.name}' is missing` + ` following required options: ${
missingOpts.map((opt) => {
const name = opt.shift()!;
const aliases = opt;
if (aliases.length) return `${name} [${aliases.join(', ')}]`;
return name;
}).join(', ')
}`;
break;
}
case 'unrecognized_args_error': {
const { command, unrecognized } = event;
msg = `Unrecognized options for command '${command.name}': ${unrecognized.join(', ')}`;
break;
}
case 'unknown_error': {
const e = event.error;
console.error(typeof e === 'object' && e !== null && 'message' in e ? e.message : e);
return true;
}
}
console.error(msg);
return true;
}
}
// @ts-expect-error
return false;
};
export const eventHandlerWrapper =
<TOpts>(customEventHandler: EventHandler<TOpts>) => async (event: BroCliEvent, options: TOpts) =>
await customEventHandler(event, options) ? true : await defaultEventHandler(event, options);