-
Notifications
You must be signed in to change notification settings - Fork 12k
/
command-module.ts
259 lines (228 loc) · 8.03 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
/**
* @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 { analytics, logging, schema, strings } from '@angular-devkit/core';
import { readFileSync } from 'fs';
import * as path from 'path';
import {
ArgumentsCamelCase,
Argv,
CamelCaseKey,
PositionalOptions,
CommandModule as YargsCommandModule,
Options as YargsOptions,
} from 'yargs';
import { Parser as yargsParser } from 'yargs/helpers';
import { createAnalytics } from '../analytics/analytics';
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'> {
/** 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;
static scope = CommandScope.Both;
private readonly optionsWithAnalytics = new Map<string, number>();
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();
if (this.shouldReportAnalytics) {
await this.reportAnalytics(camelCasedOptions);
}
let exitCode: number | void | undefined;
try {
// Run and time command.
const startTime = Date.now();
exitCode = await this.run(camelCasedOptions as Options<T> & OtherOptions);
const endTime = Date.now();
analytics.timing(this.commandName, 'duration', endTime - startTime);
await analytics.flush();
} catch (e) {
if (e instanceof schema.SchemaValidationException) {
this.context.logger.fatal(`Error: ${e.message}`);
exitCode = 1;
} else {
throw e;
}
} finally {
if (typeof exitCode === 'number' && exitCode > 0) {
process.exitCode = exitCode;
}
}
}
async reportAnalytics(
options: (Options<T> & OtherOptions) | OtherOptions,
paths: string[] = [],
dimensions: (boolean | number | string)[] = [],
): Promise<void> {
for (const [name, ua] of this.optionsWithAnalytics) {
const value = options[name];
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
dimensions[ua] = value;
}
}
const analytics = await this.getAnalytics();
analytics.pageview('/command/' + [this.commandName, ...paths].join('/'), {
dimensions,
metrics: [],
});
}
@memoize
protected getAnalytics(): Promise<analytics.Analytics> {
return createAnalytics(
!!this.context.workspace,
// Don't prompt for `ng update` and `ng analytics` commands.
['update', 'analytics'].includes(this.commandName),
);
}
/**
* 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> {
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 } : {}),
};
if (positional === undefined) {
localYargs = localYargs.option(strings.dasherize(name), {
type,
...sharedOptions,
});
} else {
localYargs = localYargs.positional(strings.dasherize(name), {
type: type === 'array' || type === 'count' ? 'string' : type,
...sharedOptions,
});
}
// Record option of analytics.
if (userAnalytics !== undefined) {
this.optionsWithAnalytics.set(name, userAnalytics);
}
}
return localYargs;
}
protected getWorkspaceOrThrow(): AngularWorkspace {
const { workspace } = this.context;
if (!workspace) {
throw new CommandModuleError('A workspace is required for this command.');
}
return workspace;
}
}
/**
* 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 {}