/
ngcli-adapter.ts
1276 lines (1189 loc) · 37.9 KB
/
ngcli-adapter.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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint-disable no-restricted-imports */
import {
fragment,
logging,
normalize,
Path,
PathFragment,
schema,
tags,
virtualFs,
workspaces,
} from '@angular-devkit/core';
import * as chalk from 'chalk';
import { createConsoleLogger, NodeJsSyncHost } from '@angular-devkit/core/node';
import { Stats } from 'fs';
import { detectPackageManager } from '../shared/package-manager';
import { GenerateOptions } from './generate';
import { FileChange, Tree } from '../shared/tree';
import {
buildWorkspaceConfigurationFromGlobs,
globForProjectFiles,
ProjectConfiguration,
RawWorkspaceJsonConfiguration,
toNewFormat,
toNewFormatOrNull,
toOldFormatOrNull,
workspaceConfigName,
WorkspaceJsonConfiguration,
} from '../shared/workspace';
import { dirname, extname, resolve, join, basename } from 'path';
import { FileBuffer } from '@angular-devkit/core/src/virtual-fs/host/interface';
import type { Architect } from '@angular-devkit/architect';
import { Observable, of, merge, forkJoin, NEVER } from 'rxjs';
import { catchError, map, switchMap, toArray, tap } from 'rxjs/operators';
import { NX_ERROR, NX_PREFIX } from '../shared/logger';
import { readJsonFile } from '../utils/fileutils';
import { parseJson, serializeJson } from '../utils/json';
import { NxJsonConfiguration } from '../shared/nx';
export async function scheduleTarget(
root: string,
opts: {
project: string;
target: string;
configuration: string;
runOptions: any;
executor: string;
},
verbose: boolean
): Promise<Observable<import('@angular-devkit/architect').BuilderOutput>> {
const { Architect } = require('@angular-devkit/architect');
const {
WorkspaceNodeModulesArchitectHost,
} = require('@angular-devkit/architect/node');
const logger = getTargetLogger(opts.executor, verbose);
const fsHost = new NxScopedHost(root);
const { workspace } = await workspaces.readWorkspace(
workspaceConfigName(root),
workspaces.createWorkspaceHost(fsHost)
);
const registry = new schema.CoreSchemaRegistry();
registry.addPostTransform(schema.transforms.addUndefinedDefaults);
const architectHost = new WorkspaceNodeModulesArchitectHost(workspace, root);
const architect: Architect = new Architect(architectHost, registry);
const run = await architect.scheduleTarget(
{
project: opts.project,
target: opts.target,
configuration: opts.configuration,
},
opts.runOptions,
{ logger }
);
let lastOutputError: string;
return run.output.pipe(
tap(
(output) =>
(lastOutputError = !output.success ? output.error : undefined),
(error) => {}, // do nothing, this could be an intentional error
() => {
lastOutputError ? logger.error(lastOutputError) : 0;
}
)
);
}
function createWorkflow(
fsHost: virtualFs.Host<Stats>,
root: string,
opts: any
) {
const NodeWorkflow = require('@angular-devkit/schematics/tools').NodeWorkflow;
const workflow = new NodeWorkflow(fsHost, {
force: opts.force,
dryRun: opts.dryRun,
packageManager: detectPackageManager(),
root: normalize(root),
registry: new schema.CoreSchemaRegistry(
require('@angular-devkit/schematics').formats.standardFormats
),
resolvePaths: [process.cwd(), root],
});
workflow.registry.addPostTransform(schema.transforms.addUndefinedDefaults);
workflow.engineHost.registerOptionsTransform(
require('@angular-devkit/schematics/tools').validateOptionsWithSchema(
workflow.registry
)
);
if (opts.interactive) {
workflow.registry.usePromptProvider(createPromptProvider());
}
return workflow;
}
function getCollection(workflow: any, name: string) {
const collection = workflow.engine.createCollection(name);
if (!collection) throw new Error(`Cannot find collection '${name}'`);
return collection;
}
async function createRecorder(
host: NxScopedHost,
record: {
loggingQueue: string[];
error: boolean;
},
logger: logging.Logger
) {
const actualConfigName = await host.workspaceConfigName();
return (event: import('@angular-devkit/schematics').DryRunEvent) => {
let eventPath = event.path.startsWith('/')
? event.path.substr(1)
: event.path;
if (eventPath === 'workspace.json' || eventPath === 'angular.json') {
eventPath = actualConfigName;
}
if (event.kind === 'error') {
record.error = true;
logger.warn(
`ERROR! ${eventPath} ${
event.description == 'alreadyExist'
? 'already exists'
: 'does not exist.'
}.`
);
} else if (event.kind === 'update') {
record.loggingQueue.push(
tags.oneLine`${chalk.white('UPDATE')} ${eventPath}`
);
} else if (event.kind === 'create') {
record.loggingQueue.push(
tags.oneLine`${chalk.green('CREATE')} ${eventPath}`
);
} else if (event.kind === 'delete') {
record.loggingQueue.push(`${chalk.yellow('DELETE')} ${eventPath}`);
} else if (event.kind === 'rename') {
record.loggingQueue.push(
`${chalk.blue('RENAME')} ${eventPath} => ${event.to}`
);
}
};
}
async function runSchematic(
host: NxScopedHost,
root: string,
workflow: import('@angular-devkit/schematics/tools').NodeWorkflow,
logger: logging.Logger,
opts: GenerateOptions,
schematic: import('@angular-devkit/schematics').Schematic<
import('@angular-devkit/schematics/tools').FileSystemCollectionDescription,
import('@angular-devkit/schematics/tools').FileSystemSchematicDescription
>,
printDryRunMessage = true,
recorder: any = null
): Promise<{ status: number; loggingQueue: string[] }> {
const record = { loggingQueue: [] as string[], error: false };
workflow.reporter.subscribe(
recorder || (await createRecorder(host, record, logger))
);
try {
await workflow
.execute({
collection: opts.collectionName,
schematic: opts.generatorName,
options: opts.generatorOptions,
debug: opts.debug,
logger,
})
.toPromise();
} catch (e) {
console.log(e);
throw e;
}
if (!record.error) {
record.loggingQueue.forEach((log) => logger.info(log));
}
if (opts.dryRun && printDryRunMessage) {
logger.warn(`\nNOTE: The "dryRun" flag means no changes were made.`);
}
return { status: 0, loggingQueue: record.loggingQueue };
}
type AngularJsonConfiguration = WorkspaceJsonConfiguration &
Pick<NxJsonConfiguration, 'cli' | 'defaultProject' | 'generators'> & {
schematics?: NxJsonConfiguration['generators'];
};
export class NxScopedHost extends virtualFs.ScopedHost<any> {
protected __nxInMemoryWorkspace: WorkspaceJsonConfiguration | null;
constructor(private root: string) {
super(new NodeJsSyncHost(), normalize(root));
}
protected __readWorkspaceConfiguration = (
configFileName: ChangeContext['actualConfigFileName'],
overrides?: {
workspace?: Observable<RawWorkspaceJsonConfiguration>;
nx?: Observable<NxJsonConfiguration>;
}
): Observable<FileBuffer> => {
const readJsonFile = (path: string) =>
super
.read(path as Path)
.pipe(map((data) => JSON.parse(Buffer.from(data).toString())));
const readWorkspaceJsonFile = (
nxJson: NxJsonConfiguration
): Observable<RawWorkspaceJsonConfiguration> => {
if (overrides?.workspace) {
return overrides.workspace;
} else if (this.__nxInMemoryWorkspace) {
return of(this.__nxInMemoryWorkspace);
} else {
if (configFileName) {
return super
.read(configFileName)
.pipe(map((data) => parseJson(Buffer.from(data).toString())));
} else {
const staticProjects = globForProjectFiles(this.root);
this.__nxInMemoryWorkspace = buildWorkspaceConfigurationFromGlobs(
nxJson,
staticProjects.filter((x) => basename(x) !== 'package.json')
);
Object.entries(this.__nxInMemoryWorkspace.projects).forEach(
([project, config]) => {
this.__nxInMemoryWorkspace.projects[project] = config.root as any;
}
);
return of(this.__nxInMemoryWorkspace);
}
}
};
const readNxJsonFile = () => {
if (overrides?.nx) {
return overrides.nx;
}
return readJsonFile('nx.json');
};
return super.exists('nx.json' as Path).pipe(
switchMap((nxJsonExists) => {
let nxJsonObservable: Observable<NxJsonConfiguration> = NEVER;
if (nxJsonExists) {
nxJsonObservable = readNxJsonFile();
} else {
nxJsonObservable = of({} as NxJsonConfiguration);
}
const workspaceJsonObservable: Observable<RawWorkspaceJsonConfiguration> =
nxJsonObservable.pipe(switchMap((x) => readWorkspaceJsonFile(x)));
return forkJoin([nxJsonObservable, workspaceJsonObservable]);
}),
switchMap(([nxJson, workspaceJson]) => {
try {
// resolve inline configurations and downlevel format
return this.resolveInlineProjectConfigurations(workspaceJson).pipe(
map((x) => {
const angularJson: AngularJsonConfiguration = x;
// assign props ng cli expects from nx json, if it exists
angularJson.cli ??= nxJson?.cli;
angularJson.generators ??= nxJson?.generators;
angularJson.defaultProject ??= nxJson?.defaultProject;
if (workspaceJson.version === 2) {
const formatted = toOldFormatOrNull(workspaceJson);
return formatted
? Buffer.from(serializeJson(formatted))
: Buffer.from(serializeJson(x));
}
return Buffer.from(serializeJson(x));
})
);
} catch {
return of(Buffer.from(serializeJson(workspaceJson)));
}
})
);
};
read(path: Path): Observable<FileBuffer> {
return this.context(path).pipe(
switchMap((r) => {
if (r.isWorkspaceConfig) {
return this.__readWorkspaceConfiguration(r.actualConfigFileName);
} else {
return super.read(path);
}
})
);
}
write(path: Path, content: FileBuffer): Observable<void> {
return this.context(path).pipe(
switchMap((r) => {
if (r.isWorkspaceConfig) {
return this.writeWorkspaceConfiguration(r, content);
} else {
return super.write(path, content);
}
})
);
}
isFile(path: Path): Observable<boolean> {
return this.context(path).pipe(
switchMap((r) => {
if (r.isWorkspaceConfig) {
return of(true); // isWorkspaceConfig means its a file
} else {
return super.isFile(path);
}
})
);
}
exists(path: Path): Observable<boolean> {
return this.context(path).pipe(
switchMap((r) => {
if (r.isWorkspaceConfig) {
return of(true);
} else {
return super.exists(path);
}
})
);
}
workspaceConfigName(): Promise<string> {
return super
.exists('/angular.json' as any)
.pipe(
map((hasAngularJson) =>
hasAngularJson ? 'angular.json' : 'workspace.json'
)
)
.toPromise();
}
protected context(path: string): Observable<ChangeContext> {
if (isWorkspaceConfigPath(path)) {
return forkJoin([
super.exists('/angular.json' as Path),
super.exists('/workspace.json' as Path),
]).pipe(
switchMap(([isAngularJson, isWorkspaceJson]) => {
if (!isAngularJson && !isWorkspaceJson) {
return of({
isWorkspaceConfig: true,
actualConfigFileName: null,
// AngularJson / WorkspaceJson v2 is always used for standalone project config
isNewFormat: true,
});
}
const actualConfigFileName = isAngularJson
? ('/angular.json' as Path)
: ('/workspace.json' as Path);
return super.read(actualConfigFileName as any).pipe(
map((r) => {
try {
const w = parseJson(Buffer.from(r).toString());
return {
isWorkspaceConfig: true,
actualConfigFileName,
isNewFormat: w.version === 2,
};
} catch {
return {
isWorkspaceConfig: true,
actualConfigFileName,
isNewFormat: false,
};
}
})
);
})
);
} else {
return of({
isWorkspaceConfig: false,
actualConfigFileName: null,
isNewFormat: false,
});
}
}
private writeWorkspaceConfiguration(
context: ChangeContext,
content
): Observable<void> {
const config = parseJson(Buffer.from(content).toString());
if (context.isNewFormat) {
try {
const w = parseJson(Buffer.from(content).toString());
const formatted: AngularJsonConfiguration = toNewFormatOrNull(w);
if (formatted) {
const { cli, generators, defaultProject, ...workspaceJson } =
formatted;
return merge(
this.writeWorkspaceConfigFiles(context, workspaceJson),
cli || generators || defaultProject
? this.__saveNxJsonProps({ cli, generators, defaultProject })
: of(null)
);
} else {
const {
cli,
schematics,
generators,
defaultProject,
...angularJson
} = w;
return merge(
this.writeWorkspaceConfigFiles(context, angularJson),
cli || schematics
? this.__saveNxJsonProps({
cli,
defaultProject,
generators: schematics || generators,
})
: of(null)
);
}
} catch (e) {}
}
const { cli, schematics, generators, defaultProject, ...angularJson } =
config;
return merge(
this.writeWorkspaceConfigFiles(context, angularJson),
this.__saveNxJsonProps({
cli,
defaultProject,
generators: schematics || generators,
})
);
}
private __saveNxJsonProps(
props: Partial<NxJsonConfiguration>
): Observable<void> {
const nxJsonPath = 'nx.json' as Path;
return super.read(nxJsonPath).pipe(
switchMap((buf) => {
const nxJson = parseJson(Buffer.from(buf).toString());
Object.assign(nxJson, props);
return super.write(nxJsonPath, Buffer.from(serializeJson(nxJson)));
})
);
}
private writeWorkspaceConfigFiles(
{ actualConfigFileName: workspaceFileName, isNewFormat }: ChangeContext,
config
) {
// copy to avoid removing inlined config files.
const writeObservables: Observable<void>[] = [];
const configToWrite = {
...config,
projects: { ...config.projects },
};
const projects: [string, any][] = Object.entries(configToWrite.projects);
for (const [project, projectConfig] of projects) {
if (projectConfig.configFilePath) {
if (workspaceFileName && !isNewFormat) {
throw new Error(
'Attempted to write standalone project configuration into a v1 workspace'
);
}
// project was read from a project.json file
const configPath = projectConfig.configFilePath;
const fileConfigObject = { ...projectConfig };
delete fileConfigObject.configFilePath; // remove the configFilePath before writing
const projectJsonWrite = super.write(
configPath,
Buffer.from(serializeJson(fileConfigObject))
); // write back to the project.json file
writeObservables.push(projectJsonWrite);
configToWrite.projects[project] = normalize(dirname(configPath)); // update the config object to point to the written file.
}
}
if (workspaceFileName) {
const workspaceJsonWrite = super.write(
workspaceFileName,
Buffer.from(serializeJson(configToWrite))
);
writeObservables.push(workspaceJsonWrite);
}
return merge(...writeObservables);
}
protected resolveInlineProjectConfigurations(
config: RawWorkspaceJsonConfiguration
): Observable<WorkspaceJsonConfiguration> {
// Creates an observable where each emission is a project configuration
// that is not listed inside workspace.json. Each time it encounters a
// standalone config, observable is updated by concatenating the new
// config read operation.
const observables: Observable<{
project: string;
projectConfig: ProjectConfiguration;
}>[] = [];
Object.entries((config.projects as Record<string, any>) ?? {}).forEach(
([project, projectConfig]) => {
if (typeof projectConfig === 'string') {
// configFilePath is not written to files, but is stored on the config object
// so that we know where to save the project's configuration if it was updated
// by another angular schematic.
const configFilePath = join(projectConfig, 'project.json');
const next = this.read(configFilePath as Path).pipe(
map((x) => ({
project,
projectConfig: {
...parseJson(Buffer.from(x).toString()),
configFilePath,
},
}))
);
observables.push(next);
}
}
);
return merge(...observables).pipe(
toArray(),
map((configs) => {
configs.forEach(({ project, projectConfig }) => {
config.projects[project] = projectConfig;
});
return config as WorkspaceJsonConfiguration;
})
);
}
}
type ConfigFilePath = ('/angular.json' | '/workspace.json') & {
__PRIVATE_DEVKIT_PATH: void;
};
type ChangeContext = {
isWorkspaceConfig: boolean;
actualConfigFileName: ConfigFilePath | null;
isNewFormat: boolean;
};
export class NxScopeHostUsedForWrappedSchematics extends NxScopedHost {
constructor(root: string, private readonly host: Tree) {
super(root);
}
read(path: Path): Observable<FileBuffer> {
if (isWorkspaceConfigPath(path)) {
const nxJsonChange = findMatchingFileChange(this.host, 'nx.json' as Path);
const match = findWorkspaceConfigFileChange(this.host);
let workspaceJsonOverride: Observable<RawWorkspaceJsonConfiguration>;
let actualConfigFileName: ConfigFilePath = [
'/workspace.json',
'/angular.json',
].filter((f) => this.host.exists(f))[0] as ConfigFilePath;
if (actualConfigFileName) {
if (match) {
workspaceJsonOverride = of(parseJson(match.content.toString()));
}
} else if (!this.__nxInMemoryWorkspace) {
// if we've already dealt with this, let NxScopedHost read the cache...
// projects created inside a generator will not be visible
// to glob when it runs in nx/shared/workspace, so
// we have to add them into the file.
const createdProjectFiles = findCreatedProjects(this.host);
const deletedProjectFiles = findDeletedProjects(this.host);
const nxJsonInTree = nxJsonChange
? parseJson(nxJsonChange.content.toString())
: parseJson(this.host.read('nx.json').toString());
const readJsonWithHost = (file) =>
parseJson(this.host.read(file).toString());
const staticProjects = buildWorkspaceConfigurationFromGlobs(
nxJsonInTree,
globForProjectFiles(this.host.root).filter(
(x) => basename(x) !== 'package.json'
),
readJsonWithHost
);
const createdProjects = buildWorkspaceConfigurationFromGlobs(
nxJsonInTree,
createdProjectFiles.map((x) => x.path),
readJsonWithHost
).projects;
deletedProjectFiles.forEach((file) => {
const matchingStaticProject = Object.entries(
staticProjects.projects
).find(([, config]) => config.root === dirname(file.path));
if (matchingStaticProject) {
delete staticProjects.projects[matchingStaticProject[0]];
}
});
const workspace = {
...staticProjects,
projects: { ...staticProjects.projects, ...createdProjects },
};
workspaceJsonOverride = of({
...workspace,
// all projects **must** be standalone if workspace.json doesn't exist
// since the NxScopedHost already handles the standalone config case,
// lets pass them as standalone.
projects: Object.fromEntries(
Object.entries(workspace.projects).map(([project, config]) => [
project,
config.root,
])
),
});
}
// no match, default to existing behavior
if (!workspaceJsonOverride && !nxJsonChange) {
return super.read(path);
}
// we try to format it, if it changes, return it, otherwise return the original change
try {
return this.__readWorkspaceConfiguration(actualConfigFileName, {
// we are overriding workspaceJson + nxJson,
workspace: workspaceJsonOverride,
nx: nxJsonChange
? of(parseJson(nxJsonChange.content.toString()))
: null,
});
} catch (e) {
return super.read(path);
}
} else {
const match = findMatchingFileChange(this.host, path);
if (match) {
// found a matching change in the host
return of(Buffer.from(match.content));
} else if (
// found a change to workspace config, and reading a project config file
basename(path) === 'project.json' &&
findWorkspaceConfigFileChange(this.host)
) {
return of(this.host.read(path));
} else {
// found neither, use default read method
return super.read(path);
}
}
}
exists(path: Path): Observable<boolean> {
if (isWorkspaceConfigPath(path)) {
return findWorkspaceConfigFileChange(this.host)
? of(true)
: super.exists(path);
} else {
return findMatchingFileChange(this.host, path)
? of(true)
: super.exists(path);
}
}
isDirectory(path: Path): Observable<boolean> {
return super.isDirectory(path).pipe(
catchError(() => of(false)),
switchMap((isDirectory) =>
isDirectory
? of(true)
: of(this.host.exists(path) && !this.host.isFile(path))
)
);
}
isFile(path: Path): Observable<boolean> {
if (isWorkspaceConfigPath(path)) {
return findWorkspaceConfigFileChange(this.host)
? of(true)
: super.isFile(path);
} else {
return findMatchingFileChange(this.host, path)
? of(true)
: super.isFile(path);
}
}
list(path: Path): Observable<PathFragment[]> {
const fragments = this.host.children(path).map((child) => fragment(child));
return of(fragments);
}
}
type WorkspaceConfigFileChange = FileChange & {
path: ConfigFilePath;
};
function findWorkspaceConfigFileChange(host: Tree): WorkspaceConfigFileChange {
return host
.listChanges()
.find(
(f) => f.path == 'workspace.json' || f.path == 'angular.json'
) as WorkspaceConfigFileChange;
}
function findCreatedProjects(host: Tree): FileChange[] {
return host
.listChanges()
.filter(
(f) =>
(basename(f.path) === 'project.json' ||
basename(f.path) === 'package.json') &&
f.type === 'CREATE'
);
}
function findDeletedProjects(host: Tree): FileChange[] {
return host
.listChanges()
.filter((f) => basename(f.path) === 'project.json' && f.type === 'DELETE');
}
function findMatchingFileChange(host: Tree, path: Path) {
const targetPath = path.startsWith('/') ? path.substring(1) : path.toString();
return host
.listChanges()
.find((f) => f.path === targetPath && f.type !== 'DELETE');
}
function isWorkspaceConfigPath(p: Path | string) {
return (
p === 'angular.json' ||
p === '/angular.json' ||
p === 'workspace.json' ||
p === '/workspace.json'
);
}
function processConfigWhenReading(content: ArrayBuffer) {
try {
const json = parseJson(Buffer.from(content).toString());
Object.values(json.projects).forEach((p: any) => {
try {
Object.values(p.architect || p.targets).forEach((e: any) => {
if (
(e.builder === '@nrwl/jest:jest' ||
e.executor === '@nrwl/jest:jest') &&
!e.options.tsConfig
) {
e.options.tsConfig = `${p.root}/tsconfig.spec.json`;
}
});
} catch (e) {}
});
return Buffer.from(serializeJson(json));
} catch (e) {
return content;
}
}
function processConfigWhenWriting(content: ArrayBuffer) {
try {
const json = parseJson(Buffer.from(content).toString());
Object.values(json.projects).forEach((p: any) => {
try {
Object.values(p.architect || p.targets).forEach((e: any) => {
if (
(e.builder === '@nrwl/jest:jest' ||
e.executor === '@nrwl/jest:jest') &&
e.options.tsConfig
) {
delete e.options.tsConfig;
}
});
} catch (e) {}
});
return Buffer.from(serializeJson(json));
} catch (e) {
return content;
}
}
export async function generate(
root: string,
opts: GenerateOptions,
verbose: boolean
) {
const logger = getLogger(verbose);
const fsHost = new NxScopedHost(root);
const workflow = createWorkflow(fsHost, root, opts);
const collection = getCollection(workflow, opts.collectionName);
const schematic = collection.createSchematic(opts.generatorName, true);
return (
await runSchematic(
fsHost,
root,
workflow,
logger as any,
{ ...opts, generatorName: schematic.description.name },
schematic
)
).status;
}
function createPromptProvider() {
interface Prompt {
name: string;
type: 'input' | 'select' | 'multiselect' | 'confirm' | 'numeral';
message: string;
initial?: any;
choices?: (string | { name: string; message: string })[];
validate?: (value: string) => boolean | string;
}
return (definitions: Array<any>) => {
const questions: Prompt[] = definitions.map((definition) => {
const question: Prompt = {
name: definition.id,
message: definition.message,
} as any;
if (definition.default) {
question.initial = definition.default;
}
const validator = definition.validator;
if (validator) {
question.validate = (input) => validator(input);
}
switch (definition.type) {
case 'string':
case 'input':
return { ...question, type: 'input' };
case 'boolean':
case 'confirmation':
case 'confirm':
return { ...question, type: 'confirm' };
case 'number':
case 'numeral':
return { ...question, type: 'numeral' };
case 'list':
return {
...question,
type: !!definition.multiselect ? 'multiselect' : 'select',
choices:
definition.items &&
definition.items.map((item) => {
if (typeof item == 'string') {
return item;
} else {
return {
message: item.label,
name: item.value,
};
}
}),
};
default:
return { ...question, type: definition.type };
}
});
return require('enquirer').prompt(questions);
};
}
export async function runMigration(
root: string,
packageName: string,
migrationName: string,
isVerbose: boolean
) {
const logger = getLogger(isVerbose);
const fsHost = new NxScopedHost(root);
const workflow = createWorkflow(fsHost, root, {});
const collection = resolveMigrationsCollection(packageName);
return workflow
.execute({
collection,
schematic: migrationName,
options: {},
debug: false,
logger: logger as any,
})
.toPromise();
}
function resolveMigrationsCollection(name: string): string {
let collectionPath: string | undefined = undefined;
if (name.startsWith('.') || name.startsWith('/')) {
name = resolve(name);
}
if (extname(name)) {
collectionPath = require.resolve(name);
} else {
let packageJsonPath;
try {
packageJsonPath = require.resolve(join(name, 'package.json'), {
paths: [process.cwd()],
});
} catch (e) {
// workaround for a bug in node 12
packageJsonPath = require.resolve(
join(process.cwd(), name, 'package.json')
);
}
// eslint-disable-next-line @typescript-eslint/no-var-requires
const packageJson = require(packageJsonPath);
let pkgJsonSchematics =
packageJson['nx-migrations'] ?? packageJson['ng-update'];
if (!pkgJsonSchematics) {
throw new Error(`Could not find migrations in package: "${name}"`);
}
if (typeof pkgJsonSchematics != 'string') {
pkgJsonSchematics = pkgJsonSchematics.migrations;
}
collectionPath = require.resolve(pkgJsonSchematics, {
paths: [dirname(packageJsonPath)],
});
}
try {
if (collectionPath) {
readJsonFile(collectionPath);
return collectionPath;
}
} catch {
throw new Error(`Invalid migration file in package: "${name}"`);
}
throw new Error(`Collection cannot be resolved: "${name}"`);
}
function convertEventTypeToHandleMultipleConfigNames(
host: Tree,
eventPath: string,
content: Buffer | never
) {
const actualConfigName = host.exists('/angular.json')
? 'angular.json'
: 'workspace.json';
const isWorkspaceConfig =
eventPath === 'angular.json' || eventPath === 'workspace.json';
if (isWorkspaceConfig) {
let isNewFormat = true;
try {
isNewFormat =
parseJson(host.read(actualConfigName, 'utf-8')).version === 2;
} catch (e) {}
if (content && isNewFormat) {
const formatted = toNewFormat(parseJson(content.toString()));
if (formatted) {
return {
eventPath: actualConfigName,
content: Buffer.from(serializeJson(formatted)),
};
} else {
return { eventPath: actualConfigName, content };
}
} else {
return { eventPath: actualConfigName, content };
}
} else {
return { eventPath, content };
}
}
let collectionResolutionOverrides = null;
let mockedSchematics = null;
/**
* By default, Angular Devkit schematic collections will be resolved using the Node resolution.