-
Notifications
You must be signed in to change notification settings - Fork 622
/
Copy pathTaskOperationRunner.ts
215 lines (184 loc) · 7.76 KB
/
TaskOperationRunner.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
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
// See LICENSE in the project root for license information.
import {
type IOperationRunner,
type IOperationRunnerContext,
OperationStatus
} from '@rushstack/operation-graph';
import { AlreadyReportedError, InternalError } from '@rushstack/node-core-library';
import type { HeftTask } from '../../pluginFramework/HeftTask';
import { copyFilesAsync, normalizeCopyOperation } from '../../plugins/CopyFilesPlugin';
import { deleteFilesAsync } from '../../plugins/DeleteFilesPlugin';
import type {
HeftTaskSession,
IHeftTaskFileOperations,
IHeftTaskRunHookOptions,
IHeftTaskRunIncrementalHookOptions
} from '../../pluginFramework/HeftTaskSession';
import type { HeftPhaseSession } from '../../pluginFramework/HeftPhaseSession';
import type { InternalHeftSession } from '../../pluginFramework/InternalHeftSession';
import { watchGlobAsync, type IGlobOptions } from '../../plugins/FileGlobSpecifier';
import { type IWatchedFileState, WatchFileSystemAdapter } from '../../utilities/WatchFileSystemAdapter';
export interface ITaskOperationRunnerOptions {
internalHeftSession: InternalHeftSession;
task: HeftTask;
}
/**
* Log out a start message, run a provided function, and log out an end message
*/
export async function runAndMeasureAsync<T = void>(
fn: () => Promise<T>,
startMessageFn: () => string,
endMessageFn: () => string,
logFn: (message: string) => void
): Promise<T> {
logFn(startMessageFn());
const startTime: number = performance.now();
try {
return await fn();
} finally {
const endTime: number = performance.now();
logFn(`${endMessageFn()} (${endTime - startTime}ms)`);
}
}
export class TaskOperationRunner implements IOperationRunner {
private readonly _options: ITaskOperationRunnerOptions;
private _fileOperations: IHeftTaskFileOperations | undefined = undefined;
private _watchFileSystemAdapter: WatchFileSystemAdapter | undefined = undefined;
public readonly silent: boolean = false;
public get operationName(): string {
const { taskName, parentPhase } = this._options.task;
return `Task ${JSON.stringify(taskName)} of phase ${JSON.stringify(parentPhase.phaseName)}`;
}
public constructor(options: ITaskOperationRunnerOptions) {
this._options = options;
}
public async executeAsync(context: IOperationRunnerContext): Promise<OperationStatus> {
const { internalHeftSession, task } = this._options;
const { parentPhase } = task;
const phaseSession: HeftPhaseSession = internalHeftSession.getSessionForPhase(parentPhase);
const taskSession: HeftTaskSession = phaseSession.getSessionForTask(task);
return await this._executeTaskAsync(context, taskSession);
}
private async _executeTaskAsync(
context: IOperationRunnerContext,
taskSession: HeftTaskSession
): Promise<OperationStatus> {
const { abortSignal, requestRun } = context;
const { hooks, logger } = taskSession;
// Need to clear any errors or warnings from the previous invocation, particularly
// if this is an immediate rerun
logger.resetErrorsAndWarnings();
const rootFolderPath: string = this._options.internalHeftSession.heftConfiguration.buildFolderPath;
const isWatchMode: boolean = taskSession.parameters.watch && !!requestRun;
const { terminal } = logger;
// Exit the task early if cancellation is requested
if (abortSignal.aborted) {
return OperationStatus.Aborted;
}
if (!this._fileOperations && hooks.registerFileOperations.isUsed()) {
const fileOperations: IHeftTaskFileOperations = await hooks.registerFileOperations.promise({
copyOperations: new Set(),
deleteOperations: new Set()
});
// Do this here so that we only need to do it once for each run
for (const copyOperation of fileOperations.copyOperations) {
normalizeCopyOperation(rootFolderPath, copyOperation);
}
this._fileOperations = fileOperations;
}
const shouldRunIncremental: boolean = isWatchMode && hooks.runIncremental.isUsed();
let watchFileSystemAdapter: WatchFileSystemAdapter | undefined;
const getWatchFileSystemAdapter = (): WatchFileSystemAdapter => {
if (!watchFileSystemAdapter) {
watchFileSystemAdapter = this._watchFileSystemAdapter ||= new WatchFileSystemAdapter();
watchFileSystemAdapter.setBaseline();
}
return watchFileSystemAdapter;
};
const shouldRun: boolean = hooks.run.isUsed() || shouldRunIncremental;
if (!shouldRun && !this._fileOperations) {
terminal.writeVerboseLine('Task execution skipped, no implementation provided');
return OperationStatus.NoOp;
}
const runResult: OperationStatus = shouldRun
? await runAndMeasureAsync(
async (): Promise<OperationStatus> => {
// Create the options and provide a utility method to obtain paths to copy
const runHookOptions: IHeftTaskRunHookOptions = {
abortSignal
};
// Run the plugin run hook
try {
if (shouldRunIncremental) {
const runIncrementalHookOptions: IHeftTaskRunIncrementalHookOptions = {
...runHookOptions,
watchGlobAsync: (
pattern: string | string[],
options: IGlobOptions = {}
): Promise<Map<string, IWatchedFileState>> => {
return watchGlobAsync(pattern, {
...options,
fs: getWatchFileSystemAdapter()
});
},
requestRun: requestRun!
};
await hooks.runIncremental.promise(runIncrementalHookOptions);
} else {
await hooks.run.promise(runHookOptions);
}
} catch (e) {
// Log out using the task logger, and return an error status
if (!(e instanceof AlreadyReportedError)) {
logger.emitError(e as Error);
}
return OperationStatus.Failure;
}
if (abortSignal.aborted) {
return OperationStatus.Aborted;
}
return OperationStatus.Success;
},
() => `Starting ${shouldRunIncremental ? 'incremental ' : ''}task execution`,
() => {
const finishedWord: string = abortSignal.aborted ? 'Aborted' : 'Finished';
return `${finishedWord} ${shouldRunIncremental ? 'incremental ' : ''}task execution`;
},
terminal.writeVerboseLine.bind(terminal)
)
: // This branch only occurs if only file operations are defined.
OperationStatus.Success;
if (this._fileOperations) {
const { copyOperations, deleteOperations } = this._fileOperations;
await Promise.all([
copyOperations.size > 0
? copyFilesAsync(
copyOperations,
logger.terminal,
`${taskSession.tempFolderPath}/file-copy.json`,
isWatchMode ? getWatchFileSystemAdapter() : undefined
)
: Promise.resolve(),
deleteOperations.size > 0
? deleteFilesAsync(rootFolderPath, deleteOperations, logger.terminal)
: Promise.resolve()
]);
}
if (watchFileSystemAdapter) {
if (!requestRun) {
throw new InternalError(`watchFileSystemAdapter was initialized but requestRun is not defined!`);
}
watchFileSystemAdapter.watch(requestRun);
}
// Even if the entire process has completed, we should mark the operation as cancelled if
// cancellation has been requested.
if (abortSignal.aborted) {
return OperationStatus.Aborted;
}
if (logger.hasErrors) {
return OperationStatus.Failure;
}
return runResult;
}
}