-
Notifications
You must be signed in to change notification settings - Fork 414
Expand file tree
/
Copy pathextension.ts
More file actions
467 lines (416 loc) · 20.4 KB
/
extension.ts
File metadata and controls
467 lines (416 loc) · 20.4 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
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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
import * as compareVersions from "compare-versions";
import * as _ from "lodash";
import * as path from "path";
import * as vscode from "vscode";
import { dispose as disposeTelemetryWrapper, initializeFromJsonFile, instrumentOperation,
instrumentOperationAsVsCodeCommand, sendInfo, setUserError } from "vscode-extension-telemetry-wrapper";
import * as commands from "./commands";
import { JavaDebugConfigurationProvider, lastUsedLaunchConfig } from "./configurationProvider";
import { HCR_EVENT, JAVA_LANGID, TELEMETRY_EVENT, USER_NOTIFICATION_EVENT } from "./constants";
import { NotificationBar } from "./customWidget";
import { initializeCodeLensProvider, startDebugging } from "./debugCodeLensProvider";
import { initExpService } from "./experimentationService";
import { registerNoConfigDebug } from "./noConfigDebugInit";
import { handleHotCodeReplaceCustomEvent, initializeHotCodeReplace, NO_BUTTON, YES_BUTTON } from "./hotCodeReplace";
import { JavaDebugAdapterDescriptorFactory } from "./javaDebugAdapterDescriptorFactory";
import { JavaInlineValuesProvider } from "./JavaInlineValueProvider";
import { logJavaException, logJavaInfo } from "./javaLogger";
import { IMainClassOption, IMainMethod, resolveMainMethod } from "./languageServerPlugin";
import { mainClassPicker } from "./mainClassPicker";
import { pickJavaProcess } from "./processPicker";
import { IProgressReporter } from "./progressAPI";
import { progressProvider } from "./progressImpl";
import { JavaTerminalLinkProvder } from "./terminalLinkProvider";
import { initializeThreadOperations } from "./threadOperations";
import * as utility from "./utility";
import { registerVariableMenuCommands } from "./variableMenu";
import { promisify } from "util";
export async function activate(context: vscode.ExtensionContext): Promise<any> {
await initializeFromJsonFile(context.asAbsolutePath("./package.json"));
await initExpService(context);
// Register No-Config Debug functionality
const noConfigDisposable = await registerNoConfigDebug(
context.environmentVariableCollection,
context.extensionPath
);
context.subscriptions.push(noConfigDisposable);
return instrumentOperation("activation", initializeExtension)(context);
}
function initializeExtension(_operationId: string, context: vscode.ExtensionContext): any {
registerDebugEventListener(context);
registerVariableMenuCommands(context);
context.subscriptions.push(vscode.window.registerTerminalLinkProvider(new JavaTerminalLinkProvder()));
context.subscriptions.push(vscode.debug.registerDebugConfigurationProvider("java", new JavaDebugConfigurationProvider()));
context.subscriptions.push(vscode.debug.registerDebugAdapterDescriptorFactory("java", new JavaDebugAdapterDescriptorFactory()));
context.subscriptions.push(instrumentOperationAsVsCodeCommand("JavaDebug.SpecifyProgramArgs", async () => {
return specifyProgramArguments(context);
}));
context.subscriptions.push(instrumentOperationAsVsCodeCommand("JavaDebug.PickJavaProcess", async () => {
let javaProcess;
try {
javaProcess = await pickJavaProcess();
} catch (error) {
vscode.window.showErrorMessage(error.message ? error.message : String(error));
}
// tslint:disable-next-line
return javaProcess ? String(javaProcess.pid) : "${command:PickJavaProcess}";
}));
const hcrStatusBar: NotificationBar = new NotificationBar("java.hcrStatusBar", "Java HotCodeReplace");
context.subscriptions.push(hcrStatusBar);
context.subscriptions.push(instrumentOperationAsVsCodeCommand("java.debug.hotCodeReplace", async () => {
await applyHCR(hcrStatusBar);
}));
context.subscriptions.push(instrumentOperationAsVsCodeCommand("java.debug.runJavaFile", async (uri: vscode.Uri) => {
await runJavaFile(uri, true);
}));
context.subscriptions.push(instrumentOperationAsVsCodeCommand("java.debug.debugJavaFile", async (uri: vscode.Uri) => {
await runJavaFile(uri, false);
}));
context.subscriptions.push(instrumentOperationAsVsCodeCommand("java.debug.runFromProjectView", async (node: any) => {
await runJavaProject(node, true);
}));
context.subscriptions.push(instrumentOperationAsVsCodeCommand("java.debug.debugFromProjectView", async (node: any) => {
await runJavaProject(node, false);
}));
initializeHotCodeReplace(context);
initializeCodeLensProvider(context);
initializeThreadOperations(context);
subscribeToJavaExtensionEvents();
context.subscriptions.push(vscode.languages.registerInlineValuesProvider("java", new JavaInlineValuesProvider()));
return {
progressProvider,
};
}
// this method is called when your extension is deactivated
export async function deactivate() {
await disposeTelemetryWrapper();
}
const delay = promisify(setTimeout);
async function subscribeToJavaExtensionEvents(): Promise<void> {
const javaExt = vscode.extensions.getExtension("redhat.java");
if (!javaExt) {
return;
}
// wait javaExt to activate
const timeout = 30 * 60 * 1000; // wait 30 min at most
let count = 0;
while (!javaExt.isActive && count < timeout) {
await delay(1000);
count += 1000;
}
if (javaExt.isActive) {
javaExt.exports?.onDidSourceInvalidate?.((event: any) => {
if (event?.affectedRootPaths?.length) {
const activeDebugSession = vscode.debug.activeDebugSession;
if (activeDebugSession?.type === "java") {
activeDebugSession.customRequest("refreshFrames", {
affectedRootPaths: event.affectedRootPaths,
});
}
}
});
}
}
function registerDebugEventListener(context: vscode.ExtensionContext) {
const measureKeys = ["duration"];
context.subscriptions.push(vscode.debug.onDidTerminateDebugSession((e) => {
if (e.type !== "java") {
return;
}
fetchUsageData().then((ret) => {
if (Array.isArray(ret) && ret.length) {
ret.forEach((entry) => {
const commonProperties: any = {};
const measureProperties: any = {};
for (const key of Object.keys(entry)) {
if (measureKeys.indexOf(key) >= 0) {
measureProperties[key] = entry[key];
} else {
commonProperties[key] = String(entry[key]);
}
}
if (entry.scope === "exception") {
logJavaException(commonProperties);
} else {
logJavaInfo(commonProperties, measureProperties);
}
});
}
});
}));
context.subscriptions.push(vscode.debug.onDidReceiveDebugSessionCustomEvent((customEvent) => {
const t = customEvent.session ? customEvent.session.type : undefined;
if (t !== JAVA_LANGID) {
return;
}
if (customEvent.event === TELEMETRY_EVENT) {
sendInfo("", {
operationName: customEvent.body?.name,
...customEvent.body?.properties,
});
} else if (customEvent.event === HCR_EVENT) {
handleHotCodeReplaceCustomEvent(customEvent);
} else if (customEvent.event === USER_NOTIFICATION_EVENT) {
handleUserNotification(customEvent);
}
}));
}
function handleUserNotification(customEvent: vscode.DebugSessionCustomEvent) {
if (customEvent.body.notificationType === "ERROR") {
utility.showErrorMessageWithTroubleshooting({
message: customEvent.body.message,
});
} else if (customEvent.body.notificationType === "WARNING") {
utility.showWarningMessageWithTroubleshooting({
message: customEvent.body.message,
});
} else {
vscode.window.showInformationMessage(customEvent.body.message);
}
}
function fetchUsageData() {
return commands.executeJavaLanguageServerCommand(commands.JAVA_FETCH_USAGE_DATA);
}
function specifyProgramArguments(context: vscode.ExtensionContext): Thenable<string> {
const javaDebugProgramArgsKey = "JavaDebugProgramArgs";
const options: vscode.InputBoxOptions = {
ignoreFocusOut: true,
placeHolder: "Enter program arguments or leave empty to pass no args",
};
const prevArgs = context.workspaceState.get(javaDebugProgramArgsKey, "");
if (prevArgs.length > 0) {
options.value = prevArgs;
}
return vscode.window.showInputBox(options).then((text) => {
// When user cancels the input box (by pressing Esc), the text value is undefined.
if (text !== undefined) {
context.workspaceState.update(javaDebugProgramArgsKey, text);
}
return text || " ";
});
}
async function applyHCR(hcrStatusBar: NotificationBar) {
const debugSession: vscode.DebugSession | undefined = vscode.debug.activeDebugSession;
if (!debugSession) {
return;
}
if (debugSession.configuration.noDebug) {
vscode.window.showWarningMessage("Failed to apply the changes because hot code replace is not supported by run mode, "
+ "would you like to restart the program?", YES_BUTTON, NO_BUTTON).then((res) => {
if (res === YES_BUTTON) {
vscode.commands.executeCommand("workbench.action.debug.restart");
}
});
return;
}
const autobuildConfig: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration("java.autobuild");
if (!autobuildConfig.enabled) {
// If autobuild is disabled, force an incremental build before HCR.
try {
hcrStatusBar.show("$(sync~spin)Compiling...");
await commands.executeJavaExtensionCommand(commands.JAVA_BUILD_WORKSPACE, JSON.stringify({
isFullBuild: false
}));
} catch (err) {
// do nothing.
}
}
hcrStatusBar.show("$(sync~spin)Applying code changes...");
const start = new Date().getTime();
const response = await debugSession.customRequest("redefineClasses");
const elapsed = new Date().getTime() - start;
const humanVisibleDelay = elapsed < 150 ? 150 : 0;
if (humanVisibleDelay) {
await new Promise((resolve) => {
setTimeout(resolve, humanVisibleDelay);
});
}
if (response && response.errorMessage) {
// The detailed error message is handled by hotCodeReplace#handleHotCodeReplaceCustomEvent
hcrStatusBar.clear();
return;
}
if (!response || !response.changedClasses || !response.changedClasses.length) {
hcrStatusBar.clear();
vscode.window.showWarningMessage("Cannot find any changed classes for hot replace!");
return;
}
const changed = response.changedClasses.length;
hcrStatusBar.show("$(check)" + `${changed} changed class${changed > 1 ? "es are" : " is"} reloaded`, 5 * 1000);
}
async function runJavaFile(uri: vscode.Uri, noDebug: boolean) {
const progressReporter = progressProvider.createProgressReporter(noDebug ? "Run" : "Debug");
try {
// Wait for Java Language Support extension being on Standard mode.
const isOnStandardMode = await utility.waitForStandardMode(progressReporter);
if (!isOnStandardMode) {
throw new utility.OperationCancelledError("");
}
const activeEditor: vscode.TextEditor | undefined = vscode.window.activeTextEditor;
if (!uri && activeEditor && _.endsWith(path.basename(activeEditor.document.fileName), ".java")) {
uri = activeEditor.document.uri;
}
if (!uri) {
vscode.window.showErrorMessage(`${noDebug ? "Run" : "Debug"} failed. Please open a Java file with main method first.`);
throw new utility.OperationCancelledError("");
}
const mainMethods: IMainMethod[] = await resolveMainMethod(uri);
const hasMainMethods: boolean = mainMethods.length > 0;
const canRunTests: boolean = await canDelegateToJavaTestRunner(uri);
const defaultPlaceHolder: string = "Select the main class to run";
if (!hasMainMethods && !canRunTests) {
// If current file is not a main class, "Run Java" will run previously used launch config.
if (lastUsedLaunchConfig) {
progressReporter.setJobName(utility.launchJobName(lastUsedLaunchConfig.name, noDebug));
progressReporter.report("Resolving launch configuration...");
lastUsedLaunchConfig.noDebug = noDebug;
lastUsedLaunchConfig.__progressId = progressReporter.getId();
vscode.debug.startDebugging(lastUsedLaunchConfig.__workspaceFolder, lastUsedLaunchConfig);
} else {
progressReporter.report("Resolving main class...");
const mainClasses: IMainClassOption[] = await utility.searchMainMethods();
if (progressReporter.isCancelled()) {
throw new utility.OperationCancelledError("");
}
const placeHolder: string = `The file '${path.basename(uri.fsPath)}' is not executable, please select a main class you want to run.`;
await launchMain(mainClasses, uri, noDebug, progressReporter, placeHolder, false /*autoPick*/);
}
} else if (hasMainMethods && !canRunTests) {
await launchMain(mainMethods, uri, noDebug, progressReporter, defaultPlaceHolder);
} else if (!hasMainMethods && canRunTests) {
launchTesting(uri, noDebug, progressReporter);
} else {
const launchMainChoice: string = "main() method";
const launchTestChoice: string = "unit tests";
const choice: string | undefined = await vscode.window.showQuickPick(
[launchMainChoice, launchTestChoice],
{ placeHolder: "Please select which kind of task you would like to launch" },
);
if (choice === launchMainChoice) {
await launchMain(mainMethods, uri, noDebug, progressReporter, defaultPlaceHolder);
} else if (choice === launchTestChoice) {
launchTesting(uri, noDebug, progressReporter);
}
}
} catch (ex) {
progressReporter.done();
if (ex instanceof utility.OperationCancelledError) {
return;
}
if (ex instanceof utility.JavaExtensionNotEnabledError) {
utility.guideToInstallJavaExtension();
return;
}
vscode.window.showErrorMessage(String((ex && ex.message) || ex));
}
}
async function canDelegateToJavaTestRunner(uri: vscode.Uri): Promise<boolean> {
const fsPath: string = uri.fsPath;
const isTestFile: boolean = /.*[\/\\]src[\/\\]test[\/\\]java[\/\\].*[Tt]ests?\.java/.test(fsPath);
if (!isTestFile) {
return false;
}
return (await vscode.commands.getCommands()).includes("java.test.editor.run");
}
function launchTesting(uri: vscode.Uri, noDebug: boolean, progressReporter: IProgressReporter) {
const command: string = noDebug ? "java.test.editor.run" : "java.test.editor.debug";
vscode.commands.executeCommand(command, uri, progressReporter);
if (compareVersions.compare(getTestExtensionVersion(), "0.26.1", "<=")) {
throw new utility.OperationCancelledError("");
}
}
function getTestExtensionVersion(): string {
const extension: vscode.Extension<any> | undefined = vscode.extensions.getExtension("vscjava.vscode-java-test");
return extension?.packageJSON.version || "0.0.0";
}
async function launchMain(mainMethods: IMainClassOption[], uri: vscode.Uri, noDebug: boolean, progressReporter: IProgressReporter,
placeHolder: string, autoPick: boolean = true): Promise<void> {
if (!mainMethods || !mainMethods.length) {
vscode.window.showErrorMessage(
"Error: Main method not found in the file, please define the main method as: public static void main(String[] args)");
throw new utility.OperationCancelledError("");
}
if (!mainClassPicker.isAutoPicked(mainMethods, autoPick)) {
progressReporter.hide(true);
}
const pick = await mainClassPicker.showQuickPickWithRecentlyUsed(mainMethods, placeHolder, autoPick);
if (!pick) {
throw new utility.OperationCancelledError("");
}
const existConfig: vscode.DebugConfiguration | undefined = findLaunchConfiguration(
pick.mainClass, pick.projectName, uri.fsPath);
if (existConfig) {
progressReporter.setJobName(utility.launchJobName(existConfig.name, noDebug));
} else {
progressReporter.setJobName(utility.launchJobNameByMainClass(pick.mainClass, noDebug));
}
progressReporter.report("Launching main class...");
startDebugging(pick.mainClass, pick.projectName || "", uri, noDebug, progressReporter);
}
async function runJavaProject(node: any, noDebug: boolean) {
if (!node || !node.name || !node.uri) {
vscode.window.showErrorMessage(`Failed to ${noDebug ? "run" : "debug"} the project because of invalid project node. `
+ "This command only applies to Project Explorer view.");
const error = new Error(`Failed to ${noDebug ? "run" : "debug"} the project because of invalid project node.`);
setUserError(error);
throw error;
}
const progressReporter = progressProvider.createProgressReporter(noDebug ? "Run" : "Debug");
try {
progressReporter.report("Resolving main class...");
const mainClassesOptions: IMainClassOption[] = await utility.searchMainMethods(vscode.Uri.parse(node.uri));
if (progressReporter.isCancelled()) {
throw new utility.OperationCancelledError("");
}
if (!mainClassesOptions || !mainClassesOptions.length) {
vscode.window.showErrorMessage(`Failed to ${noDebug ? "run" : "debug"} this project '${node._nodeData.displayName || node.name}' `
+ "because it does not contain any main class.");
throw new utility.OperationCancelledError("");
}
if (!mainClassPicker.isAutoPicked(mainClassesOptions)) {
progressReporter.hide(true);
}
const pick = await mainClassPicker.showQuickPickWithRecentlyUsed(mainClassesOptions,
"Select the main class to run.");
if (!pick || progressReporter.isCancelled()) {
throw new utility.OperationCancelledError("");
}
const projectName: string | undefined = pick.projectName;
const mainClass: string = pick.mainClass;
const filePath: string | undefined = pick.filePath;
const workspaceFolder: vscode.WorkspaceFolder | undefined =
filePath ? vscode.workspace.getWorkspaceFolder(vscode.Uri.file(filePath)) : undefined;
const existConfig: vscode.DebugConfiguration | undefined = findLaunchConfiguration(mainClass, projectName, filePath);
const debugConfig = existConfig || {
type: "java",
name: `${mainClass.substr(mainClass.lastIndexOf(".") + 1)}`,
request: "launch",
mainClass,
projectName,
};
debugConfig.noDebug = noDebug;
debugConfig.__progressId = progressReporter.getId();
debugConfig.__origin = "internal";
progressReporter.setJobName(utility.launchJobName(debugConfig.name, noDebug));
progressReporter.report("Launching main class...");
vscode.debug.startDebugging(workspaceFolder, debugConfig);
} catch (ex) {
progressReporter.done();
if (ex instanceof utility.OperationCancelledError) {
return;
}
throw ex;
}
}
function findLaunchConfiguration(mainClass: string, projectName: string | undefined, filePath?: string): vscode.DebugConfiguration | undefined {
const workspaceFolder: vscode.WorkspaceFolder | undefined =
filePath ? vscode.workspace.getWorkspaceFolder(vscode.Uri.file(filePath)) : undefined;
const launchConfigurations: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration("launch", workspaceFolder);
const existingConfigs: vscode.DebugConfiguration[] = launchConfigurations.configurations;
const existConfig: vscode.DebugConfiguration | undefined = _.find(existingConfigs, (config) => {
return config.mainClass === mainClass && _.toString(config.projectName) === _.toString(projectName);
});
return existConfig;
}