-
-
Notifications
You must be signed in to change notification settings - Fork 25
/
service.ts
executable file
·203 lines (181 loc) · 6.35 KB
/
service.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
/**
* @module ConsoleService
*/
import { INestApplicationContext, Injectable } from '@nestjs/common';
import * as commander from 'commander';
import { CreateCommandOptions, InjectCli } from './decorators';
import { CommandActionHandler, CommandActionWrapper, CommandResponse } from './interfaces';
@Injectable()
export class ConsoleService {
/**
* An optional instance of the application.
* Required to scan the application
*/
protected container?: INestApplicationContext;
/**
* A Map holding group commands by name
*/
protected commands: Map<string, commander.Command> = new Map();
/**
* The root cli
*/
protected cli: commander.Command;
constructor(@InjectCli() cli: commander.Command) {
this.cli = cli;
}
static createCli(name?: string): commander.Command {
const cli = new commander.Command(name);
cli.storeOptionsAsProperties(false);
cli.allowUnknownOption(false);
return cli;
}
/**
* Reset the cli stack (for testing purpose only)
*/
resetCli(): void {
this.cli = ConsoleService.createCli();
}
/**
* Get the root cli
*/
getRootCli(): commander.Command {
return this.cli;
}
/**
* Get a cli
* @param name Get a cli by name, if not set, the root cli is used
*/
getCli(name?: string): commander.Command | undefined {
let cli: commander.Command | undefined;
if (typeof name === 'string') {
cli = this.commands.get(name);
} else {
cli = this.cli;
}
return cli;
}
/**
* Set the container
*/
setContainer(container: INestApplicationContext): ConsoleService {
this.container = container;
return this;
}
/**
* Get the container
*/
getContainer(): INestApplicationContext | undefined {
return this.container;
}
/**
* Wrap an action handler to work with promise.
*/
static createHandler(action: CommandActionHandler): CommandActionWrapper {
return async (...args: any[]): Promise<CommandResponse> => {
const command: commander.Command = args.find((c) => c instanceof commander.Command);
let data: CommandResponse;
if (typeof action === 'object') {
data = action.instance[action.methodName](...args);
} else {
data = action(...args);
}
if (data instanceof Promise) {
data = await data;
}
return { data, command };
};
}
/**
* Execute the cli
*/
async init(argv: string[]): Promise<CommandResponse> {
await this.cli.parseAsync(argv);
const results = await Promise.all((this.cli as any)._actionResults as Promise<CommandResponse>[]);
return results[0];
}
/**
* Create a Command
*
* @param options The options to create the commands
* @param handler The handler of the command
* @param parent The command to use as a parent
*/
createCommand(
options: CreateCommandOptions,
handler: CommandActionHandler,
parent: commander.Command,
commanderOptions?: commander.CommandOptions
): commander.Command {
const args = options.command.split(' ');
const commandNames = args[0].split('.');
const command = ConsoleService.createCli(commandNames[commandNames.length - 1]);
if (args.length > 1) {
command.arguments(args.slice(1).join(' '));
}
if (options.description !== undefined) {
command.description(options.description);
}
if (options.alias !== undefined) {
command.alias(options.alias);
}
if (Array.isArray(options.options)) {
for (const opt of options.options) {
let method = 'option';
if (opt.required === true) {
method = 'requiredOption';
}
command[method](opt.flags, opt.description, opt.fn || opt.defaultValue, opt.defaultValue);
}
}
// here as any is required cause commander bad typing on action for promise
command.action(ConsoleService.createHandler(handler) as any);
// add the command to the parent
parent.addCommand(command, commanderOptions);
// add the command to cli stack
this.commands.set(this.getCommandFullName(command), command);
return command;
}
/**
* Create a group of command.
* @param options The options to create the grouped command
* @param parent The command to use as a parent
* @throws an error if the parent command contains explicit arguments, only simple commands are allowed (no spaces)
*/
createGroupCommand(options: CreateCommandOptions, parent: commander.Command): commander.Command {
if ((parent as any)._args.length > 0) {
throw new Error('Sub commands cannot be applied to command with explicit args');
}
const commandNames = options.command.split('.');
const command = ConsoleService.createCli(commandNames[commandNames.length - 1]);
if (options.description !== undefined) {
command.description(options.description);
}
if (options.alias !== undefined) {
command.alias(options.alias);
}
if (Array.isArray(options.options)) {
for (const opt of options.options) {
let method = 'option';
if (opt.required === true) {
method = 'requiredOption';
}
command[method](opt.flags, opt.description, opt.fn || opt.defaultValue, opt.defaultValue);
}
}
parent.addCommand(command);
this.commands.set(this.getCommandFullName(command), command);
return command;
}
/**
* Get the full name of a command (parents names + command names separated by dot)
*/
getCommandFullName(command: commander.Command): string {
let fullName = command.name();
let commandParent = command.parent;
while (commandParent instanceof commander.Command && commandParent.name() !== '') {
fullName = `${commandParent.name()}.${fullName}`;
commandParent = commandParent.parent;
}
return fullName;
}
}