forked from nrwl/nx
/
project-configuration.ts
620 lines (577 loc) · 17.8 KB
/
project-configuration.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
import { basename, dirname, join, relative } from 'path';
import type { NxJsonConfiguration } from '../../config/nx-json';
import {
ProjectConfiguration,
RawProjectsConfigurations,
ProjectsConfigurations,
} from '../../config/workspace-json-project-json';
import {
buildWorkspaceConfigurationFromGlobs,
deduplicateProjectFiles,
globForProjectFiles,
reformattedWorkspaceJsonOrNull,
toNewFormat,
} from '../../config/workspaces';
import { PackageJson } from '../../utils/package-json';
import { joinPathFragments, normalizePath } from '../../utils/path';
import type { Tree } from '../tree';
import { readJson, updateJson, writeJson } from './json';
export type WorkspaceConfiguration = Omit<ProjectsConfigurations, 'projects'> &
Partial<NxJsonConfiguration>;
/**
* Adds project configuration to the Nx workspace.
*
* The project configuration is stored in workspace.json or the associated project.json file.
* The utility will update either files.
*
* @param tree - the file system tree
* @param projectName - unique name. Often directories are part of the name (e.g., mydir-mylib)
* @param projectConfiguration - project configuration
* @param standalone - should the project use package.json? If false, the project config is inside workspace.json
*/
export function addProjectConfiguration(
tree: Tree,
projectName: string,
projectConfiguration: ProjectConfiguration,
standalone?: boolean
): void {
standalone = standalone ?? shouldDefaultToUsingStandaloneConfigs(tree);
setProjectConfiguration(
tree,
projectName,
projectConfiguration,
'create',
standalone
);
}
/**
* Updates the configuration of an existing project.
*
* The project configuration is stored in workspace.json or the associated project.json file.
* The utility will update either files.
*
* @param tree - the file system tree
* @param projectName - unique name. Often directories are part of the name (e.g., mydir-mylib)
* @param projectConfiguration - project configuration
*/
export function updateProjectConfiguration(
tree: Tree,
projectName: string,
projectConfiguration: ProjectConfiguration
): void {
setProjectConfiguration(tree, projectName, projectConfiguration, 'update');
}
/**
* Removes the configuration of an existing project.
*
* The project configuration is stored in workspace.json or the associated project.json file.
* The utility will update either file.
*/
export function removeProjectConfiguration(
tree: Tree,
projectName: string
): void {
setProjectConfiguration(tree, projectName, undefined, 'delete');
}
/**
* Get a map of all projects in a workspace.
*
* Use {@link readProjectConfiguration} if only one project is needed.
*/
export function getProjects(tree: Tree): Map<string, ProjectConfiguration> {
const workspace = readWorkspace(tree);
return new Map(
Object.keys(workspace.projects || {}).map((projectName) => {
return [projectName, getProjectConfiguration(projectName, workspace)];
})
);
}
/**
* Read general workspace configuration such as the default project or cli settings
*
* This does _not_ provide projects configuration, use {@link readProjectConfiguration} instead.
*/
export function readWorkspaceConfiguration(tree: Tree): WorkspaceConfiguration {
const { projects, ...workspace } = readRawWorkspaceJson(tree); // Create a new object, without projects
let nxJson = readNxJson(tree);
if (nxJson === null) {
return workspace;
}
return {
...workspace,
...nxJson,
};
}
/**
* Update general workspace configuration such as the default project or cli settings.
*
* This does _not_ update projects configuration, use {@link updateProjectConfiguration} or {@link addProjectConfiguration} instead.
*/
export function updateWorkspaceConfiguration(
tree: Tree,
workspaceConfig: WorkspaceConfiguration
): void {
const {
// Nx Json Properties
cli,
defaultProject,
generators,
implicitDependencies,
plugins,
pluginsConfig,
npmScope,
namedInputs,
targetDefaults,
targetDependencies,
workspaceLayout,
tasksRunnerOptions,
affected,
extends: ext,
} = workspaceConfig;
const nxJson: Required<NxJsonConfiguration> = {
implicitDependencies,
plugins,
pluginsConfig,
npmScope,
namedInputs,
targetDefaults,
targetDependencies,
workspaceLayout,
tasksRunnerOptions,
affected,
cli,
generators,
defaultProject,
extends: ext,
};
if (tree.exists('nx.json')) {
updateJson<NxJsonConfiguration>(tree, 'nx.json', (json) => {
if (json.extends) {
const nxJsonExtends = readNxJsonExtends(tree, json.extends);
const changedPropsOfNxJson = {};
Object.keys(nxJson).forEach((prop) => {
if (
JSON.stringify(nxJson[prop], null, 2) !=
JSON.stringify(nxJsonExtends[prop], null, 2)
) {
changedPropsOfNxJson[prop] = nxJson[prop];
}
});
return { ...json, ...changedPropsOfNxJson };
} else {
return { ...json, ...nxJson };
}
});
}
// Only prop in workspace.json is version. If there is no
// workspace.json file, this f(x) doesn't update anything
// in project config.
const workspacePath = getWorkspacePath(tree);
if (workspacePath) {
updateJson<ProjectsConfigurations>(tree, workspacePath, (json) => {
const config = {
...json,
version: workspaceConfig.version,
};
if (!(workspaceConfig as any).newProjectRoot) {
delete (config as any).newProjectRoot;
}
return config;
});
}
}
function readNxJsonExtends(tree: Tree, extendsPath: string) {
try {
return readJson(
tree,
relative(
tree.root,
require.resolve(extendsPath, {
paths: [tree.root],
})
)
);
} catch (e) {
throw new Error(`Unable to resolve nx.json extends. Error: ${e.message}`);
}
}
/**
* Reads a project configuration.
*
* The project configuration is stored in workspace.json or the associated project.json file.
* The utility will read from either file.
*
* @param tree - the file system tree
* @param projectName - unique name. Often directories are part of the name (e.g., mydir-mylib)
* @throws If supplied projectName cannot be found
*/
export function readProjectConfiguration(
tree: Tree,
projectName: string
): ProjectConfiguration {
const workspace = readWorkspace(tree);
if (!workspace.projects[projectName]) {
throw new Error(
getWorkspacePath(tree)
? `Cannot find configuration for '${projectName}' in ${getWorkspacePath(
tree
)}.`
: `Cannot find configuration for '${projectName}'`
);
}
return getProjectConfiguration(projectName, workspace);
}
export function readNxJson(tree: Tree): NxJsonConfiguration | null {
if (!tree.exists('nx.json')) {
return null;
}
let nxJson = readJson<NxJsonConfiguration>(tree, 'nx.json');
if (nxJson.extends) {
nxJson = { ...readNxJsonExtends(tree, nxJson.extends), ...nxJson };
}
return nxJson;
}
/**
* Returns if a project has a standalone configuration (project.json).
*
* @param tree - the file system tree
* @param project - the project name
*/
export function isStandaloneProject(tree: Tree, project: string): boolean {
const path = getWorkspacePath(tree);
const rawWorkspace =
path && tree.exists(path)
? readJson<RawProjectsConfigurations>(tree, path)
: null;
if (rawWorkspace) {
const projectConfig = rawWorkspace.projects?.[project];
return typeof projectConfig === 'string';
}
return true;
}
function getProjectConfiguration(
projectName: string,
workspace: ProjectsConfigurations
): ProjectConfiguration {
return {
...readWorkspaceSection(workspace, projectName),
};
}
function readWorkspaceSection(
workspace: ProjectsConfigurations,
projectName: string
) {
return workspace.projects[projectName];
}
function setProjectConfiguration(
tree: Tree,
projectName: string,
projectConfiguration: ProjectConfiguration,
mode: 'create' | 'update' | 'delete',
standalone: boolean = false
): void {
if (mode === 'delete') {
addProjectToWorkspaceJson(
tree,
projectName,
readProjectConfiguration(tree, projectName),
mode
);
return;
}
if (!projectConfiguration) {
throw new Error(
`Cannot ${mode} "${projectName}" with value ${projectConfiguration}`
);
}
addProjectToWorkspaceJson(
tree,
projectName,
projectConfiguration,
mode,
standalone
);
}
export function getRelativeProjectJsonSchemaPath(
tree: Tree,
project: ProjectConfiguration
): string {
return normalizePath(
relative(
join(tree.root, project.root),
join(tree.root, 'node_modules/nx/schemas/project-schema.json')
)
);
}
function addProjectToWorkspaceJson(
tree: Tree,
projectName: string,
project: ProjectConfiguration,
mode: 'create' | 'update' | 'delete',
standalone: boolean = false
) {
const workspaceConfigPath = getWorkspacePath(tree);
const workspaceJson = readRawWorkspaceJson(tree);
if (workspaceConfigPath) {
validateProjectConfigurationOperationsGivenWorkspaceJson(
mode,
workspaceJson,
projectName
);
} else {
validateProjectConfigurationOperationsWithoutWorkspaceJson(
mode,
projectName,
project.root,
tree
);
}
const projectConfigFile =
(mode === 'create' && standalone) || !workspaceConfigPath
? joinPathFragments(project.root, 'project.json')
: getProjectFileLocation(tree, projectName);
const jsonSchema =
projectConfigFile && mode === 'create'
? { $schema: getRelativeProjectJsonSchemaPath(tree, project) }
: {};
if (projectConfigFile) {
if (mode === 'delete') {
tree.delete(projectConfigFile);
delete workspaceJson.projects[projectName];
} else {
// keep real workspace up to date
if (workspaceConfigPath && mode === 'create') {
workspaceJson.projects[projectName] = project.root;
}
// update the project.json file
writeJson(tree, projectConfigFile, {
name: mode === 'create' ? projectName : project.name ?? projectName,
...jsonSchema,
...project,
root: undefined,
});
}
} else if (mode === 'delete') {
delete workspaceJson.projects[projectName];
} else {
workspaceJson.projects[projectName] = project;
}
if (workspaceConfigPath && tree.exists(workspaceConfigPath)) {
writeJson(
tree,
workspaceConfigPath,
reformattedWorkspaceJsonOrNull(workspaceJson) ?? workspaceJson
);
}
}
/**
* Read the workspace configuration, including projects.
*/
export function readWorkspace(tree: Tree): ProjectsConfigurations {
const workspaceJson = inlineProjectConfigurationsWithTree(tree);
const originalVersion = workspaceJson.version;
return {
...toNewFormat(workspaceJson),
version: originalVersion,
};
}
/**
* This has to be separate from the inline functionality inside nx,
* as the functionality in nx does not use a Tree. Changes made during
* a generator would not be present during runtime execution.
* @returns
*/
function inlineProjectConfigurationsWithTree(
tree: Tree
): ProjectsConfigurations {
const workspaceJson = readRawWorkspaceJson(tree);
Object.entries(workspaceJson.projects || {}).forEach(([project, config]) => {
if (typeof config === 'string') {
const configFileLocation = joinPathFragments(config, 'project.json');
workspaceJson.projects[project] = {
root: config,
...readJson<ProjectConfiguration>(tree, configFileLocation),
};
}
});
return workspaceJson as ProjectsConfigurations;
}
/**
* Used to ensure that projects created during
* the same devkit generator run show up when
* there is no workspace.json file, as `glob`
* cannot find them.
*
* We exclude the root `package.json` from this list unless
* considered a project during workspace generation
*/
function findCreatedProjects(tree: Tree) {
const createdProjectFiles = [];
for (const change of tree.listChanges()) {
if (change.type === 'CREATE') {
const fileName = basename(change.path);
// all created project json files are created projects
if (fileName === 'project.json') {
createdProjectFiles.push(change.path);
} else if (fileName === 'package.json') {
// created package.json files are projects by default *unless* they are at the root
const includedByDefault = change.path === 'package.json' ? false : true;
// If the file should be included by default
if (includedByDefault) {
createdProjectFiles.push(change.path);
} else {
const contents: PackageJson = JSON.parse(change.content.toString());
// if the file should be included by the Nx property
if (contents.nx) {
createdProjectFiles.push(change.path);
}
}
}
}
}
return deduplicateProjectFiles(createdProjectFiles);
}
/**
* Used to ensure that projects created during
* the same devkit generator run show up when
* there is no workspace.json file, as `glob`
* cannot find them.
*/
function findDeletedProjects(tree: Tree) {
return tree.listChanges().filter((f) => {
const fileName = basename(f.path);
return (
f.type === 'DELETE' &&
(fileName === 'project.json' || fileName === 'package.json')
);
});
}
let staticFSWorkspace: RawProjectsConfigurations;
let cachedTree: Tree;
function readRawWorkspaceJson(tree: Tree): RawProjectsConfigurations {
const path = getWorkspacePath(tree);
if (path && tree.exists(path)) {
// `workspace.json` exists, use it.
return readJson<RawProjectsConfigurations>(tree, path);
} else {
const nxJson = readNxJson(tree);
const createdProjects = buildWorkspaceConfigurationFromGlobs(
nxJson,
findCreatedProjects(tree),
(file) => readJson(tree, file)
).projects;
// We already have built a cache but need to confirm it's the same tree
if (!staticFSWorkspace || tree !== cachedTree) {
staticFSWorkspace = buildWorkspaceConfigurationFromGlobs(
nxJson,
[...globForProjectFiles(tree.root, nxJson)],
(file) => readJson(tree, file)
);
cachedTree = tree;
}
const projects = { ...staticFSWorkspace.projects, ...createdProjects };
findDeletedProjects(tree).forEach((file) => {
const matchingStaticProject = Object.entries(projects).find(
([, config]) =>
typeof config === 'string'
? config === dirname(file.path)
: config.root === dirname(file.path)
);
if (matchingStaticProject) {
delete projects[matchingStaticProject[0]];
}
});
staticFSWorkspace = {
...staticFSWorkspace,
projects,
};
return staticFSWorkspace;
}
}
/**
* @description Determine where a project's configuration is located.
* @returns file path if separate from root config, null otherwise.
*/
function getProjectFileLocation(tree: Tree, project: string): string | null {
const rawWorkspace = readRawWorkspaceJson(tree);
const projectConfig = rawWorkspace.projects?.[project];
return typeof projectConfig === 'string'
? joinPathFragments(projectConfig, 'project.json')
: null;
}
function validateProjectConfigurationOperationsGivenWorkspaceJson(
mode: 'create' | 'update' | 'delete',
workspaceJson: RawProjectsConfigurations | ProjectsConfigurations | null,
projectName: string
) {
if (mode == 'create' && workspaceJson.projects[projectName]) {
throw new Error(
`Cannot create Project '${projectName}'. It already exists.`
);
}
if (mode == 'update' && !workspaceJson.projects[projectName]) {
throw new Error(
`Cannot update Project '${projectName}'. It does not exist.`
);
}
if (mode == 'delete' && !workspaceJson.projects[projectName]) {
throw new Error(
`Cannot delete Project '${projectName}'. It does not exist.`
);
}
}
function validateProjectConfigurationOperationsWithoutWorkspaceJson(
mode: 'create' | 'update' | 'delete',
projectName: string,
projectRoot: string,
tree: Tree
) {
if (
mode == 'create' &&
tree.exists(joinPathFragments(projectRoot, 'project.json'))
) {
throw new Error(
`Cannot create a new project at ${projectRoot}. It already exists.`
);
}
if (
mode == 'update' &&
!tree.exists(joinPathFragments(projectRoot, 'project.json'))
) {
throw new Error(
`Cannot update Project ${projectName} at ${projectRoot}. It doesn't exist or uses package.json configuration.`
);
}
if (mode == 'delete' && !tree.exists(joinPathFragments(projectRoot))) {
throw new Error(
`Cannot delete Project ${projectName}. It doesn't exist or uses package.json configuration.`
);
}
}
export function shouldDefaultToUsingStandaloneConfigs(tree: Tree): boolean {
const workspacePath = getWorkspacePath(tree);
const rawWorkspace =
workspacePath && tree.exists(workspacePath)
? readJson<RawProjectsConfigurations>(tree, workspacePath)
: null;
return !rawWorkspace
? true // if workspace.json doesn't exist, all projects **must** be standalone
: Object.values(rawWorkspace.projects).reduce(
// default for second, third... projects should be based on all projects being defined as a path
// for configuration read from ng schematics, this is determined by configFilePath's presence
(allStandalone, next) =>
allStandalone &&
(typeof next === 'string' || 'configFilePath' in next),
// default for first project should be true if using Nx Schema
rawWorkspace.version > 1
);
}
export function getWorkspacePath(
tree: Tree
): '/angular.json' | '/workspace.json' | null {
const possibleFiles: ('/angular.json' | '/workspace.json')[] = [
'/angular.json',
'/workspace.json',
];
return possibleFiles.filter((path) => tree.exists(path))[0];
}