forked from nrwl/nx
/
dynamic-run-one-terminal-output-life-cycle.ts
361 lines (327 loc) · 11.2 KB
/
dynamic-run-one-terminal-output-life-cycle.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
import * as cliCursor from 'cli-cursor';
import { dots } from 'cli-spinners';
import { EOL } from 'os';
import * as readline from 'readline';
import { output } from '../../utilities/output';
import type { LifeCycle } from '../life-cycle';
import type { Task } from '../tasks-runner';
import { prettyTime } from './pretty-time';
/**
* As tasks are completed the overall state moves from:
* 1. EXECUTING_DEPENDENT_TARGETS (dynamic lines, including a spinner are reprinted, task outputs not shown)
* 2. EXECUTING_INITIATING_PROJECT_TARGET (dynamic output effectively ends as initiating project tasks forward output)
* 3. COMPLETED_SUCCESSFULLY or COMPLETED_WITH_ERRORS (footer messaging is appended to the previous output)
*/
type State =
| 'EXECUTING_DEPENDENT_TARGETS'
| 'EXECUTING_INITIATING_PROJECT_TARGET'
| 'COMPLETED_SUCCESSFULLY'
| 'COMPLETED_WITH_ERRORS';
/**
* The following function is responsible for creating a life cycle with dynamic
* outputs, meaning previous outputs can be rewritten or modified as new outputs
* are added. It is therefore intended for use on a user's local machines.
*
* In CI environments the static equivalent of this life cycle should be used.
*
* NOTE: output.dim() should be preferred over output.colors.gray() because it
* is much more consistently readable across different terminal color themes.
*/
export async function createRunOneDynamicOutputRenderer({
initiatingProject,
tasks,
args,
overrides,
}: {
initiatingProject: string;
tasks: Task[];
args: { target?: string; configuration?: string; parallel?: number };
overrides: Record<string, unknown>;
}): Promise<{ lifeCycle: LifeCycle; renderIsDone: Promise<void> }> {
cliCursor.hide();
let resolveRenderIsDonePromise: (value: void) => void;
const renderIsDone = new Promise<void>(
(resolve) => (resolveRenderIsDonePromise = resolve)
).then(() => {
clearRenderInterval();
cliCursor.show();
});
function clearRenderInterval() {
if (renderDependentTargetsIntervalId) {
clearInterval(renderDependentTargetsIntervalId);
}
}
process.on('exit', () => clearRenderInterval());
process.on('SIGINT', () => clearRenderInterval());
process.on('SIGTERM', () => clearRenderInterval());
process.on('SIGHUP', () => clearRenderInterval());
const lifeCycle = {} as Partial<LifeCycle>;
const start = process.hrtime();
const figures = await import('figures');
let state: State = 'EXECUTING_DEPENDENT_TARGETS';
const tasksToTerminalOutputs: Record<string, string> = {};
const totalTasks = tasks.length;
const totalDependentTasks = totalTasks - 1;
const totalTasksFromInitiatingProject = tasks.filter(
(t) => t.target.project === initiatingProject
).length;
// Tasks from the initiating project are treated differently, they forward their output
const totalDependentTasksNotFromInitiatingProject =
totalTasks - totalTasksFromInitiatingProject;
const targetName = args.target;
let dependentTargetsNumLines = 0;
let totalCompletedTasks = 0;
let totalSuccessfulTasks = 0;
let totalFailedTasks = 0;
let totalCachedTasks = 0;
// Used to control the rendering of the spinner
let dependentTargetsCurrentFrame = 0;
let renderDependentTargetsIntervalId: NodeJS.Timeout | undefined;
const clearDependentTargets = () => {
for (let i = 0; i < dependentTargetsNumLines; i++) {
readline.moveCursor(process.stdout, 0, -1);
readline.clearLine(process.stdout, 0);
}
};
const renderLines = (
lines: string[],
dividerColor = 'cyan',
renderDivider = true,
skipPadding = false
) => {
let additionalLines = 0;
if (renderDivider) {
output.addVerticalSeparator(dividerColor);
additionalLines += 3;
}
if (renderDivider) {
lines.push('');
}
for (const line of lines) {
process.stdout.write((skipPadding ? '' : output.X_PADDING) + line + EOL);
}
dependentTargetsNumLines = lines.length + additionalLines;
};
const renderDependentTargets = (renderDivider = true) => {
if (totalDependentTasksNotFromInitiatingProject <= 0) {
return;
}
const max = dots.frames.length - 1;
const curr = dependentTargetsCurrentFrame;
dependentTargetsCurrentFrame = curr >= max ? 0 : curr + 1;
const linesToRender: string[] = [''];
const remainingDependentTasksNotFromInitiatingProject =
totalDependentTasksNotFromInitiatingProject - totalCompletedTasks;
switch (state) {
case 'EXECUTING_DEPENDENT_TARGETS':
if (totalFailedTasks === 0) {
linesToRender.push(
` ${output.colors.cyan(
dots.frames[dependentTargetsCurrentFrame]
)} ${output.colors.white.dim(
`Nx is waiting on ${remainingDependentTasksNotFromInitiatingProject} dependent project tasks before running tasks from`
)} ${output.colors.white(`${initiatingProject}`)}...`
);
if (totalSuccessfulTasks > 0) {
linesToRender.push('');
}
}
break;
}
if (totalFailedTasks > 0) {
linesToRender.push(
output.colors.red.dim(
` ${output.colors.red(
figures.cross
)} ${totalFailedTasks}${`/${totalCompletedTasks}`} dependent project tasks failed (see below)`
)
);
}
if (totalSuccessfulTasks > 0) {
linesToRender.push(
output.dim(
` ${output.dim(
figures.tick
)} ${totalSuccessfulTasks}${`/${totalCompletedTasks}`} dependent project tasks succeeded ${output.dim(
`[${totalCachedTasks} read from cache]`
)}`
)
);
}
clearDependentTargets();
if (linesToRender.length > 1) {
renderLines(
linesToRender,
'gray',
renderDivider && state !== 'EXECUTING_DEPENDENT_TARGETS',
true
);
} else {
renderLines([]);
}
};
lifeCycle.startCommand = () => {
renderDependentTargets();
};
lifeCycle.startTasks = (tasks: Task[]) => {
for (const task of tasks) {
// Move from the dependent project tasks phase to the initiating project's targets
if (
task.target.project === initiatingProject &&
state !== 'EXECUTING_INITIATING_PROJECT_TARGET'
) {
state = 'EXECUTING_INITIATING_PROJECT_TARGET';
clearRenderInterval();
renderDependentTargets(false);
if (totalDependentTasksNotFromInitiatingProject > 0) {
output.addNewline();
process.stdout.write(
` ${output.dim(
'Hint: you can run the command with'
)} --verbose ${output.dim(
'to see the full dependent project outputs'
)}` + EOL
);
output.addVerticalSeparator('gray');
}
}
}
if (
!renderDependentTargetsIntervalId &&
state === 'EXECUTING_DEPENDENT_TARGETS'
) {
renderDependentTargetsIntervalId = setInterval(
renderDependentTargets,
100
);
}
};
lifeCycle.printTaskTerminalOutput = (task, cacheStatus, terminalOutput) => {
if (task.target.project === initiatingProject) {
output.logCommand(task.id, cacheStatus);
output.addNewline();
process.stdout.write(terminalOutput);
} else {
tasksToTerminalOutputs[task.id] = terminalOutput;
}
};
lifeCycle.endTasks = (taskResults) => {
for (let t of taskResults) {
totalCompletedTasks++;
switch (t.status) {
case 'remote-cache':
case 'local-cache':
case 'local-cache-kept-existing':
totalCachedTasks++;
totalSuccessfulTasks++;
break;
case 'success':
totalSuccessfulTasks++;
break;
case 'failure':
totalFailedTasks++;
/**
* A dependent project has failed so we stop executing and update the relevant
* dependent project task messaging
*/
if (t.task.target.project !== initiatingProject) {
clearRenderInterval();
renderDependentTargets(false);
output.addVerticalSeparator('red');
output.logCommand(t.task.id, t.status);
output.addNewline();
process.stdout.write(tasksToTerminalOutputs[t.task.id]);
}
break;
}
delete tasksToTerminalOutputs[t.task.id];
}
};
lifeCycle.endCommand = () => {
clearRenderInterval();
const timeTakenText = prettyTime(process.hrtime(start));
if (totalSuccessfulTasks === totalTasks) {
state = 'COMPLETED_SUCCESSFULLY';
let text = `Successfully ran target ${output.bold(
targetName
)} for project ${output.bold(initiatingProject)}`;
if (totalDependentTasks > 0) {
text += ` and ${output.bold(
totalDependentTasks
)} task(s) it depends on`;
}
const taskOverridesLines = [];
if (Object.keys(overrides).length > 0) {
const leftPadding = `${output.X_PADDING} `;
taskOverridesLines.push('');
taskOverridesLines.push(
`${leftPadding}${output.dim.green('With additional flags:')}`
);
Object.entries(overrides)
.map(([flag, value]) =>
output.dim.green(`${leftPadding} --${flag}=${value}`)
)
.forEach((arg) => taskOverridesLines.push(arg));
}
const pinnedFooterLines = [
output.applyNxPrefix(
'green',
output.colors.green(text) + output.dim.white(` (${timeTakenText})`)
),
...taskOverridesLines,
];
if (totalCachedTasks > 0) {
pinnedFooterLines.push(
output.dim(
`${EOL} Nx read the output from the cache instead of running the command for ${totalCachedTasks} out of ${totalTasks} tasks.`
)
);
}
renderLines(pinnedFooterLines, 'green');
} else {
state = 'COMPLETED_WITH_ERRORS';
let text = `Ran target ${output.bold(
targetName
)} for project ${output.bold(initiatingProject)}`;
if (totalDependentTasks > 0) {
text += ` and ${output.bold(
totalDependentTasks
)} task(s) it depends on`;
}
const taskOverridesLines = [];
if (Object.keys(overrides).length > 0) {
const leftPadding = `${output.X_PADDING} `;
taskOverridesLines.push('');
taskOverridesLines.push(
`${leftPadding}${output.dim.red('With additional flags:')}`
);
Object.entries(overrides)
.map(([flag, value]) =>
output.dim.red(`${leftPadding} --${flag}=${value}`)
)
.forEach((arg) => taskOverridesLines.push(arg));
}
renderLines(
[
output.applyNxPrefix(
'red',
output.colors.red(text) + output.dim.white(` (${timeTakenText})`)
),
...taskOverridesLines,
'',
` ${output.colors.red(
figures.cross
)} ${totalFailedTasks}${`/${totalCompletedTasks}`} failed`,
` ${output.dim(
figures.tick
)} ${totalSuccessfulTasks}${`/${totalCompletedTasks}`} succeeded ${output.dim(
`[${totalCachedTasks} read from cache]`
)}`,
],
'red'
);
}
resolveRenderIsDonePromise();
};
return { lifeCycle, renderIsDone };
}