- Notifications
You must be signed in to change notification settings - Fork 12k
/
Copy pathschematics.ts
522 lines (445 loc) · 15.5 KB
/
schematics.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
#!/usr/bin/env node
/**
* @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,logging,schema}from'@angular-devkit/core';
import{ProcessOutput,createConsoleLogger}from'@angular-devkit/core/node';
import{UnsuccessfulWorkflowExecution}from'@angular-devkit/schematics';
import{NodeWorkflow}from'@angular-devkit/schematics/tools';
importansiColorsfrom'ansi-colors';
import{existsSync}from'node:fs';
import*aspathfrom'node:path';
importyargsParser,{camelCase,decamelize}from'yargs-parser';
/**
* Parse the name of schematic passed in argument, and return a {collection, schematic} named
* tuple. The user can pass in `collection-name:schematic-name`, and this function will either
* return `{collection: 'collection-name', schematic: 'schematic-name'}`, or it will error out
* and show usage.
*
* In the case where a collection name isn't part of the argument, the default is to use the
* schematics package (@angular-devkit/schematics-cli) as the collection.
*
* This logic is entirely up to the tooling.
*
* @param str The argument to parse.
* @return {{collection: string, schematic: (string)}}
*/
functionparseSchematicName(str: string|null): {collection: string;schematic: string|null}{
letcollection='@angular-devkit/schematics-cli';
letschematic=str;
if(schematic?.includes(':')){
constlastIndexOfColon=schematic.lastIndexOf(':');
[collection,schematic]=[
schematic.slice(0,lastIndexOfColon),
schematic.substring(lastIndexOfColon+1),
];
}
return{ collection, schematic };
}
functionremoveLeadingSlash(value: string): string{
returnvalue[0]==='/' ? value.slice(1) : value;
}
exportinterfaceMainOptions{
args: string[];
stdout?: ProcessOutput;
stderr?: ProcessOutput;
}
function_listSchematics(workflow: NodeWorkflow,collectionName: string,logger: logging.Logger){
try{
constcollection=workflow.engine.createCollection(collectionName);
logger.info(collection.listSchematicNames().join('\n'));
}catch(error){
logger.fatal(errorinstanceofError ? error.message : `${error}`);
return1;
}
return0;
}
function_createPromptProvider(): schema.PromptProvider{
returnasync(definitions)=>{
let prompts: typeofimport('@inquirer/prompts')|undefined;
constanswers: Record<string,JsonValue>={};
for(constdefinitionofdefinitions){
// Only load prompt package if needed
prompts??=awaitimport('@inquirer/prompts');
switch(definition.type){
case'confirmation':
answers[definition.id]=awaitprompts.confirm({
message: definition.message,
default: definition.defaultasboolean|undefined,
});
break;
case'list':
if(!definition.items?.length){
continue;
}
answers[definition.id]=await(
definition.multiselect ? prompts.checkbox : prompts.select
)({
message: definition.message,
default: definition.default,
validate: (values)=>{
if(!definition.validator){
returntrue;
}
returndefinition.validator(Object.values(values).map(({ value })=>value));
},
choices: definition.items.map((item)=>
typeofitem=='string'
? {
name: item,
value: item,
}
: {
name: item.label,
value: item.value,
},
),
});
break;
case'input': {
let finalValue: JsonValue|undefined;
answers[definition.id]=awaitprompts.input({
message: definition.message,
default: definition.defaultasstring|undefined,
asyncvalidate(value){
if(definition.validator===undefined){
returntrue;
}
letlastValidation: ReturnType<typeofdefinition.validator>=false;
for(consttypeofdefinition.propertyTypes){
letpotential;
switch(type){
case'string':
potential=String(value);
break;
case'integer':
case'number':
potential=Number(value);
break;
default:
potential=value;
break;
}
lastValidation=awaitdefinition.validator(potential);
// Can be a string if validation fails
if(lastValidation===true){
finalValue=potential;
returntrue;
}
}
returnlastValidation;
},
});
// 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;
}
}
}
returnanswers;
};
}
functionfindUp(names: string|string[],from: string){
if(!Array.isArray(names)){
names=[names];
}
constroot=path.parse(from).root;
letcurrentDir=from;
while(currentDir&¤tDir!==root){
for(constnameofnames){
constp=path.join(currentDir,name);
if(existsSync(p)){
returnp;
}
}
currentDir =path.dirname(currentDir);
}
returnnull;
}
/**
* return package manager' name by lock file
*/
functiongetPackageManagerName(){
// order by check priority
constLOCKS: Record<string,string>={
'package-lock.json': 'npm',
'yarn.lock': 'yarn',
'pnpm-lock.yaml': 'pnpm',
};
constlockPath=findUp(Object.keys(LOCKS),process.cwd());
if(lockPath){
returnLOCKS[path.basename(lockPath)];
}
return'npm';
}
// eslint-disable-next-line max-lines-per-function
exportasyncfunctionmain({
args,
stdout =process.stdout,
stderr =process.stderr,
}: MainOptions): Promise<0|1>{
const{ cliOptions, schematicOptions, _ }=parseArgs(args);
// Create a separate instance to prevent unintended global changes to the color configuration
constcolors=ansiColors.create();
/** Create the DevKit Logger used through the CLI. */
constlogger=createConsoleLogger(!!cliOptions.verbose,stdout,stderr,{
info: (s)=>s,
debug: (s)=>s,
warn: (s)=>colors.bold.yellow(s),
error: (s)=>colors.bold.red(s),
fatal: (s)=>colors.bold.red(s),
});
if(cliOptions.help){
logger.info(getUsage());
return0;
}
/** Get the collection an schematic name from the first argument. */
const{collection: collectionName,schematic: schematicName}=parseSchematicName(
_.shift()||null,
);
constisLocalCollection=collectionName.startsWith('.')||collectionName.startsWith('/');
/** Gather the arguments for later use. */
constdebugPresent=cliOptions.debug!==null;
constdebug=debugPresent ? !!cliOptions.debug : isLocalCollection;
constdryRunPresent=cliOptions['dry-run']!==null;
constdryRun=dryRunPresent ? !!cliOptions['dry-run'] : debug;
constforce=!!cliOptions.force;
constallowPrivate=!!cliOptions['allow-private'];
/** Create the workflow scoped to the working directory that will be executed with this run. */
constworkflow=newNodeWorkflow(process.cwd(),{
force,
dryRun,
resolvePaths: [process.cwd(),__dirname],
schemaValidation: true,
packageManager: getPackageManagerName(),
});
/** If the user wants to list schematics, we simply show all the schematic names. */
if(cliOptions['list-schematics']){
return_listSchematics(workflow,collectionName,logger);
}
if(!schematicName){
logger.info(getUsage());
return1;
}
if(debug){
logger.info(
`Debug mode enabled${isLocalCollection ? ' by default for local collections' : ''}.`,
);
}
// Indicate to the user when nothing has been done. This is automatically set to off when there's
// a new DryRunEvent.
letnothingDone=true;
// Logging queue that receives all the messages to show the users. This only get shown when no
// errors happened.
letloggingQueue: string[]=[];
leterror=false;
/**
* Logs out dry run events.
*
* All events will always be executed here, in order of discovery. That means that an error would
* be shown along other events when it happens. Since errors in workflows will stop the Observable
* from completing successfully, we record any events other than errors, then on completion we
* show them.
*
* This is a simple way to only show errors when an error occur.
*/
workflow.reporter.subscribe((event)=>{
nothingDone=false;
// Strip leading slash to prevent confusion.
consteventPath=removeLeadingSlash(event.path);
switch(event.kind){
case'error':
error=true;
logger.error(
`ERROR! ${eventPath}${event.description=='alreadyExist' ? 'already exists' : 'does not exist'}.`,
);
break;
case'update':
loggingQueue.push(`${colors.cyan('UPDATE')}${eventPath} (${event.content.length} bytes)`);
break;
case'create':
loggingQueue.push(`${colors.green('CREATE')}${eventPath} (${event.content.length} bytes)`);
break;
case'delete':
loggingQueue.push(`${colors.yellow('DELETE')}${eventPath}`);
break;
case'rename':
loggingQueue.push(
`${colors.blue('RENAME')}${eventPath} => ${removeLeadingSlash(event.to)}`,
);
break;
}
});
/**
* Listen to lifecycle events of the workflow to flush the logs between each phases.
*/
workflow.lifeCycle.subscribe((event)=>{
if(event.kind=='workflow-end'||event.kind=='post-tasks-start'){
if(!error){
// Flush the log queue and clean the error state.
loggingQueue.forEach((log)=>logger.info(log));
}
loggingQueue=[];
error=false;
}
});
workflow.registry.addPostTransform(schema.transforms.addUndefinedDefaults);
// Show usage of deprecated options
workflow.registry.useXDeprecatedProvider((msg)=>logger.warn(msg));
// Pass the rest of the arguments as the smart default "argv". Then delete it.
workflow.registry.addSmartDefaultProvider('argv',(schema)=>
'index'inschema ? _[Number(schema['index'])] : _,
);
// Add prompts.
if(cliOptions.interactive&&isTTY()){
workflow.registry.usePromptProvider(_createPromptProvider());
}
/**
* Execute the workflow, which will report the dry run events, run the tasks, and complete
* after all is done.
*
* The Observable returned will properly cancel the workflow if unsubscribed, error out if ANY
* step of the workflow failed (sink or task), with details included, and will only complete
* when everything is done.
*/
try{
awaitworkflow
.execute({
collection: collectionName,
schematic: schematicName,
options: schematicOptions,
allowPrivate: allowPrivate,
debug: debug,
logger: logger,
})
.toPromise();
if(nothingDone){
logger.info('Nothing to be done.');
}elseif(dryRun){
logger.info(
`Dry run enabled${
dryRunPresent ? '' : ' by default in debug mode'
}. No files written to disk.`,
);
}
return0;
}catch(err){
if(errinstanceofUnsuccessfulWorkflowExecution){
// "See above" because we already printed the error.
logger.fatal('The Schematic workflow failed. See above.');
}elseif(debug&&errinstanceofError){
logger.fatal(`An error occured:\n${err.stack}`);
}else{
logger.fatal(`Error: ${errinstanceofError ? err.message : err}`);
}
return1;
}
}
/**
* Get usage of the CLI tool.
*/
functiongetUsage(): string{
return`
schematics [collection-name:]schematic-name [options, ...]
By default, if the collection name is not specified, use the internal collection provided
by the Schematics CLI.
Options:
--debug Debug mode. This is true by default if the collection is a relative
path (in that case, turn off with --debug=false).
--allow-private Allow private schematics to be run from the command line. Default to
false.
--dry-run Do not output anything, but instead just show what actions would be
performed. Default to true if debug is also true.
--force Force overwriting files that would otherwise be an error.
--list-schematics List all schematics from the collection, by name. A collection name
should be suffixed by a colon. Example: '@angular-devkit/schematics-cli:'.
--no-interactive Disables interactive input prompts.
--verbose Show more information.
--help Show this message.
Any additional option is passed to the Schematics depending on its schema.
`;
}
/** Parse the command line. */
constbooleanArgs=[
'allow-private',
'debug',
'dry-run',
'force',
'help',
'list-schematics',
'verbose',
'interactive',
]asconst;
typeElementType<TextendsReadonlyArray<unknown>>=
TextendsReadonlyArray<inferElementType> ? ElementType : never;
interfaceOptions{
_: string[];
schematicOptions: Record<string,unknown>;
cliOptions: Partial<Record<ElementType<typeofbooleanArgs>,boolean|null>>;
}
/** Parse the command line. */
functionparseArgs(args: string[]): Options{
const{ _, ...options}=yargsParser(args,{
boolean: booleanArgsasunknownasstring[],
default: {
'interactive': true,
'debug': null,
'dry-run': null,
},
configuration: {
'dot-notation': false,
'boolean-negation': true,
'strip-aliased': true,
'camel-case-expansion': false,
},
});
// Camelize options as yargs will return the object in kebab-case when camel casing is disabled.
constschematicOptions: Options['schematicOptions']={};
constcliOptions: Options['cliOptions']={};
constisCliOptions=(
key: ElementType<typeofbooleanArgs>|string,
): keyisElementType<typeofbooleanArgs>=>
booleanArgs.includes(keyasElementType<typeofbooleanArgs>);
for(const[key,value]ofObject.entries(options)){
if(/[A-Z]/.test(key)){
thrownewError(`Unknown argument ${key}. Did you mean ${decamelize(key)}?`);
}
if(isCliOptions(key)){
cliOptions[key]=value;
}else{
schematicOptions[camelCase(key)]=value;
}
}
return{
_: _.map((v)=>v.toString()),
schematicOptions,
cliOptions,
};
}
functionisTTY(): boolean{
constisTruthy=(value: undefined|string)=>{
// Returns true if value is a string that is anything but 0 or false.
returnvalue!==undefined&&value!=='0'&&value.toUpperCase()!=='FALSE';
};
// If we force TTY, we always return true.
constforce=process.env['NG_FORCE_TTY'];
if(force!==undefined){
returnisTruthy(force);
}
return!!process.stdout.isTTY&&!isTruthy(process.env['CI']);
}
if(require.main===module){
const args=process.argv.slice(2);
main({ args })
.then((exitCode)=>(process.exitCode=exitCode))
.catch((e)=>{
throwe;
});
}