forked from angular/angular-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathschematics-command-module.ts
404 lines (350 loc) · 12.8 KB
/
schematics-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
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
/**
* @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.dev/license
*/
import { JsonValue, normalize as devkitNormalize, schema } from '@angular-devkit/core';
import { Collection, UnsuccessfulWorkflowExecution, formats } from '@angular-devkit/schematics';
import {
FileSystemCollectionDescription,
FileSystemSchematicDescription,
NodeWorkflow,
} from '@angular-devkit/schematics/tools';
import { relative } from 'node:path';
import { Argv } from 'yargs';
import { isPackageNameSafeForAnalytics } from '../analytics/analytics';
import { EventCustomDimension } from '../analytics/analytics-parameters';
import { getProjectByCwd, getSchematicDefaults } from '../utilities/config';
import { assertIsError } from '../utilities/error';
import { memoize } from '../utilities/memoize';
import { isTTY } from '../utilities/tty';
import {
CommandModule,
CommandModuleImplementation,
CommandScope,
Options,
OtherOptions,
} from './command-module';
import { Option, parseJsonSchemaToOptions } from './utilities/json-schema';
import { SchematicEngineHost } from './utilities/schematic-engine-host';
import { subscribeToWorkflow } from './utilities/schematic-workflow';
export const DEFAULT_SCHEMATICS_COLLECTION = '@schematics/angular';
export interface SchematicsCommandArgs {
interactive: boolean;
force: boolean;
'dry-run': boolean;
defaults: boolean;
}
export interface SchematicsExecutionOptions extends Options<SchematicsCommandArgs> {
packageRegistry?: string;
}
export abstract class SchematicsCommandModule
extends CommandModule<SchematicsCommandArgs>
implements CommandModuleImplementation<SchematicsCommandArgs>
{
override scope = CommandScope.In;
protected readonly allowPrivateSchematics: boolean = false;
async builder(argv: Argv): Promise<Argv<SchematicsCommandArgs>> {
return argv
.option('interactive', {
describe: 'Enable interactive input prompts.',
type: 'boolean',
default: true,
})
.option('dry-run', {
describe: 'Run through and reports activity without writing out results.',
type: 'boolean',
alias: ['d'],
default: false,
})
.option('defaults', {
describe: 'Disable interactive input prompts for options with a default.',
type: 'boolean',
default: false,
})
.option('force', {
describe: 'Force overwriting of existing files.',
type: 'boolean',
default: false,
})
.strict();
}
/** Get schematic schema options.*/
protected async getSchematicOptions(
collection: Collection<FileSystemCollectionDescription, FileSystemSchematicDescription>,
schematicName: string,
workflow: NodeWorkflow,
): Promise<Option[]> {
const schematic = collection.createSchematic(schematicName, true);
const { schemaJson } = schematic.description;
if (!schemaJson) {
return [];
}
return parseJsonSchemaToOptions(workflow.registry, schemaJson);
}
@memoize
protected getOrCreateWorkflowForBuilder(collectionName: string): NodeWorkflow {
return new NodeWorkflow(this.context.root, {
resolvePaths: this.getResolvePaths(collectionName),
engineHostCreator: (options) => new SchematicEngineHost(options.resolvePaths),
});
}
@memoize
protected async getOrCreateWorkflowForExecution(
collectionName: string,
options: SchematicsExecutionOptions,
): Promise<NodeWorkflow> {
const { logger, root, packageManager } = this.context;
const { force, dryRun, packageRegistry } = options;
const workflow = new NodeWorkflow(root, {
force,
dryRun,
packageManager: packageManager.name,
// A schema registry is required to allow customizing addUndefinedDefaults
registry: new schema.CoreSchemaRegistry(formats.standardFormats),
packageRegistry,
resolvePaths: this.getResolvePaths(collectionName),
schemaValidation: true,
optionTransforms: [
// Add configuration file defaults
async (schematic, current) => {
const projectName =
typeof current?.project === 'string' ? current.project : this.getProjectName();
return {
...(await getSchematicDefaults(schematic.collection.name, schematic.name, projectName)),
...current,
};
},
],
engineHostCreator: (options) => new SchematicEngineHost(options.resolvePaths),
});
workflow.registry.addPostTransform(schema.transforms.addUndefinedDefaults);
workflow.registry.useXDeprecatedProvider((msg) => logger.warn(msg));
workflow.registry.addSmartDefaultProvider('projectName', () => this.getProjectName());
const workingDir = devkitNormalize(relative(this.context.root, process.cwd()));
workflow.registry.addSmartDefaultProvider('workingDirectory', () =>
workingDir === '' ? undefined : workingDir,
);
workflow.engineHost.registerOptionsTransform(async (schematic, options) => {
const {
collection: { name: collectionName },
name: schematicName,
} = schematic;
const analytics = isPackageNameSafeForAnalytics(collectionName)
? await this.getAnalytics()
: undefined;
analytics?.reportSchematicRunEvent({
[EventCustomDimension.SchematicCollectionName]: collectionName,
[EventCustomDimension.SchematicName]: schematicName,
...this.getAnalyticsParameters(options as unknown as {}),
});
return options;
});
if (options.interactive !== false && isTTY()) {
workflow.registry.usePromptProvider(async (definitions: Array<schema.PromptDefinition>) => {
let prompts: typeof import('@inquirer/prompts') | undefined;
const answers: Record<string, JsonValue> = {};
for (const definition of definitions) {
if (options.defaults && definition.default !== undefined) {
continue;
}
// Only load prompt package if needed
prompts ??= await import('@inquirer/prompts');
switch (definition.type) {
case 'confirmation':
answers[definition.id] = await prompts.confirm({
message: definition.message,
default: definition.default as boolean | undefined,
});
break;
case 'list':
if (!definition.items?.length) {
continue;
}
answers[definition.id] = await (
definition.multiselect ? prompts.checkbox : prompts.select
)({
message: definition.message,
validate: (values) => {
if (!definition.validator) {
return true;
}
return definition.validator(Object.values(values).map(({ value }) => value));
},
default: definition.multiselect ? undefined : definition.default,
choices: definition.items?.map((item) =>
typeof item == 'string'
? {
name: item,
value: item,
}
: {
...item,
name: item.label,
value: item.value,
},
),
});
break;
case 'input': {
let finalValue: JsonValue | undefined;
answers[definition.id] = await prompts.input({
message: definition.message,
default: definition.default as string | undefined,
async validate(value) {
if (definition.validator === undefined) {
return true;
}
let lastValidation: ReturnType<typeof definition.validator> = false;
for (const type of definition.propertyTypes) {
let potential;
switch (type) {
case 'string':
potential = String(value);
break;
case 'integer':
case 'number':
potential = Number(value);
break;
default:
potential = value;
break;
}
lastValidation = await definition.validator(potential);
// Can be a string if validation fails
if (lastValidation === true) {
finalValue = potential;
return true;
}
}
return lastValidation;
},
});
// Use validated value if present.
// This ensures the correct type is inserted into the final schema options.
if (finalValue !== undefined) {
answers[definition.id] = finalValue;
}
break;
}
}
}
return answers;
});
}
return workflow;
}
@memoize
protected async getSchematicCollections(): Promise<Set<string>> {
const getSchematicCollections = (
configSection: Record<string, unknown> | undefined,
): Set<string> | undefined => {
if (!configSection) {
return undefined;
}
const { schematicCollections } = configSection;
if (Array.isArray(schematicCollections)) {
return new Set(schematicCollections);
}
return undefined;
};
const { workspace, globalConfiguration } = this.context;
if (workspace) {
const project = getProjectByCwd(workspace);
if (project) {
const value = getSchematicCollections(workspace.getProjectCli(project));
if (value) {
return value;
}
}
}
const value =
getSchematicCollections(workspace?.getCli()) ??
getSchematicCollections(globalConfiguration.getCli());
if (value) {
return value;
}
return new Set([DEFAULT_SCHEMATICS_COLLECTION]);
}
protected parseSchematicInfo(
schematic: string | undefined,
): [collectionName: string | undefined, schematicName: string | undefined] {
if (schematic?.includes(':')) {
const [collectionName, schematicName] = schematic.split(':', 2);
return [collectionName, schematicName];
}
return [undefined, schematic];
}
protected async runSchematic(options: {
executionOptions: SchematicsExecutionOptions;
schematicOptions: OtherOptions;
collectionName: string;
schematicName: string;
}): Promise<number> {
const { logger } = this.context;
const { schematicOptions, executionOptions, collectionName, schematicName } = options;
const workflow = await this.getOrCreateWorkflowForExecution(collectionName, executionOptions);
if (!schematicName) {
throw new Error('schematicName cannot be undefined.');
}
const { unsubscribe, files } = subscribeToWorkflow(workflow, logger);
try {
await workflow
.execute({
collection: collectionName,
schematic: schematicName,
options: schematicOptions,
logger,
allowPrivate: this.allowPrivateSchematics,
})
.toPromise();
if (!files.size) {
logger.info('Nothing to be done.');
}
if (executionOptions.dryRun) {
logger.warn(`\nNOTE: The "--dry-run" option means no changes were made.`);
}
} catch (err) {
// In case the workflow was not successful, show an appropriate error message.
if (err instanceof UnsuccessfulWorkflowExecution) {
// "See above" because we already printed the error.
logger.fatal('The Schematic workflow failed. See above.');
} else {
assertIsError(err);
logger.fatal(err.message);
}
return 1;
} finally {
unsubscribe();
}
return 0;
}
private getProjectName(): string | undefined {
const { workspace } = this.context;
if (!workspace) {
return undefined;
}
const projectName = getProjectByCwd(workspace);
if (projectName) {
return projectName;
}
return undefined;
}
private getResolvePaths(collectionName: string): string[] {
const { workspace, root } = this.context;
if (collectionName[0] === '.') {
// Resolve relative collections from the location of `angular.json`
return [root];
}
return workspace
? // Workspace
collectionName === DEFAULT_SCHEMATICS_COLLECTION
? // Favor __dirname for @schematics/angular to use the build-in version
[__dirname, process.cwd(), root]
: [process.cwd(), root, __dirname]
: // Global
[__dirname, process.cwd()];
}
}