/
utils.ts
376 lines (334 loc) · 10.5 KB
/
utils.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
import { output } from '../utils/output';
import { Workspaces } from '../config/workspaces';
import { mergeNpmScriptsWithTargets } from '../utils/project-graph-utils';
import { existsSync } from 'fs';
import { join, relative } from 'path';
import {
loadNxPlugins,
mergePluginTargetsWithNxTargets,
} from '../utils/nx-plugin';
import { Task, TaskGraph } from '../config/task-graph';
import { ProjectGraph, ProjectGraphProjectNode } from '../config/project-graph';
import { TargetDependencyConfig } from '../config/workspace-json-project-json';
import { workspaceRoot } from '../utils/workspace-root';
import { NxJsonConfiguration } from '../config/nx-json';
import { joinPathFragments } from '../utils/path';
import { isRelativePath } from '../utils/fileutils';
import { serializeOverridesIntoCommandLine } from '../utils/serialize-overrides-into-command-line';
export function getCommandAsString(execCommand: string, task: Task) {
const args = getPrintableCommandArgsForTask(task);
return [execCommand, 'nx', ...args].join(' ').trim();
}
export function getDependencyConfigs(
{ project, target }: { project: string; target: string },
defaultDependencyConfigs: Record<string, (TargetDependencyConfig | string)[]>,
projectGraph: ProjectGraph
): TargetDependencyConfig[] | undefined {
// DependencyConfigs configured in workspace.json override configurations at the root.
const dependencyConfigs = expandDependencyConfigSyntaxSugar(
projectGraph.nodes[project].data?.targets[target]?.dependsOn ??
defaultDependencyConfigs[target] ??
[]
);
for (const dependencyConfig of dependencyConfigs) {
if (
dependencyConfig.projects !== 'dependencies' &&
dependencyConfig.projects !== 'self'
) {
output.error({
title: `dependsOn is improperly configured for ${project}:${target}`,
bodyLines: [
`dependsOn.projects is "${dependencyConfig.projects}" but should be "self" or "dependencies"`,
],
});
process.exit(1);
}
}
return dependencyConfigs;
}
function expandDependencyConfigSyntaxSugar(
deps: (TargetDependencyConfig | string)[]
): TargetDependencyConfig[] {
return deps.map((d) => {
if (typeof d === 'string') {
if (d.startsWith('^')) {
return { projects: 'dependencies', target: d.substring(1) };
} else {
return { projects: 'self', target: d };
}
} else {
return d;
}
});
}
export function getOutputs(
p: Record<string, ProjectGraphProjectNode>,
task: Task
) {
return getOutputsForTargetAndConfiguration(task, p[task.target.project]);
}
class InvalidOutputsError extends Error {
constructor(public outputs: string[], public invalidOutputs: Set<string>) {
super(InvalidOutputsError.createMessage(invalidOutputs));
}
private static createMessage(invalidOutputs: Set<string>) {
const invalidOutputsList =
'\n - ' + Array.from(invalidOutputs).join('\n - ');
return `The following outputs are invalid:${invalidOutputsList}\nPlease run "nx repair" to repair your configuration`;
}
}
export function validateOutputs(outputs: string[]) {
const invalidOutputs = new Set<string>();
for (const output of outputs) {
if (!/^{[\s\S]+}/.test(output)) {
invalidOutputs.add(output);
}
}
if (invalidOutputs.size > 0) {
throw new InvalidOutputsError(outputs, invalidOutputs);
}
}
export function transformLegacyOutputs(
projectRoot: string,
error: InvalidOutputsError
) {
return error.outputs.map((output) => {
if (!error.invalidOutputs.has(output)) {
return output;
}
const relativePath = isRelativePath(output)
? output
: relative(projectRoot, output);
const isWithinProject = !relativePath.startsWith('..');
return joinPathFragments(
isWithinProject ? '{projectRoot}' : '{workspaceRoot}',
isWithinProject ? relativePath : output
);
});
}
/**
* Returns the list of outputs that will be cached.
* @param task target + overrides
* @param node ProjectGraphProjectNode object that the task runs against
*/
export function getOutputsForTargetAndConfiguration(
task: Pick<Task, 'target' | 'overrides'>,
node: ProjectGraphProjectNode
): string[] {
const { target, configuration } = task.target;
const targetConfiguration = node.data.targets[target];
const options = {
...targetConfiguration.options,
...targetConfiguration?.configurations?.[configuration],
...task.overrides,
};
if (targetConfiguration?.outputs) {
try {
validateOutputs(targetConfiguration.outputs);
} catch (error) {
if (error instanceof InvalidOutputsError) {
// TODO(v16): start warning for invalid outputs
targetConfiguration.outputs = transformLegacyOutputs(
node.data.root,
error
);
} else {
throw error;
}
}
return targetConfiguration.outputs
.map((output: string) => {
return interpolate(output, {
projectRoot: node.data.root,
projectName: node.name,
project: { ...node.data, name: node.name }, // this is legacy
options,
});
})
.filter((output) => !!output && !output.match(/{.*}/));
}
// Keep backwards compatibility in case `outputs` doesn't exist
if (options.outputPath) {
return Array.isArray(options.outputPath)
? options.outputPath
: [options.outputPath];
} else if (target === 'build' || target === 'prepare') {
return [
`dist/${node.data.root}`,
`${node.data.root}/dist`,
`${node.data.root}/build`,
`${node.data.root}/public`,
];
} else {
return [];
}
}
export function interpolate(template: string, data: any): string {
if (template.includes('{workspaceRoot}', 1)) {
throw new Error(
`Output '${template}' is invalid. {workspaceRoot} can only be used at the beginning of the expression.`
);
}
if (data.projectRoot == '.' && template.includes('{projectRoot}', 1)) {
throw new Error(
`Output '${template}' is invalid. When {projectRoot} is '.', it can only be used at the beginning of the expression.`
);
}
let res = template.replace('{workspaceRoot}/', '');
if (data.projectRoot == '.') {
res = res.replace('{projectRoot}/', '');
}
return res.replace(/{([\s\S]+?)}/g, (match: string) => {
let value = data;
let path = match.slice(1, -1).trim().split('.');
for (let idx = 0; idx < path.length; idx++) {
if (!value[path[idx]]) {
return match;
}
value = value[path[idx]];
}
return value;
});
}
export function getExecutorNameForTask(
task: Task,
nxJson: NxJsonConfiguration,
projectGraph: ProjectGraph
) {
const project = projectGraph.nodes[task.target.project].data;
const projectRoot = join(workspaceRoot, project.root);
if (existsSync(join(projectRoot, 'package.json'))) {
project.targets = mergeNpmScriptsWithTargets(projectRoot, project.targets);
}
project.targets = mergePluginTargetsWithNxTargets(
project.root,
project.targets,
loadNxPlugins(nxJson.plugins)
);
return project.targets[task.target.target].executor;
}
export function getExecutorForTask(
task: Task,
workspace: Workspaces,
projectGraph: ProjectGraph,
nxJson: NxJsonConfiguration
) {
const executor = getExecutorNameForTask(task, nxJson, projectGraph);
const [nodeModule, executorName] = executor.split(':');
return workspace.readExecutor(nodeModule, executorName);
}
export function getCustomHasher(
task: Task,
workspace: Workspaces,
nxJson: NxJsonConfiguration,
projectGraph: ProjectGraph
) {
const factory = getExecutorForTask(
task,
workspace,
projectGraph,
nxJson
).hasherFactory;
return factory ? factory() : null;
}
export function removeTasksFromTaskGraph(
graph: TaskGraph,
ids: string[]
): TaskGraph {
const tasks = {};
const dependencies = {};
const removedSet = new Set(ids);
for (let taskId of Object.keys(graph.tasks)) {
if (!removedSet.has(taskId)) {
tasks[taskId] = graph.tasks[taskId];
dependencies[taskId] = graph.dependencies[taskId].filter(
(depTaskId) => !removedSet.has(depTaskId)
);
}
}
return {
tasks,
dependencies: dependencies,
roots: Object.keys(dependencies).filter(
(k) => dependencies[k].length === 0
),
};
}
export function calculateReverseDeps(
taskGraph: TaskGraph
): Record<string, string[]> {
const reverseTaskDeps: Record<string, string[]> = {};
Object.keys(taskGraph.tasks).forEach((t) => {
reverseTaskDeps[t] = [];
});
Object.keys(taskGraph.dependencies).forEach((taskId) => {
taskGraph.dependencies[taskId].forEach((d) => {
reverseTaskDeps[d].push(taskId);
});
});
return reverseTaskDeps;
}
export function getCliPath() {
return require.resolve(`../../bin/run-executor.js`);
}
export function getPrintableCommandArgsForTask(task: Task) {
const args: string[] = task.overrides['__overrides_unparsed__'];
const target = task.target.target.includes(':')
? `"${task.target.target}"`
: task.target.target;
const config = task.target.configuration
? `:${task.target.configuration}`
: '';
return ['run', `${task.target.project}:${target}${config}`, ...args];
}
export function getSerializedArgsForTask(task: Task, isVerbose: boolean) {
return [
JSON.stringify({
targetDescription: task.target,
overrides: task.overrides,
isVerbose: isVerbose,
}),
];
}
export function shouldStreamOutput(
task: Task,
initiatingProject: string | null,
options: {
cacheableOperations?: string[] | null;
cacheableTargets?: string[] | null;
}
): boolean {
if (process.env.NX_STREAM_OUTPUT === 'true') return true;
if (longRunningTask(task)) return true;
if (task.target.project === initiatingProject) return true;
return false;
}
export function isCacheableTask(
task: Task,
options: {
cacheableOperations?: string[] | null;
cacheableTargets?: string[] | null;
}
): boolean {
const cacheable = options.cacheableOperations || options.cacheableTargets;
return (
cacheable &&
cacheable.indexOf(task.target.target) > -1 &&
!longRunningTask(task)
);
}
function longRunningTask(task: Task) {
const t = task.target.target;
return (
(!!task.overrides['watch'] && task.overrides['watch'] !== 'false') ||
t.endsWith(':watch') ||
t.endsWith('-watch') ||
t === 'serve' ||
t === 'dev' ||
t === 'start'
);
}
// TODO: vsavkin remove when nx-cloud doesn't depend on it
export function unparse(options: Object): string[] {
return serializeOverridesIntoCommandLine(options);
}