/
workspace.ts
904 lines (811 loc) · 24.7 KB
/
workspace.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
import { existsSync, readFileSync } from 'fs';
import * as path from 'path';
import { appRootPath } from '../utils/app-root';
import { readJsonFile } from '../utils/fileutils';
import type { NxJsonConfiguration } from './nx';
import { TaskGraph } from './tasks';
import { logger } from './logger';
import { sync as globSync } from 'fast-glob';
import ignore, { Ignore } from 'ignore';
import { basename, dirname, join } from 'path';
import { performance } from 'perf_hooks';
import { loadNxPlugins } from './nx-plugin';
export interface Workspace
extends WorkspaceJsonConfiguration,
NxJsonConfiguration {
projects: Record<string, ProjectConfiguration>;
}
/**
* Workspace configuration
*/
export interface WorkspaceJsonConfiguration {
/**
* Version of the configuration format
*/
version: number;
/**
* Projects' projects
*/
projects: {
[projectName: string]: ProjectConfiguration;
};
}
export interface RawWorkspaceJsonConfiguration
extends Omit<WorkspaceJsonConfiguration, 'projects'> {
projects: { [projectName: string]: ProjectConfiguration | string };
}
/**
* Type of project supported
*/
export type ProjectType = 'library' | 'application';
/**
* Project configuration
*/
export interface ProjectConfiguration {
/**
* Project's name. Optional if specified in workspace.json
*/
name?: string;
/**
* Project's targets
*/
targets?: { [targetName: string]: TargetConfiguration };
/**
* Project's location relative to the root of the workspace
*/
root: string;
/**
* The location of project's sources relative to the root of the workspace
*/
sourceRoot?: string;
/**
* Project type
*/
projectType?: ProjectType;
/**
* List of default values used by generators.
*
* These defaults are project specific.
*
* Example:
*
* ```
* {
* "@nrwl/react": {
* "library": {
* "style": "scss"
* }
* }
* }
* ```
*/
generators?: { [collectionName: string]: { [generatorName: string]: any } };
/**
* List of projects which are added as a dependency
*/
implicitDependencies?: string[];
/**
* List of tags used by nx-enforce-module-boundaries / project graph
*/
tags?: string[];
}
export interface TargetDependencyConfig {
/**
* This the projects that the targets belong to
*
* 'self': This target depends on another target of the same project
* 'deps': This target depends on targets of the projects of it's deps.
*/
projects: 'self' | 'dependencies';
/**
* The name of the target
*/
target: string;
}
/**
* Target's configuration
*/
export interface TargetConfiguration {
/**
* The executor/builder used to implement the target.
*
* Example: '@nrwl/web:rollup'
*/
executor: string;
/**
* List of the target's outputs. The outputs will be cached by the Nx computation
* caching engine.
*/
outputs?: string[];
/**
* This describes other targets that a target depends on.
*/
dependsOn?: TargetDependencyConfig[];
/**
* Target's options. They are passed in to the executor.
*/
options?: any;
/**
* Sets of options
*/
configurations?: { [config: string]: any };
/**
* A default named configuration to use when a target configuration is not provided.
*/
defaultConfiguration?: string;
}
export function workspaceConfigName(root: string) {
if (existsSync(path.join(root, 'angular.json'))) {
return 'angular.json';
} else if (existsSync(path.join(root, 'workspace.json'))) {
return 'workspace.json';
} else {
return null;
}
}
/**
* A callback function that is executed after changes are made to the file system
*/
export type GeneratorCallback = () => void | Promise<void>;
/**
* A function that schedules updates to the filesystem to be done atomically
*/
export type Generator<T = unknown> = (
tree,
schema: T
) => void | GeneratorCallback | Promise<void | GeneratorCallback>;
export interface ExecutorConfig {
schema: any;
hasherFactory?: () => any;
implementationFactory: () => Executor;
batchImplementationFactory?: () => TaskGraphExecutor;
}
/**
* Implementation of a target of a project
*/
export type Executor<T = any> = (
/**
* Options that users configure or pass via the command line
*/
options: T,
context: ExecutorContext
) =>
| Promise<{ success: boolean }>
| AsyncIterableIterator<{ success: boolean }>;
/**
* Implementation of a target of a project that handles multiple projects to be batched
*/
export type TaskGraphExecutor<T = any> = (
/**
* Graph of Tasks to be executed
*/
taskGraph: TaskGraph,
/**
* Map of Task IDs to options for the task
*/
options: Record<string, T>,
/**
* Set of overrides for the overall execution
*/
overrides: T,
context: ExecutorContext
) => Promise<Record<string, { success: boolean; terminalOutput: string }>>;
/**
* Context that is passed into an executor
*/
export interface ExecutorContext {
/**
* The root of the workspace
*/
root: string;
/**
* The name of the project being executed on
*/
projectName?: string;
/**
* The name of the target being executed
*/
targetName?: string;
/**
* The name of the configuration being executed
*/
configurationName?: string;
/**
* The configuration of the target being executed
*/
target?: TargetConfiguration;
/**
* The full workspace configuration
*/
workspace: WorkspaceJsonConfiguration & NxJsonConfiguration;
/**
* The current working directory
*/
cwd: string;
/**
* Enable verbose logging
*/
isVerbose: boolean;
}
export class Workspaces {
constructor(private root: string) {}
relativeCwd(cwd: string) {
return path.relative(this.root, cwd).replace(/\\/g, '/') || null;
}
calculateDefaultProjectName(
cwd: string,
wc: WorkspaceJsonConfiguration & NxJsonConfiguration
) {
const relativeCwd = this.relativeCwd(cwd);
if (relativeCwd) {
const matchingProject = Object.keys(wc.projects).find((p) => {
const projectRoot = wc.projects[p].root;
return (
relativeCwd == projectRoot ||
relativeCwd.startsWith(`${projectRoot}/`)
);
});
if (matchingProject) return matchingProject;
}
return wc.defaultProject;
}
readWorkspaceConfiguration(): WorkspaceJsonConfiguration &
NxJsonConfiguration {
const nxJsonPath = path.join(this.root, 'nx.json');
const nxJson = readNxJson(nxJsonPath);
const workspaceFile = workspaceConfigName(this.root);
const workspacePath = workspaceFile
? path.join(this.root, workspaceFile)
: null;
const workspace =
workspacePath && existsSync(workspacePath)
? this.readFromWorkspaceJson()
: buildWorkspaceConfigurationFromGlobs(
nxJson,
globForProjectFiles(this.root, nxJson),
(path) => readJsonFile(join(this.root, path))
);
assertValidWorkspaceConfiguration(nxJson);
return { ...workspace, ...nxJson };
}
isNxExecutor(nodeModule: string, executor: string) {
const schema = this.readExecutor(nodeModule, executor).schema;
return schema['cli'] === 'nx';
}
isNxGenerator(collectionName: string, generatorName: string) {
const schema = this.readGenerator(collectionName, generatorName).schema;
return schema['cli'] === 'nx';
}
readExecutor(nodeModule: string, executor: string): ExecutorConfig {
try {
const { executorsFilePath, executorConfig } = this.readExecutorsJson(
nodeModule,
executor
);
const executorsDir = path.dirname(executorsFilePath);
const schemaPath = path.join(executorsDir, executorConfig.schema || '');
const schema = readJsonFile(schemaPath);
if (!schema.properties || typeof schema.properties !== 'object') {
schema.properties = {};
}
const implementationFactory = this.getImplementationFactory<Executor>(
executorConfig.implementation,
executorsDir
);
const batchImplementationFactory = executorConfig.batchImplementation
? this.getImplementationFactory<TaskGraphExecutor>(
executorConfig.batchImplementation,
executorsDir
)
: null;
const hasherFactory = executorConfig.hasher
? this.getImplementationFactory<Function>(
executorConfig.hasher,
executorsDir
)
: null;
return {
schema,
implementationFactory,
batchImplementationFactory,
hasherFactory,
};
} catch (e) {
throw new Error(
`Unable to resolve ${nodeModule}:${executor}.\n${e.message}`
);
}
}
readGenerator(collectionName: string, generatorName: string) {
try {
const { generatorsFilePath, generatorsJson, normalizedGeneratorName } =
this.readGeneratorsJson(collectionName, generatorName);
const generatorsDir = path.dirname(generatorsFilePath);
const generatorConfig =
generatorsJson.generators?.[normalizedGeneratorName] ||
generatorsJson.schematics?.[normalizedGeneratorName];
const schemaPath = path.join(generatorsDir, generatorConfig.schema || '');
const schema = readJsonFile(schemaPath);
if (!schema.properties || typeof schema.properties !== 'object') {
schema.properties = {};
}
generatorConfig.implementation =
generatorConfig.implementation || generatorConfig.factory;
const implementationFactory = this.getImplementationFactory<Generator>(
generatorConfig.implementation,
generatorsDir
);
return { normalizedGeneratorName, schema, implementationFactory };
} catch (e) {
throw new Error(
`Unable to resolve ${collectionName}:${generatorName}.\n${e.message}`
);
}
}
private getImplementationFactory<T>(
implementation: string,
directory: string
): () => T {
const [implementationModulePath, implementationExportName] =
implementation.split('#');
return () => {
const module = require(path.join(directory, implementationModulePath));
return module[implementationExportName || 'default'] as T;
};
}
private readExecutorsJson(nodeModule: string, executor: string) {
const packageJsonPath = require.resolve(`${nodeModule}/package.json`, {
paths: this.resolvePaths(),
});
const packageJson = readJsonFile(packageJsonPath);
const executorsFile = packageJson.executors ?? packageJson.builders;
if (!executorsFile) {
throw new Error(
`The "${nodeModule}" package does not support Nx executors.`
);
}
const executorsFilePath = require.resolve(
path.join(path.dirname(packageJsonPath), executorsFile)
);
const executorsJson = readJsonFile(executorsFilePath);
const executorConfig: {
implementation: string;
batchImplementation?: string;
schema: string;
hasher?: string;
} =
executorsJson.executors?.[executor] || executorsJson.builders?.[executor];
if (!executorConfig) {
throw new Error(
`Cannot find executor '${executor}' in ${executorsFilePath}.`
);
}
return { executorsFilePath, executorConfig };
}
private readGeneratorsJson(collectionName: string, generator: string) {
let generatorsFilePath;
if (collectionName.endsWith('.json')) {
generatorsFilePath = require.resolve(collectionName, {
paths: this.resolvePaths(),
});
} else {
const packageJsonPath = require.resolve(
`${collectionName}/package.json`,
{
paths: this.resolvePaths(),
}
);
const packageJson = readJsonFile(packageJsonPath);
const generatorsFile = packageJson.generators ?? packageJson.schematics;
if (!generatorsFile) {
throw new Error(
`The "${collectionName}" package does not support Nx generators.`
);
}
generatorsFilePath = require.resolve(
path.join(path.dirname(packageJsonPath), generatorsFile)
);
}
const generatorsJson = readJsonFile(generatorsFilePath);
let normalizedGeneratorName =
findFullGeneratorName(generator, generatorsJson.generators) ||
findFullGeneratorName(generator, generatorsJson.schematics);
if (!normalizedGeneratorName) {
for (let parent of generatorsJson.extends || []) {
try {
return this.readGeneratorsJson(parent, generator);
} catch (e) {}
}
throw new Error(
`Cannot find generator '${generator}' in ${generatorsFilePath}.`
);
}
return { generatorsFilePath, generatorsJson, normalizedGeneratorName };
}
private resolvePaths() {
return this.root ? [this.root, __dirname] : [__dirname];
}
private readFromWorkspaceJson() {
const rawWorkspace = readJsonFile(
path.join(this.root, workspaceConfigName(this.root))
);
return resolveNewFormatWithInlineProjects(rawWorkspace, this.root);
}
}
function assertValidWorkspaceConfiguration(
nxJson: NxJsonConfiguration & { projects?: any }
) {
// Assert valid workspace configuration
if (nxJson.projects) {
logger.warn(
'NX As of Nx 13, project configuration should be moved from nx.json to workspace.json/project.json. Please run "nx format" to fix this.'
);
}
}
function findFullGeneratorName(
name: string,
generators: {
[name: string]: { aliases?: string[] };
}
) {
if (generators) {
for (let [key, data] of Object.entries<{ aliases?: string[] }>(
generators
)) {
if (
key === name ||
(data.aliases && (data.aliases as string[]).includes(name))
) {
return key;
}
}
}
}
export function reformattedWorkspaceJsonOrNull(w: any) {
return w.version === 2 ? toNewFormatOrNull(w) : toOldFormatOrNull(w);
}
export function toNewFormat(w: any): WorkspaceJsonConfiguration {
const f = toNewFormatOrNull(w);
return f ?? w;
}
export function toNewFormatOrNull(w: any) {
let formatted = false;
Object.values(w.projects || {}).forEach((projectConfig: any) => {
if (projectConfig.architect) {
renamePropertyWithStableKeys(projectConfig, 'architect', 'targets');
formatted = true;
}
if (projectConfig.schematics) {
renamePropertyWithStableKeys(projectConfig, 'schematics', 'generators');
formatted = true;
}
Object.values(projectConfig.targets || {}).forEach((target: any) => {
if (target.builder !== undefined) {
renamePropertyWithStableKeys(target, 'builder', 'executor');
formatted = true;
}
});
});
if (w.schematics) {
renamePropertyWithStableKeys(w, 'schematics', 'generators');
formatted = true;
}
if (w.version !== 2) {
w.version = 2;
formatted = true;
}
return formatted ? w : null;
}
export function toOldFormatOrNull(w: any) {
let formatted = false;
Object.values(w.projects || {}).forEach((projectConfig: any) => {
if (typeof projectConfig === 'string') {
throw new Error(
"'project.json' files are incompatible with version 1 workspace schemas."
);
}
if (projectConfig.targets) {
renamePropertyWithStableKeys(projectConfig, 'targets', 'architect');
formatted = true;
}
if (projectConfig.generators) {
renamePropertyWithStableKeys(projectConfig, 'generators', 'schematics');
formatted = true;
}
Object.values(projectConfig.architect || {}).forEach((target: any) => {
if (target.executor !== undefined) {
renamePropertyWithStableKeys(target, 'executor', 'builder');
formatted = true;
}
});
});
if (w.generators) {
renamePropertyWithStableKeys(w, 'generators', 'schematics');
formatted = true;
}
if (w.version !== 1) {
w.version = 1;
formatted = true;
}
return formatted ? w : null;
}
export function resolveOldFormatWithInlineProjects(
w: any,
root: string = appRootPath
) {
const inlined = inlineProjectConfigurations(w, root);
const formatted = toOldFormatOrNull(inlined);
return formatted ? formatted : inlined;
}
export function resolveNewFormatWithInlineProjects(
w: any,
root: string = appRootPath
) {
return toNewFormat(inlineProjectConfigurations(w, root));
}
function inlineProjectConfigurations(w: any, root: string = appRootPath) {
Object.entries(w.projects || {}).forEach(
([project, config]: [string, any]) => {
if (typeof config === 'string') {
const configFilePath = path.join(root, config, 'project.json');
const fileConfig = readJsonFile(configFilePath);
w.projects[project] = fileConfig;
}
}
);
return w;
}
/**
* Reads an nx.json file from a given path or extends a local nx.json config.
*/
function readNxJson(nxJson: string): NxJsonConfiguration {
let nxJsonConfig: NxJsonConfiguration;
if (existsSync(nxJson)) {
nxJsonConfig = readJsonFile<NxJsonConfiguration>(nxJson);
} else {
nxJsonConfig = {} as NxJsonConfiguration;
}
if (nxJsonConfig.extends) {
const extendedNxJsonPath = require.resolve(nxJsonConfig.extends, {
paths: [dirname(nxJson)],
});
const baseNxJson = readJsonFile<NxJsonConfiguration>(extendedNxJsonPath);
nxJsonConfig = { ...baseNxJson, ...nxJsonConfig };
}
return nxJsonConfig;
}
/**
* Pulled from toFileName in names from @nrwl/devkit.
* Todo: Should refactor, not duplicate.
*/
export function toProjectName(
fileName: string,
nxJson: NxJsonConfiguration
): string {
const directory = dirname(fileName);
let { appsDir, libsDir } = nxJson?.workspaceLayout || {};
appsDir ??= 'apps';
libsDir ??= 'libs';
const parts = directory.split(/[\/\\]/g);
if ([appsDir, libsDir].includes(parts[0])) {
parts.splice(0, 1);
}
return parts.join('-').toLowerCase();
}
let projectGlobCache: string[];
let projectGlobCacheKey: string;
function getGlobPatternsFromPlugins(nxJson: NxJsonConfiguration): string[] {
const plugins = loadNxPlugins(nxJson?.plugins);
const patterns = [];
for (const plugin of plugins) {
if (!plugin.projectFilePatterns) {
continue;
}
for (const filePattern of plugin.projectFilePatterns) {
patterns.push('**/' + filePattern);
}
}
return patterns;
}
/**
* Get the package.json globs from package manager workspaces
*/
function getGlobPatternsFromPackageManagerWorkspaces(root: string): string[] {
// TODO: add support for pnpm
try {
const { workspaces } = readJsonFile(join(root, 'package.json'));
return (
workspaces?.map((pattern) => pattern + '/package.json') ?? [
'**/package.json',
]
);
} catch {
return ['**/package.json'];
}
}
export function globForProjectFiles(
root: string,
nxJson?: NxJsonConfiguration
) {
// Deal w/ Caching
const cacheKey = [root, ...(nxJson?.plugins || [])].join(',');
if (projectGlobCache && cacheKey === projectGlobCacheKey)
return projectGlobCache;
projectGlobCacheKey = cacheKey;
const projectGlobPatterns: string[] = [
'**/project.json',
...getGlobPatternsFromPackageManagerWorkspaces(root),
...getGlobPatternsFromPlugins(nxJson),
];
const combinedProjectGlobPattern = '{' + projectGlobPatterns.join(',') + '}';
performance.mark('start-glob-for-projects');
/**
* This configures the files and directories which we always want to ignore as part of file watching
* and which we know the location of statically (meaning irrespective of user configuration files).
* This has the advantage of being ignored directly within globSync
*
* Other ignored entries will need to be determined dynamically by reading and evaluating the user's
* .gitignore and .nxignore files below.
*/
const ALWAYS_IGNORE = [
join(root, 'node_modules'),
'**/node_modules',
join(root, 'dist'),
join(root, '.git'),
];
/**
* TODO: This utility has been implemented multiple times across the Nx codebase,
* discuss whether it should be moved to a shared location.
*/
const ig = ignore();
try {
ig.add(readFileSync(`${root}/.gitignore`, 'utf-8'));
} catch {}
try {
ig.add(readFileSync(`${root}/.nxignore`, 'utf-8'));
} catch {}
const globResults = globSync(combinedProjectGlobPattern, {
ignore: ALWAYS_IGNORE,
absolute: false,
cwd: root,
});
projectGlobCache = deduplicateProjectFiles(globResults, ig);
performance.mark('finish-glob-for-projects');
performance.measure(
'glob-for-project-files',
'start-glob-for-projects',
'finish-glob-for-projects'
);
return projectGlobCache;
}
export function deduplicateProjectFiles(files: string[], ig?: Ignore) {
const filtered = new Map();
files.forEach((file) => {
const projectFolder = dirname(file);
const projectFile = basename(file);
if (
ig?.ignores(file) || // file is in .gitignore or .nxignore
file === 'package.json' || // file is workspace root package json
// project.json or equivallent inferred project file has been found
(filtered.has(projectFolder) && projectFile !== 'project.json')
) {
return;
}
filtered.set(projectFolder, projectFile);
});
return Array.from(filtered.entries()).map(([folder, file]) =>
join(folder, file)
);
}
function buildProjectConfigurationFromPackageJson(
path: string,
packageJson: { name: string },
nxJson: NxJsonConfiguration
): ProjectConfiguration & { name: string } {
const directory = dirname(path).split('\\').join('/');
const npmPrefix = `@${nxJson.npmScope}/`;
let name = packageJson.name ?? toProjectName(directory, nxJson);
if (name.startsWith(npmPrefix)) {
name = name.replace(npmPrefix, '');
}
return {
root: directory,
sourceRoot: directory,
name,
};
}
export function inferProjectFromNonStandardFile(
file: string,
nxJson: NxJsonConfiguration
): ProjectConfiguration & { name: string } {
const directory = dirname(file).split('\\').join('/');
return {
name: toProjectName(file, nxJson),
root: directory,
};
}
export function buildWorkspaceConfigurationFromGlobs(
nxJson: NxJsonConfiguration,
projectFiles: string[] = globForProjectFiles(appRootPath, nxJson), // making this parameter allows devkit to pick up newly created projects
readJson: (string) => any = readJsonFile // making this an arg allows us to reuse in devkit
): WorkspaceJsonConfiguration {
const projects: Record<string, ProjectConfiguration> = {};
for (const file of projectFiles) {
const directory = dirname(file).split('\\').join('/');
const fileName = basename(file);
if (fileName === 'project.json') {
// Nx specific project configuration (`project.json` files) in the same
// directory as a package.json should overwrite the inferred package.json
// project configuration.
const configuration = readJson(file);
let name = configuration.name;
if (!configuration.name) {
name = toProjectName(file, nxJson);
}
if (!projects[name]) {
projects[name] = configuration;
} else {
logger.warn(
`Skipping project found at ${directory} since project ${name} already exists at ${projects[name].root}! Specify a unique name for the project to allow Nx to differentiate between the two projects.`
);
}
} else {
// We can infer projects from package.json files,
// if a package.json file is in a directory w/o a `project.json` file.
// this results in targets being inferred by Nx from package scripts,
// and the root / sourceRoot both being the directory.
if (fileName === 'package.json') {
const { name, ...config } = buildProjectConfigurationFromPackageJson(
file,
readJson(file),
nxJson
);
if (!projects[name]) {
projects[name] = config;
} else {
logger.warn(
`Skipping project found at ${directory} since project ${name} already exists at ${projects[name].root}! Specify a unique name for the project to allow Nx to differentiate between the two projects.`
);
}
} else {
// This project was created from an nx plugin.
// The only thing we know about the file is its location
const { name, ...config } = inferProjectFromNonStandardFile(
file,
nxJson
);
if (!projects[name]) {
projects[name] = config;
} else {
logger.error(
`Skipping project inferred from ${file} since project ${name} already exists.`
);
throw new Error();
}
}
}
}
return {
version: 2,
projects: projects,
};
}
// we have to do it this way to preserve the order of properties
// not to screw up the formatting
export function renamePropertyWithStableKeys(
obj: any,
from: string,
to: string
) {
const copy = { ...obj };
Object.keys(obj).forEach((k) => {
delete obj[k];
});
Object.keys(copy).forEach((k) => {
if (k === from) {
obj[to] = copy[k];
} else {
obj[k] = copy[k];
}
});
}