Repository navigation
Expand file tree
/
Copy pathbuildTaskProvider.ts
More file actions
302 lines (268 loc) · 10.9 KB
/
Copy pathbuildTaskProvider.ts
File metadata and controls
302 lines (268 loc) · 10.9 KB
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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
import { CancellationTokenSource, commands, CustomExecution, Event, EventEmitter, Pseudoterminal, Task,
TaskDefinition, TaskGroup, TaskProvider, TaskRevealKind, TaskScope, Uri, workspace, WorkspaceFolder } from "vscode";
import { Jdtls } from "../../java/jdtls";
import * as path from "path";
import { checkErrorsReportedByJavaExtension } from "../../build";
import { Commands } from "../../commands";
import { sendInfo } from "vscode-extension-telemetry-wrapper";
/**
* A task provider to provide Java build task support.
*/
export class BuildTaskProvider implements TaskProvider {
public static readonly type = "java (build)";
// tslint:disable-next-line: no-invalid-template-strings
public static readonly workspace = "${workspace}";
public static readonly defaultTaskName = "Build Workspace";
async provideTasks(): Promise<Task[]> {
const folders: readonly WorkspaceFolder[] = workspace.workspaceFolders || [];
if (!folders.length) {
return [];
}
const defaultTaskDefinition = {
type: BuildTaskProvider.type,
paths: [ BuildTaskProvider.workspace ],
isFullBuild: true,
};
const defaultTask = new Task(
defaultTaskDefinition,
TaskScope.Workspace,
BuildTaskProvider.defaultTaskName,
BuildTaskProvider.type,
new CustomExecution(async (resolvedDefinition: IBuildTaskDefinition): Promise<Pseudoterminal> => {
return new BuildTaskTerminal(resolvedDefinition, TaskScope.Workspace);
}),
);
defaultTask.detail = "$(tools) Build all the Java projects in workspace.";
defaultTask.group = TaskGroup.Build;
defaultTask.presentationOptions = {
reveal: TaskRevealKind.Never,
clear: true,
};
return [defaultTask];
}
async resolveTask(task: Task): Promise<Task | undefined> {
const taskDefinition = task.definition as IBuildTaskDefinition;
if (!taskDefinition.paths?.length) {
taskDefinition.paths = [ BuildTaskProvider.workspace ];
} else {
taskDefinition.paths = taskDefinition.paths
.map(p => p.trim())
.filter(Boolean);
task.definition = taskDefinition;
}
task.execution = new CustomExecution(async (resolvedDefinition: IBuildTaskDefinition): Promise<Pseudoterminal> => {
return new BuildTaskTerminal(resolvedDefinition, task.scope ?? TaskScope.Workspace);
});
task.presentationOptions = {
reveal: TaskRevealKind.Never,
clear: true,
};
return task;
}
}
class BuildTaskTerminal implements Pseudoterminal {
private cancellationTokenSource: CancellationTokenSource;
constructor(private readonly definition: IBuildTaskDefinition,
private readonly scope: WorkspaceFolder | TaskScope.Global | TaskScope.Workspace) {
this.cancellationTokenSource = new CancellationTokenSource();
}
writeEmitter = new EventEmitter<string>();
closeEmitter = new EventEmitter<number>();
onDidWrite: Event<string> = this.writeEmitter.event;
onDidClose: Event<number> = this.closeEmitter.event;
async open(): Promise<void> {
// TODO: consider change to terminal name via changeNameEmitter.
// see: https://github.com/microsoft/vscode/issues/154146
let returnCode = Number.MAX_SAFE_INTEGER;
if (this.scope === TaskScope.Global) {
this.writeEmitter.fire('Global task is not supported.\r\n\r\n');
returnCode = ReturnCode.UnsupportedTask;
} else if (this.definition.paths.length === 1 &&
this.definition.paths[0] === BuildTaskProvider.workspace) {
returnCode = await this.buildWorkspace();
} else {
returnCode = await this.buildProjects();
}
this.writeEmitter.fire('Task complete.\r\n');
this.closeEmitter.fire(returnCode);
sendInfo("", {
buildTaskReturnCode: returnCode.toString()
});
}
close(): void {
this.cancellationTokenSource.cancel();
this.cancellationTokenSource.dispose();
}
async buildWorkspace(): Promise<number> {
this.writeEmitter.fire("Building all the Java projects in workspace...\r\n\r\n");
try {
await commands.executeCommand(Commands.COMPILE_WORKSPACE, this.definition.isFullBuild, this.cancellationTokenSource.token);
} catch (e) {
if (checkErrorsReportedByJavaExtension()) {
commands.executeCommand(Commands.WORKBENCH_VIEW_PROBLEMS);
this.writeEmitter.fire("Errors found when building the workspace, please open PROBLEMS view for details.\r\n\r\n");
return ReturnCode.UserError;
} else {
this.writeEmitter.fire("Errors occur when building the workspace:\r\n");
this.writeEmitter.fire(`${e}\r\n\r\n`);
return ReturnCode.CommandFail;
}
}
return ReturnCode.Success;
}
async buildProjects(): Promise<number> {
// tslint:disable-next-line: prefer-const
let [includedPaths, excludedPaths, invalidPaths] = categorizePaths(this.definition.paths, this.scope);
if (invalidPaths.length) {
this.printList("Following paths are invalid, please provide absolute paths instead:", invalidPaths);
return ReturnCode.InvalidPath;
}
const projectUris: string[] = await Jdtls.getProjectUris();
const projectPaths: string[] = projectUris
.map(uri => Uri.parse(uri).fsPath)
.filter(p => path.basename(p) !== "jdt.ls-java-project");
[includedPaths, invalidPaths] = getFinalPaths(includedPaths, excludedPaths, projectPaths);
if (invalidPaths.length) {
this.printList("Following paths are skipped due to not matching any project root path:", invalidPaths);
}
if (includedPaths.length === 0) {
return ReturnCode.EmptyIncludedPath;
}
if (this.cancellationTokenSource.token.isCancellationRequested) {
return ReturnCode.Cancelled;
}
this.printList("Building following projects:", includedPaths);
const uris: Uri[] = includedPaths.map(p => Uri.file(p));
try {
const res = await commands.executeCommand(Commands.BUILD_PROJECT, uris, this.definition.isFullBuild,
this.cancellationTokenSource.token);
switch (res) {
case Jdtls.CompileWorkspaceStatus.Witherror:
if (checkErrorsReportedByJavaExtension()) {
commands.executeCommand(Commands.WORKBENCH_VIEW_PROBLEMS);
this.writeEmitter.fire("Errors found when building the workspace, please open PROBLEMS view for details.\r\n\r\n");
}
return ReturnCode.UserError;
case Jdtls.CompileWorkspaceStatus.Cancelled:
return ReturnCode.Cancelled;
case Jdtls.CompileWorkspaceStatus.Failed:
return ReturnCode.CommandFail;
case Jdtls.CompileWorkspaceStatus.Succeed:
return ReturnCode.Success;
}
} catch (e) {
this.writeEmitter.fire(`Error occurs when building the workspace:\r\n`);
this.writeEmitter.fire(`${e}\r\n\r\n`);
return ReturnCode.CommandFail;
}
return ReturnCode.Success;
}
private printList(title: string, list: string[]) {
this.writeEmitter.fire(`${title}\r\n`);
for (const l of list) {
this.writeEmitter.fire(` ${l}\r\n`);
}
this.writeEmitter.fire("\r\n");
}
}
/**
* Categorize the paths into three categories, and return the categories in an array.
* @param paths paths in the task definition.
* @param scope scope of the task
* @returns {Array} [included paths, excluded paths, invalid paths].
*/
export function categorizePaths(paths: string[], scope: WorkspaceFolder | TaskScope.Global | TaskScope.Workspace): string[][] {
const includes = [];
const excludes = [];
const invalid = [];
for (const p of paths) {
let actualPath = p;
const isNegative: boolean = p.startsWith("!");
if (isNegative) {
actualPath = trimNegativeSign(actualPath);
}
if (actualPath === BuildTaskProvider.workspace || path.isAbsolute(actualPath)) {
if (isNegative) {
excludes.push(actualPath);
} else {
includes.push(actualPath);
}
continue;
}
let folder: WorkspaceFolder | undefined;
if (scope === TaskScope.Workspace) {
// cannot recover the absolute path
if (!workspace.workspaceFolders || workspace.workspaceFolders.length > 1) {
invalid.push(p);
} else {
folder = workspace.workspaceFolders[0];
}
}
if (!folder) {
continue;
}
const resolvedPath = path.join(folder.uri.fsPath, actualPath);
if (isNegative) {
excludes.push(resolvedPath);
} else {
includes.push(resolvedPath);
}
}
return [includes, excludes, invalid];
}
function trimNegativeSign(negativePath: string) {
let idx = 0;
for (; idx < negativePath.length; idx++) {
if (negativePath.charAt(idx) !== "!") {
break;
}
}
return negativePath.substring(idx);
}
/**
* Get the final paths which will be passed to the build projects command.
* @param includes included paths.
* @param excludes excluded paths.
* @param projectPaths paths of all the projects.
* @returns {Array} [ final paths, invalid paths ].
*/
export function getFinalPaths(includes: string[], excludes: string[], projectPaths: string[]): string[][] {
if (includes.includes(BuildTaskProvider.workspace)) {
includes = projectPaths;
}
includes = includes.filter(p => {
return !excludes.some(excludePath => path.relative(excludePath, p) === "");
});
const result: string[] = [];
const invalid: string[] = [];
for (const p of includes) {
const valid = projectPaths.some(projectPath => path.relative(projectPath, p) === "");
if (valid) {
result.push(p);
} else {
invalid.push(p);
}
}
return [result, invalid];
}
interface IBuildTaskDefinition extends TaskDefinition {
/**
* The root paths of the projects to be built.
*/
paths: string[];
/**
* Whether this is a full build or not.
*/
isFullBuild: boolean;
}
enum ReturnCode {
Success = 0,
InvalidPath = 1,
UnsupportedTask = 2,
EmptyIncludedPath = 3,
UserError = 64,
CommandFail = -1,
Cancelled = -32800,
}