-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
workspace.ts
628 lines (561 loc) · 16.1 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
import { existsSync } from 'fs';
import * as path from 'path';
import { appRootPath } from '../utils/app-root';
import { readJsonFile } from '../utils/fileutils';
import type { NxJsonConfiguration, NxJsonProjectConfiguration } from './nx';
import type { PackageManager } from './package-manager';
import { TaskGraph } from './tasks';
export interface Workspace
extends WorkspaceJsonConfiguration,
NxJsonConfiguration {
projects: Record<string, ProjectConfiguration & NxJsonProjectConfiguration>;
}
/**
* Workspace configuration
*/
export interface WorkspaceJsonConfiguration {
/**
* Version of the configuration format
*/
version: number;
/**
* Projects' configurations
*/
projects: { [projectName: string]: ProjectConfiguration };
/**
* Default project. When project isn't provided, the default project
* will be used. Convenient for small workspaces with one main application.
*/
defaultProject?: string;
/**
* List of default values used by generators.
*
* These defaults are global. They are used when no other defaults are configured.
*
* Example:
*
* ```
* {
* "@nrwl/react": {
* "library": {
* "style": "scss"
* }
* }
* }
* ```
*/
generators?: { [collectionName: string]: { [generatorName: string]: any } };
/**
* Default generator collection. It is used when no collection is provided.
*/
cli?: {
packageManager?: PackageManager;
defaultCollection?: string;
};
}
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 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 } };
}
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:package'
*/
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 {
return 'workspace.json';
}
}
/**
* 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;
/**
* 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) || null;
}
calculateDefaultProjectName(cwd: string, wc: WorkspaceJsonConfiguration) {
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 {
const w = readJsonFile(
path.join(this.root, workspaceConfigName(this.root))
);
return resolveNewFormatWithInlineProjects(w, this.root);
}
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];
}
}
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) {
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) {
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,
includeConfigFilePath = false
) {
const inlined = inlineProjectConfigurations(w, root, includeConfigFilePath);
const formatted = toOldFormatOrNull(inlined);
return formatted ? formatted : inlined;
}
export function resolveNewFormatWithInlineProjects(
w: any,
root: string = appRootPath
) {
return toNewFormat(inlineProjectConfigurations(w, root));
}
export function inlineProjectConfigurations(
w: any,
root: string = appRootPath,
includeConfigFilePath = false
) {
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);
if (includeConfigFilePath) {
fileConfig.configFilePath = configFilePath;
}
w.projects[project] = fileConfig;
}
}
);
return w;
}
// 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];
}
});
}