/
command-module.ts
346 lines (300 loc) · 11 KB
/
command-module.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
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { logging, schema, strings } from '@angular-devkit/core';
import { readFileSync } from 'fs';
import * as path from 'path';
import yargs, {
Arguments,
ArgumentsCamelCase,
Argv,
CamelCaseKey,
PositionalOptions,
CommandModule as YargsCommandModule,
Options as YargsOptions,
} from 'yargs';
import { Parser as yargsParser } from 'yargs/helpers';
import { getAnalyticsUserId } from '../analytics/analytics';
import { AnalyticsCollector } from '../analytics/analytics-collector';
import { EventCustomDimension, EventCustomMetric } from '../analytics/analytics-parameters';
import { considerSettingUpAutocompletion } from '../utilities/completion';
import { AngularWorkspace } from '../utilities/config';
import { memoize } from '../utilities/memoize';
import { PackageManagerUtils } from '../utilities/package-manager';
import { Option } from './utilities/json-schema';
export type Options<T> = { [key in keyof T as CamelCaseKey<key>]: T[key] };
export enum CommandScope {
/** Command can only run inside an Angular workspace. */
In,
/** Command can only run outside an Angular workspace. */
Out,
/** Command can run inside and outside an Angular workspace. */
Both,
}
export interface CommandContext {
currentDirectory: string;
root: string;
workspace?: AngularWorkspace;
globalConfiguration: AngularWorkspace;
logger: logging.Logger;
packageManager: PackageManagerUtils;
/** Arguments parsed in free-from without parser configuration. */
args: {
positional: string[];
options: {
help: boolean;
jsonHelp: boolean;
getYargsCompletions: boolean;
} & Record<string, unknown>;
};
}
export type OtherOptions = Record<string, unknown>;
export interface CommandModuleImplementation<T extends {} = {}>
extends Omit<YargsCommandModule<{}, T>, 'builder' | 'handler'> {
/** Scope in which the command can be executed in. */
scope: CommandScope;
/** Path used to load the long description for the command in JSON help text. */
longDescriptionPath?: string;
/** Object declaring the options the command accepts, or a function accepting and returning a yargs instance. */
builder(argv: Argv): Promise<Argv<T>> | Argv<T>;
/** A function which will be passed the parsed argv. */
run(options: Options<T> & OtherOptions): Promise<number | void> | number | void;
}
export interface FullDescribe {
describe?: string;
longDescription?: string;
longDescriptionRelativePath?: string;
}
export abstract class CommandModule<T extends {} = {}> implements CommandModuleImplementation<T> {
abstract readonly command: string;
abstract readonly describe: string | false;
abstract readonly longDescriptionPath?: string;
protected readonly shouldReportAnalytics: boolean = true;
readonly scope: CommandScope = CommandScope.Both;
private readonly optionsWithAnalytics = new Map<string, string>();
constructor(protected readonly context: CommandContext) {}
/**
* Description object which contains the long command descroption.
* This is used to generate JSON help wich is used in AIO.
*
* `false` will result in a hidden command.
*/
public get fullDescribe(): FullDescribe | false {
return this.describe === false
? false
: {
describe: this.describe,
...(this.longDescriptionPath
? {
longDescriptionRelativePath: path
.relative(path.join(__dirname, '../../../../'), this.longDescriptionPath)
.replace(/\\/g, path.posix.sep),
longDescription: readFileSync(this.longDescriptionPath, 'utf8').replace(
/\r\n/g,
'\n',
),
}
: {}),
};
}
protected get commandName(): string {
return this.command.split(' ', 1)[0];
}
abstract builder(argv: Argv): Promise<Argv<T>> | Argv<T>;
abstract run(options: Options<T> & OtherOptions): Promise<number | void> | number | void;
async handler(args: ArgumentsCamelCase<T> & OtherOptions): Promise<void> {
const { _, $0, ...options } = args;
// Camelize options as yargs will return the object in kebab-case when camel casing is disabled.
const camelCasedOptions: Record<string, unknown> = {};
for (const [key, value] of Object.entries(options)) {
camelCasedOptions[yargsParser.camelCase(key)] = value;
}
// Set up autocompletion if appropriate.
const autocompletionExitCode = await considerSettingUpAutocompletion(
this.commandName,
this.context.logger,
);
if (autocompletionExitCode !== undefined) {
process.exitCode = autocompletionExitCode;
return;
}
// Gather and report analytics.
const analytics = await this.getAnalytics();
const stopPeriodicFlushes = analytics && analytics.periodFlush();
let exitCode: number | void | undefined;
try {
if (analytics) {
this.reportCommandRunAnalytics(analytics);
this.reportWorkspaceInfoAnalytics(analytics);
}
exitCode = await this.run(camelCasedOptions as Options<T> & OtherOptions);
} catch (e) {
if (e instanceof schema.SchemaValidationException) {
this.context.logger.fatal(`Error: ${e.message}`);
exitCode = 1;
} else {
throw e;
}
} finally {
await stopPeriodicFlushes?.();
if (typeof exitCode === 'number' && exitCode > 0) {
process.exitCode = exitCode;
}
}
}
@memoize
protected async getAnalytics(): Promise<AnalyticsCollector | undefined> {
if (!this.shouldReportAnalytics) {
return undefined;
}
const userId = await getAnalyticsUserId(
this.context,
// Don't prompt for `ng update` and `ng analytics` commands.
['update', 'analytics'].includes(this.commandName),
);
return userId ? new AnalyticsCollector(this.context, userId) : undefined;
}
/**
* Adds schema options to a command also this keeps track of options that are required for analytics.
* **Note:** This method should be called from the command bundler method.
*/
protected addSchemaOptionsToCommand<T>(localYargs: Argv<T>, options: Option[]): Argv<T> {
const booleanOptionsWithNoPrefix = new Set<string>();
for (const option of options) {
const {
default: defaultVal,
positional,
deprecated,
description,
alias,
userAnalytics,
type,
hidden,
name,
choices,
} = option;
const sharedOptions: YargsOptions & PositionalOptions = {
alias,
hidden,
description,
deprecated,
choices,
// This should only be done when `--help` is used otherwise default will override options set in angular.json.
...(this.context.args.options.help ? { default: defaultVal } : {}),
};
let dashedName = strings.dasherize(name);
// Handle options which have been defined in the schema with `no` prefix.
if (type === 'boolean' && dashedName.startsWith('no-')) {
dashedName = dashedName.slice(3);
booleanOptionsWithNoPrefix.add(dashedName);
}
if (positional === undefined) {
localYargs = localYargs.option(dashedName, {
type,
...sharedOptions,
});
} else {
localYargs = localYargs.positional(dashedName, {
type: type === 'array' || type === 'count' ? 'string' : type,
...sharedOptions,
});
}
// Record option of analytics.
if (userAnalytics !== undefined) {
this.optionsWithAnalytics.set(name, userAnalytics);
}
}
// Handle options which have been defined in the schema with `no` prefix.
if (booleanOptionsWithNoPrefix.size) {
localYargs.middleware((options: Arguments) => {
for (const key of booleanOptionsWithNoPrefix) {
if (key in options) {
options[`no-${key}`] = !options[key];
delete options[key];
}
}
}, false);
}
return localYargs;
}
protected getWorkspaceOrThrow(): AngularWorkspace {
const { workspace } = this.context;
if (!workspace) {
throw new CommandModuleError('A workspace is required for this command.');
}
return workspace;
}
/**
* Flush on an interval (if the event loop is waiting).
*
* @returns a method that when called will terminate the periodic
* flush and call flush one last time.
*/
protected getAnalyticsParameters(
options: (Options<T> & OtherOptions) | OtherOptions,
): Partial<Record<EventCustomDimension | EventCustomMetric, string | boolean | number>> {
const parameters: Partial<
Record<EventCustomDimension | EventCustomMetric, string | boolean | number>
> = {};
const validEventCustomDimensionAndMetrics = new Set([
...Object.values(EventCustomDimension),
...Object.values(EventCustomMetric),
]);
for (const [name, ua] of this.optionsWithAnalytics) {
const value = options[name];
if (
(typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') &&
validEventCustomDimensionAndMetrics.has(ua as EventCustomDimension | EventCustomMetric)
) {
parameters[ua as EventCustomDimension | EventCustomMetric] = value;
}
}
return parameters;
}
private reportCommandRunAnalytics(analytics: AnalyticsCollector): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const internalMethods = (yargs as any).getInternalMethods();
// $0 generate component [name] -> generate_component
// $0 add <collection> -> add
const fullCommand = (internalMethods.getUsageInstance().getUsage()[0][0] as string)
.split(' ')
.filter((x) => {
const code = x.charCodeAt(0);
return code >= 97 && code <= 122;
})
.join('_');
analytics.reportCommandRunEvent(fullCommand);
}
private reportWorkspaceInfoAnalytics(analytics: AnalyticsCollector): void {
const { workspace } = this.context;
if (!workspace) {
return;
}
let applicationProjectsCount = 0;
let librariesProjectsCount = 0;
for (const project of workspace.projects.values()) {
switch (project.extensions['projectType']) {
case 'application':
applicationProjectsCount++;
break;
case 'library':
librariesProjectsCount++;
break;
}
}
analytics.reportWorkspaceInfoEvent({
[EventCustomMetric.AllProjectsCount]: librariesProjectsCount + applicationProjectsCount,
[EventCustomMetric.ApplicationProjectsCount]: applicationProjectsCount,
[EventCustomMetric.LibraryProjectsCount]: librariesProjectsCount,
});
}
}
/**
* Creates an known command module error.
* This is used so during executation we can filter between known validation error and real non handled errors.
*/
export class CommandModuleError extends Error {}