-
-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathkernel.ts
809 lines (705 loc) · 21.4 KB
/
kernel.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
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
/*
* @adonisjs/ace
*
* (c) AdonisJS
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
import Hooks from '@poppinss/hooks'
import { cliui } from '@poppinss/cliui'
import { Prompt } from '@poppinss/prompts'
import { distance } from 'fastest-levenshtein'
import { RuntimeException } from '@poppinss/utils'
import debug from './debug.js'
import { Parser } from './parser.js'
import * as errors from './errors.js'
import { ListCommand } from './commands/list.js'
import { BaseCommand } from './commands/base.js'
import { sortAlphabetically } from './helpers.js'
import { ListLoader } from './loaders/list_loader.js'
import { ExceptionHandler } from './exception_handler.js'
import type {
Flag,
UIPrimitives,
FlagListener,
LoadedHookArgs,
CommandMetaData,
LoadersContract,
LoadingHookArgs,
FindingHookArgs,
ExecutedHookArgs,
ExecutorContract,
LoadedHookHandler,
AllowedInfoValues,
ExecutingHookArgs,
LoadingHookHandler,
FindingHookHandler,
AbstractBaseCommand,
ExecutedHookHandler,
ExecutingHookHandler,
} from './types.js'
/**
* The Ace kernel manages the registration and execution of commands.
*
* The kernel is the main entry point of a console application, and
* is tailored for a standard CLI environment.
*/
export class Kernel<Command extends AbstractBaseCommand> {
errorHandler: {
render(error: unknown, kernel: Kernel<any>): Promise<any>
} = new ExceptionHandler()
/**
* The default executor for creating command's instance
* and running them
*/
static commandExecutor: ExecutorContract<typeof BaseCommand> = {
create(command, parsedArgs, kernel) {
return new command(kernel, parsedArgs, kernel.ui, kernel.prompt)
},
run(command) {
return command.exec()
},
}
/**
* The default command to use when creating kernel instance
* via "static create" method.
*/
static defaultCommand: typeof BaseCommand = ListCommand
/**
* Creates an instance of kernel with the default executor
* and default command
*/
static create() {
return new Kernel<typeof BaseCommand>(this.defaultCommand, this.commandExecutor)
}
/**
* Listeners for CLI options. Executed for the main command
* only
*/
#optionListeners: Map<string, FlagListener<Command>> = new Map()
/**
* The global command is used to register global flags applicable
* on all the commands
*/
#globalCommand: typeof BaseCommand = class extends BaseCommand {
static options = {
allowUnknownFlags: true,
}
}
/**
* The default command to run when no command is mentioned. The default
* command will also run when only flags are mentioned.
*/
#defaultCommand: Command
/**
* Available hooks
*/
#hooks: Hooks<{
finding: FindingHookArgs
loading: LoadingHookArgs
loaded: LoadedHookArgs<Command>
executing: ExecutingHookArgs<InstanceType<Command>>
executed: ExecutedHookArgs<InstanceType<Command>>
}> = new Hooks()
/**
* Executors are used to instantiate a command and execute
* the run method.
*/
#executor: ExecutorContract<Command>
/**
* Keeping track of the main command. There are some action (like termination)
* that only the main command can perform
*/
#mainCommand?: InstanceType<Command>
/**
* The current state of kernel. The `running` and `terminated`
* states are only set when kernel takes over the process.
*/
#state: 'idle' | 'booted' | 'running' | 'completed' = 'idle'
/**
* Collection of loaders to use for loading commands
*/
#loaders: (LoadersContract<Command> | (() => Promise<LoadersContract<Command>>))[] = []
/**
* An array of registered namespaces. Sorted alphabetically
*/
#namespaces: string[] = []
/**
* A collection of aliases for the commands. The key is the alias name
* and the value is the command name.
*
* In case of duplicate aliases, the most recent alias will override
* the previous existing alias.
*/
#aliases: Map<string, string> = new Map()
/**
* An collection of expansion arguments and flags set on
* an alias. The key is the alias name and the value is
* everything after it.
*/
#aliasExpansions: Map<string, string[]> = new Map()
/**
* A collection of commands by the command name. This allows us to keep only
* the unique commands and also keep the loader reference to know which
* loader to ask for loading the command.
*/
#commands: Map<string, { metaData: CommandMetaData; loader: LoadersContract<Command> }> =
new Map()
/**
* The exit code for the kernel. The exit code is inferred
* from the main code when not set explicitly.
*/
exitCode?: number
/**
* The UI primitives to use within commands
*/
ui: UIPrimitives = cliui()
/**
* Instance of prompt to display CLI prompts. We share
* a single instance with all the commands. This
* allows trapping prompts for commands executed
* internally.
*/
prompt = new Prompt()
/**
* CLI info map
*/
info: Map<string, AllowedInfoValues> = new Map()
/**
* List of global flags
*/
get flags(): ({ name: string } & Flag)[] {
return this.#globalCommand.flags
}
constructor(defaultCommand: Command, executor: ExecutorContract<Command>) {
this.#defaultCommand = defaultCommand
this.#executor = executor
}
/**
* Process command line arguments. All flags before the command
* name are considered as Node.js argv and all flags after
* the command name are considered as command argv.
*
* The behavior is same as Node.js CLI, where all flags before the
* script file name are Node.js argv.
*/
#processArgv(argv: string[]) {
const commandNameIndex = argv.findIndex((value) => !value.startsWith('-'))
if (commandNameIndex === -1) {
return {
nodeArgv: [],
commandName: null,
commandArgv: argv,
}
}
return {
nodeArgv: argv.slice(0, commandNameIndex),
commandName: argv[commandNameIndex],
commandArgv: argv.slice(commandNameIndex + 1),
}
}
/**
* Creates an instance of a command by parsing and validating
* the command line arguments.
*/
async #create<T extends Command>(Command: T, argv: string | string[]): Promise<InstanceType<T>> {
/**
* Parse CLI argv without global flags. When running commands directly, we
* should not be using global flags anyways
*/
const parsed = new Parser(Command.getParserOptions()).parse(argv)
/**
* Validate the parsed output
*/
Command.validate(parsed)
/**
* Construct command instance using the executor
*/
const commandInstance = await this.#executor.create(Command, parsed, this)
commandInstance.hydrate()
return commandInstance as InstanceType<T>
}
/**
* Executes a given command. The main commands are executed using the
* "execMain" method.
*/
async #exec<T extends Command>(commandName: string, argv: string[]): Promise<InstanceType<T>> {
const Command = await this.find<T>(commandName)
/**
* Expand aliases
*/
const aliasExpansions = this.#aliasExpansions.get(commandName)
if (aliasExpansions) {
argv = aliasExpansions.concat(argv)
debug('expanding alias %O, cli args %O', commandName, argv)
}
const commandInstance = await this.#create<T>(Command, argv)
/**
* Execute the command using the executor
*/
await this.#hooks.runner('executing').run(commandInstance, false)
await this.#executor.run(commandInstance, this)
await this.#hooks.runner('executed').run(commandInstance, false)
return commandInstance
}
/**
* Executes the main command and handles the exceptions by
* reporting them
*/
async #execMain(commandName: string, nodeArgv: string[], argv: string[]) {
try {
const Command = await this.find(commandName)
/**
* Expand aliases
*/
const aliasExpansions = this.#aliasExpansions.get(commandName)
if (aliasExpansions) {
argv = aliasExpansions.concat(argv)
debug('expanding alias %O, cli args %O', commandName, argv)
}
/**
* Parse CLI argv and also merge global flags parser options.
*/
const parsed = new Parser(
Command.getParserOptions(this.#globalCommand.getParserOptions().flagsParserOptions)
).parse(argv)
/**
* Defined only for the main command
*/
parsed.nodeArgs = nodeArgv
/**
* Validate the flags against the global list as well
*/
this.#globalCommand.validate(parsed)
/**
* Run options listeners. Option listeners can terminate
* the process early
*/
let shortcircuit = false
for (let [option, listener] of this.#optionListeners) {
if (parsed.flags[option] !== undefined) {
debug('running listener for "%s" flag', option)
shortcircuit = await listener(Command, this, parsed)
if (shortcircuit) {
break
}
}
}
/**
* Validate the parsed output
*/
Command.validate(parsed)
/**
* Return early if a flag listener shortcircuits
*/
if (shortcircuit) {
debug('short circuiting from flag listener')
this.exitCode = this.exitCode ?? 0
this.#state = 'completed'
return
}
/**
* Keep a note of the main command
*/
this.#mainCommand = await this.#executor.create(Command, parsed, this)
this.#mainCommand.hydrate()
/**
* Execute the command using the executor
*/
await this.#hooks.runner('executing').run(this.#mainCommand!, true)
await this.#executor.run(this.#mainCommand!, this)
await this.#hooks.runner('executed').run(this.#mainCommand!, true)
this.exitCode = this.exitCode ?? this.#mainCommand!.exitCode
this.#state = 'completed'
} catch (error) {
this.exitCode = 1
this.#state = 'completed'
await this.errorHandler.render(error, this)
}
}
/**
* Listen for CLI options and execute an action. Only one listener
* can be defined per option.
*
* The callbacks are only executed for the main command
*/
on(option: string, callback: FlagListener<Command>): this {
debug('registering flag listener for "%s" flag', option)
this.#optionListeners.set(option, callback)
return this
}
/**
* Define a global flag that is applicable for all the
* commands.
*/
defineFlag(
name: string,
options: Partial<Flag> & { type: 'string' | 'boolean' | 'array' | 'number' }
) {
if (this.#state !== 'idle') {
throw new RuntimeException(`Cannot register global flag in "${this.#state}" state`)
}
this.#globalCommand.defineFlag(name, options)
}
/**
* Register a commands loader. The commands will be collected by
* all the loaders.
*
* Incase multiple loaders returns a single command, the command from the
* most recent loader will be used.
*/
addLoader(loader: LoadersContract<Command> | (() => Promise<LoadersContract<Command>>)): this {
if (this.#state !== 'idle') {
throw new RuntimeException(`Cannot add loader in "${this.#state}" state`)
}
this.#loaders.push(loader)
return this
}
/**
* Register alias for a comamnd name.
*/
addAlias(alias: string, command: string): this {
const [commandName, ...expansions] = command.split(' ')
this.#aliases.set(alias, commandName)
if (expansions.length) {
debug('registering alias %O for command %O with options %O', alias, commandName, expansions)
this.#aliasExpansions.set(alias, expansions)
} else {
debug('registering alias %O for command %O', alias, commandName)
}
return this
}
/**
* Check if a command or an alias is registered with kernel
*/
hasCommand(commandName: string): boolean {
commandName = this.#aliases.get(commandName) || commandName
return this.#commands.has(commandName)
}
/**
* Get the current state of the kernel.
*/
getState() {
return this.#state
}
/**
* Returns a flat list of commands metadata registered with the kernel.
* The list is sorted alphabetically by the command name.
*/
getCommands(): CommandMetaData[] {
return [...this.#commands.keys()]
.sort(sortAlphabetically)
.map((name) => this.#commands.get(name)!.metaData)
}
/**
* Get a list of commands for a specific namespace. All non-namespaces
* commands will be returned if no namespace is defined.
*/
getNamespaceCommands(namespace?: string) {
let commandNames = [...this.#commands.keys()]
/**
* Filter a list of commands by the namespace
*/
if (namespace) {
commandNames = commandNames.filter(
(name) => this.#commands.get(name)!.metaData.namespace === namespace
)
} else {
commandNames = commandNames.filter((name) => !this.#commands.get(name)!.metaData.namespace)
}
return commandNames.sort(sortAlphabetically).map((name) => this.#commands.get(name)!.metaData)
}
/**
* Returns the command metadata by its name. Returns null when the
* command is missing.
*/
getCommand(commandName: string): CommandMetaData | null {
return this.#commands.get(commandName)?.metaData || null
}
/**
* Returns a reference for the default command. The return value
* is the default command constructor
*/
getDefaultCommand() {
return this.#defaultCommand
}
/**
* Returns reference to the main command
*/
getMainCommand() {
return this.#mainCommand
}
/**
* Returns an array of aliases registered.
*
* - Call `getCommandAliases` method to get aliases for a given command
* - Call `getAliasCommand` to get the command or a given alias
*/
getAliases() {
return [...this.#aliases.keys()]
}
/**
* Returns the command metata for a given alias. Returns null
* if alias is not recognized.
*/
getAliasCommand(alias: string): CommandMetaData | null {
const aliasCommand = this.#aliases.get(alias)
if (!aliasCommand) {
return null
}
return this.#commands.get(aliasCommand)?.metaData || null
}
/**
* Returns an array of aliases for a given command
*/
getCommandAliases(commandName: string) {
return [...this.#aliases.entries()]
.filter(([, command]) => {
return command === commandName
})
.map(([alias]) => alias)
}
/**
* Returns a list of namespaces. The list is sorted alphabetically
* by the namespace name
*/
getNamespaces(): string[] {
return this.#namespaces
}
/**
* Returns an array of command and aliases name suggestions for
* a given keyword.
*/
getCommandSuggestions(keyword: string): string[] {
/**
* Priortize namespace commands when the keyword matches the
* namespace
*/
if (this.#namespaces.includes(keyword)) {
return this.getNamespaceCommands(keyword).map((command) => command.commandName)
}
const commandsAndAliases = [...this.#commands.keys()].concat([...this.#aliases.keys()])
return commandsAndAliases
.map((value) => {
return {
value,
distance: distance(keyword, value),
}
})
.sort((current, next) => next.distance - current.distance)
.filter((rating) => {
return rating.distance <= 3
})
.map((rating) => rating.value)
}
/**
* Returns an array of namespaces suggestions for a given keyword.
*/
getNamespaceSuggestions(keyword: string): string[] {
return this.#namespaces
.map((value) => {
return {
value,
distance: distance(keyword, value),
}
})
.sort((current, next) => next.distance - current.distance)
.filter((rating) => {
return rating.distance <= 3
})
.map((rating) => rating.value)
}
/**
* Listen for the event before we begin the process of finding
* the command.
*/
finding(callback: FindingHookHandler) {
this.#hooks.add('finding', callback)
return this
}
/**
* Listen for the event when importing the command
*/
loading(callback: LoadingHookHandler) {
this.#hooks.add('loading', callback)
return this
}
/**
* Listen for the event when the command has been imported
*/
loaded(callback: LoadedHookHandler<Command>) {
this.#hooks.add('loaded', callback)
return this
}
/**
* Listen for the event before we start to execute the command.
*/
executing(callback: ExecutingHookHandler<InstanceType<Command>>) {
this.#hooks.add('executing', callback)
return this
}
/**
* Listen for the event after the command has been executed
*/
executed(callback: ExecutedHookHandler<InstanceType<Command>>) {
this.#hooks.add('executed', callback)
return this
}
/**
* Loads commands from all the registered loaders. The "addLoader" method
* must be called before calling the "load" method.
*/
async boot() {
if (this.#state !== 'idle') {
return
}
/**
* Boot global command is not already booted
*/
this.#globalCommand.boot()
/**
* Registering the default command
*/
this.addLoader(new ListLoader([this.#defaultCommand]))
/**
* Set state to booted
*/
this.#state = 'booted'
/**
* A set of unique namespaces. Later, we will store them on kernel
* directly as an alphabetically sorted array.
*/
const namespaces: Set<string> = new Set()
/**
* Load metadata for all commands using the loaders
*/
for (let loader of this.#loaders) {
let loaderInstance: LoadersContract<Command>
/**
* A loader can be a function that lazily imports and instantiates
* a loader
*/
if (typeof loader === 'function') {
loaderInstance = await loader()
} else {
loaderInstance = loader
}
const commands = await loaderInstance.getMetaData()
commands.forEach((command) => {
this.#commands.set(command.commandName, { metaData: command, loader: loaderInstance })
command.aliases.forEach((alias) => this.addAlias(alias, command.commandName))
command.namespace && namespaces.add(command.namespace)
})
}
this.#namespaces = [...namespaces].sort(sortAlphabetically)
}
/**
* Find a command by its name
*/
async find<T extends Command>(commandName: string): Promise<T> {
/**
* Get command name from the alias (if one exists)
*/
commandName = this.#aliases.get(commandName) || commandName
await this.#hooks.runner('finding').run(commandName)
/**
* Find if we have a command registered
*/
const command = this.#commands.get(commandName)
if (!command) {
throw new errors.E_COMMAND_NOT_FOUND([commandName])
}
await this.#hooks.runner('loading').run(command.metaData)
/**
* Find if the loader is able to load the command
*/
const commandConstructor = await command.loader.getCommand(command.metaData)
if (!commandConstructor) {
throw new errors.E_COMMAND_NOT_FOUND([commandName])
}
await this.#hooks.runner('loaded').run(commandConstructor)
return commandConstructor as T
}
/**
* Execute a command. The second argument is an array of commandline
* arguments (without the command name)
*/
async exec<T extends Command>(commandName: string, argv: string[]) {
/**
* Boot if not already booted
*/
if (this.#state === 'idle') {
await this.boot()
}
/**
* Cannot execute commands after the main command has exited
*/
if (this.#state === 'completed') {
throw new RuntimeException(
'The kernel has been terminated. Create a fresh instance to execute commands'
)
}
return this.#exec<T>(commandName, argv)
}
/**
* Creates a command instance by parsing and validating
* the command-line arguments.
*/
async create<T extends Command>(command: T, argv: string | string[]): Promise<InstanceType<T>> {
/**
* Boot if not already booted
*/
if (this.#state === 'idle') {
await this.boot()
}
return this.#create(command, argv)
}
/**
* Handle process argv and execute the command. Calling this method
* makes kernel own the process and register SIGNAL listeners
*/
async handle(argv: string[]) {
/**
* Cannot run multiple main commands from a single process
*/
if (this.#state === 'running') {
throw new RuntimeException('Cannot run multiple main commands from a single process')
}
/**
* Cannot run multiple main commands from the same instance
*/
if (this.#state === 'completed') {
throw new RuntimeException(
'The kernel has been terminated. Create a fresh instance to execute commands'
)
}
/**
* Boot kernel
*/
if (this.#state === 'idle') {
await this.boot()
}
this.#state = 'running'
const { commandName, nodeArgv, commandArgv } = this.#processArgv(argv)
/**
* Run the default command
*/
if (!commandName) {
debug('running default command "%s"', this.#defaultCommand.commandName)
return this.#execMain(this.#defaultCommand.commandName, nodeArgv, commandArgv)
}
/**
* Run the mentioned command as the main command
*/
debug('running main command "%s"', commandName)
return this.#execMain(commandName, nodeArgv, commandArgv)
}
/**
* A named function that returns true. To be used
* by flag listeners
*/
shortcircuit() {
return true
}
}