-
Notifications
You must be signed in to change notification settings - Fork 339
/
configurationProvider.ts
853 lines (761 loc) · 37.4 KB
/
configurationProvider.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
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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
import * as fs from "fs";
import * as _ from "lodash";
import * as os from "os";
import * as path from "path";
import * as vscode from "vscode";
import * as dotenv from 'dotenv';
import { instrumentOperation, sendError, sendInfo, setUserError } from "vscode-extension-telemetry-wrapper";
import * as anchor from "./anchor";
import { buildWorkspace } from "./build";
import { populateStepFilters, substituteFilterVariables } from "./classFilter";
import * as commands from "./commands";
import { ClasspathVariable } from "./constants";
import { Type } from "./javaLogger";
import * as lsPlugin from "./languageServerPlugin";
import { addMoreHelpfulVMArgs, getJavaVersion, getShortenApproachForCLI, validateRuntimeCompatibility } from "./launchCommand";
import { mainClassPicker } from "./mainClassPicker";
import { resolveJavaProcess } from "./processPicker";
import { IProgressReporter } from "./progressAPI";
import { progressProvider } from "./progressImpl";
import * as utility from "./utility";
const platformNameMappings: { [key: string]: string } = {
win32: "windows",
linux: "linux",
darwin: "osx",
};
const platformName = platformNameMappings[process.platform];
export let lastUsedLaunchConfig: vscode.DebugConfiguration | undefined;
export class JavaDebugConfigurationProvider implements vscode.DebugConfigurationProvider {
private isUserSettingsDirty: boolean = true;
constructor() {
const packageJson: {[key: string]: any} = require("../package.json");
const debugConfigNames = Object.keys(packageJson?.contributes?.configuration?.properties || {});
vscode.workspace.onDidChangeConfiguration((event) => {
if (event.affectsConfiguration("java.debug")) {
for (const key of debugConfigNames) {
if (event.affectsConfiguration(key)) {
sendInfo("", {
operationName: "changeJavaDebugSettings",
configName: key,
});
}
}
if (vscode.debug.activeDebugSession) {
this.isUserSettingsDirty = false;
return updateDebugSettings(event);
} else {
this.isUserSettingsDirty = true;
}
}
return undefined;
});
}
// Returns an initial debug configurations based on contextual information.
public provideDebugConfigurations(folder: vscode.WorkspaceFolder | undefined, token?: vscode.CancellationToken):
vscode.ProviderResult<vscode.DebugConfiguration[]> {
const provideDebugConfigurationsHandler = instrumentOperation("provideDebugConfigurations", (_operationId: string) => {
return <Thenable<vscode.DebugConfiguration[]>>this.provideDebugConfigurationsAsync(folder, token);
});
return provideDebugConfigurationsHandler();
}
// Try to add all missing attributes to the debug configuration being launched.
public resolveDebugConfiguration(_folder: vscode.WorkspaceFolder | undefined,
config: vscode.DebugConfiguration, _token?: vscode.CancellationToken):
vscode.ProviderResult<vscode.DebugConfiguration> {
// If no debug configuration is provided, then generate one in memory.
if (this.isEmptyConfig(config)) {
config.type = "java";
config.name = "Java Debug";
config.request = "launch";
config.__origin = "internal";
}
return config;
}
// Try to add all missing attributes to the debug configuration being launched.
public resolveDebugConfigurationWithSubstitutedVariables(
folder: vscode.WorkspaceFolder | undefined,
config: vscode.DebugConfiguration,
token?: vscode.CancellationToken): vscode.ProviderResult<vscode.DebugConfiguration> {
const resolveDebugConfigurationHandler = instrumentOperation("resolveDebugConfiguration", (_operationId: string) => {
try {
// See https://github.com/microsoft/vscode-java-debug/issues/778
// Merge the platform specific properties to the global config to simplify the subsequent resolving logic.
this.mergePlatformProperties(config, folder);
return this.resolveAndValidateDebugConfiguration(folder, config, token);
} catch (ex) {
utility.showErrorMessage({
type: Type.EXCEPTION,
message: String((ex && ex.message) || ex),
});
return undefined;
}
});
return resolveDebugConfigurationHandler();
}
private provideDebugConfigurationsAsync(folder: vscode.WorkspaceFolder | undefined, token?: vscode.CancellationToken) {
return new Promise(async (resolve, _reject) => {
const progressReporter = progressProvider.createProgressReporter("Create launch.json", vscode.ProgressLocation.Window);
progressReporter.observe(token);
const defaultLaunchConfig = {
type: "java",
name: "Current File",
request: "launch",
// tslint:disable-next-line
mainClass: "${file}",
};
try {
const isOnStandardMode = await utility.waitForStandardMode(progressReporter);
if (!isOnStandardMode) {
resolve([defaultLaunchConfig]);
return;
}
if (progressReporter.isCancelled()) {
resolve([defaultLaunchConfig]);
return;
}
progressReporter.report("Generating Java configuration...");
const mainClasses = await lsPlugin.resolveMainClass(folder ? folder.uri : undefined);
const cache = {};
const launchConfigs = mainClasses.map((item) => {
return {
...defaultLaunchConfig,
name: this.constructLaunchConfigName(item.mainClass, cache),
mainClass: item.mainClass,
projectName: item.projectName,
};
});
if (progressReporter.isCancelled()) {
resolve([defaultLaunchConfig]);
return;
}
resolve([defaultLaunchConfig, ...launchConfigs]);
} catch (ex) {
if (ex instanceof utility.JavaExtensionNotEnabledError) {
utility.guideToInstallJavaExtension();
} else {
// tslint:disable-next-line
console.error(ex);
}
resolve([defaultLaunchConfig]);
} finally {
progressReporter.done();
}
});
}
private mergePlatformProperties(config: vscode.DebugConfiguration, _folder?: vscode.WorkspaceFolder) {
if (config && platformName && config[platformName]) {
try {
for (const key of Object.keys(config[platformName])) {
config[key] = config[platformName][key];
}
config[platformName] = undefined;
} catch {
// do nothing
}
}
}
private constructLaunchConfigName(mainClass: string, cache: { [key: string]: any }) {
const name = `${mainClass.substr(mainClass.lastIndexOf(".") + 1)}`;
if (cache[name] === undefined) {
cache[name] = 0;
return name;
} else {
cache[name] += 1;
return `${name}(${cache[name]})`;
}
}
private mergeEnvFile(config: vscode.DebugConfiguration) {
const baseEnv = config.env || {};
let result = baseEnv;
if (config.envFile) {
try {
result = {
...baseEnv,
...readEnvFile(config.envFile),
};
} catch (e) {
throw new utility.UserError({
message: "Cannot load environment file.",
type: Type.USAGEERROR,
});
}
}
config.env = result;
}
private async resolveAndValidateDebugConfiguration(folder: vscode.WorkspaceFolder | undefined, config: vscode.DebugConfiguration,
token?: vscode.CancellationToken) {
let configCopy: vscode.DebugConfiguration | undefined;
const isConfigFromInternal = config.__origin === "internal" /** in-memory configuration from debugger */
|| config.__configurationTarget /** configuration from launch.json */;
if (config.request === "launch" && isConfigFromInternal) {
configCopy = _.cloneDeep(config);
delete configCopy.__progressId;
delete configCopy.noDebug;
}
let progressReporter = progressProvider.getProgressReporter(config.__progressId);
if (!progressReporter && config.__progressId) {
return undefined;
} else if (!progressReporter) {
progressReporter = progressProvider.createProgressReporter(utility.launchJobName(config.name, config.noDebug));
}
progressReporter.observe(token);
if (progressReporter.isCancelled()) {
return undefined;
}
try {
const isOnStandardMode = await utility.waitForStandardMode(progressReporter);
if (!isOnStandardMode || progressReporter.isCancelled()) {
return undefined;
}
if (this.isUserSettingsDirty) {
this.isUserSettingsDirty = false;
await updateDebugSettings();
}
// If no debug configuration is provided, then generate one in memory.
if (this.isEmptyConfig(config)) {
config.type = "java";
config.name = "Java Debug";
config.request = "launch";
}
if (config.request === "launch") {
const mainClassOption = await this.resolveAndValidateMainClass(folder && folder.uri, config, progressReporter);
if (!mainClassOption || !mainClassOption.mainClass) { // Exit silently if the user cancels the prompt fix by ESC.
// Exit the debug session.
return undefined;
}
config.mainClass = mainClassOption.mainClass;
config.projectName = mainClassOption.projectName;
if (config.__workspaceFolder && config.__workspaceFolder !== folder) {
folder = config.__workspaceFolder;
}
// Update the job name if the main class is changed during the resolving of configuration provider.
if (configCopy && configCopy.mainClass !== config.mainClass) {
config.name = config.mainClass.substr(config.mainClass.lastIndexOf(".") + 1);
progressReporter.setJobName(utility.launchJobName(config.name, config.noDebug));
}
if (progressReporter.isCancelled()) {
return undefined;
}
if (needsBuildWorkspace()) {
progressReporter.report("Compiling...");
const proceed = await buildWorkspace({
mainClass: mainClassOption.mainClass,
projectName: mainClassOption.projectName,
isFullBuild: false,
}, progressReporter);
if (!proceed) {
return undefined;
}
}
if (progressReporter.isCancelled()) {
return undefined;
}
progressReporter.report("Resolving launch configuration...");
this.mergeEnvFile(config);
// If the user doesn't specify 'vmArgs' in launch.json, use the global setting to get the default vmArgs.
if (config.vmArgs === undefined) {
const debugSettings: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration("java.debug.settings");
config.vmArgs = debugSettings.vmArgs;
}
// If the user doesn't specify 'console' in launch.json, use the global setting to get the launch console.
if (!config.console) {
const debugSettings: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration("java.debug.settings");
config.console = debugSettings.console;
}
// If the console is integratedTerminal, don't auto switch the focus to DEBUG CONSOLE.
if (config.console === "integratedTerminal" && !config.internalConsoleOptions) {
config.internalConsoleOptions = "neverOpen";
}
if (progressReporter.isCancelled()) {
return undefined;
}
if (_.isEmpty(config.classPaths) && _.isEmpty(config.modulePaths)) {
const result = <any[]>(await lsPlugin.resolveClasspath(config.mainClass, config.projectName));
config.modulePaths = result[0];
config.classPaths = result[1];
} else {
config.modulePaths = await this.resolvePath(folder, config.modulePaths, config.mainClass,
config.projectName, true /*isModulePath*/);
config.classPaths = await this.resolvePath(folder, config.classPaths, config.mainClass,
config.projectName, false /*isModulePath*/);
}
if (_.isEmpty(config.classPaths) && _.isEmpty(config.modulePaths)) {
throw new utility.UserError({
message: "Cannot resolve the modulepaths/classpaths automatically, please specify the value in the launch.json.",
type: Type.USAGEERROR,
});
}
if (_.isEmpty(config.javaExec)) {
config.javaExec = await lsPlugin.resolveJavaExecutable(config.mainClass, config.projectName);
} else {
if (!fs.existsSync(config.javaExec)) {
throw new utility.UserError({
message: "Java executable file path cannot be accessed, please specify a valid path in the launch.json.",
type: Type.USAGEERROR,
});
}
}
// Add the default launch options to the config.
config.cwd = config.cwd || _.get(folder, "uri.fsPath");
if (Array.isArray(config.args)) {
config.args = this.concatArgs(config.args);
}
if (Array.isArray(config.vmArgs)) {
config.vmArgs = this.concatArgs(config.vmArgs);
}
if (progressReporter.isCancelled()) {
return undefined;
}
// Populate the class filters to the debug configuration.
await populateStepFilters(config);
const targetJavaVersion: number = await getJavaVersion(config.javaExec);
// Auto add '--enable-preview' vmArgs if the java project enables COMPILER_PB_ENABLE_PREVIEW_FEATURES flag.
if (await lsPlugin.detectPreviewFlag(config.mainClass, config.projectName)) {
config.vmArgs = (config.vmArgs || "") + " --enable-preview";
validateRuntimeCompatibility(targetJavaVersion);
}
// Add more helpful vmArgs.
await addMoreHelpfulVMArgs(config, targetJavaVersion);
if (!config.shortenCommandLine || config.shortenCommandLine === "auto") {
config.shortenCommandLine = await getShortenApproachForCLI(config, targetJavaVersion);
}
// VS Code internal console uses UTF-8 to display output by default.
if (config.console === "internalConsole" && !config.encoding) {
config.encoding = "UTF-8";
}
} else if (config.request === "attach") {
if (config.hostName && config.port && Number.isInteger(Number(config.port))) {
config.port = Number(config.port);
config.processId = undefined;
// Continue if the hostName and port are configured.
} else if (config.processId !== undefined) {
// tslint:disable-next-line
if (config.processId === "${command:PickJavaProcess}") {
return undefined;
}
const pid: number = Number(config.processId);
if (Number.isNaN(pid)) {
vscode.window.showErrorMessage(`The processId config '${config.processId}' is not a valid process id.`);
return undefined;
}
const javaProcess = await resolveJavaProcess(pid);
if (!javaProcess) {
vscode.window.showErrorMessage(`Attach to process: pid '${config.processId}' is not a debuggable Java process. `
+ `Please make sure the process has turned on debug mode using vmArgs like `
+ `'-agentlib:jdwp=transport=dt_socket,server=y,address=5005.'`);
return undefined;
}
config.processId = undefined;
config.hostName = javaProcess.hostName;
config.port = javaProcess.debugPort;
} else {
throw new utility.UserError({
message: "Please specify the hostName/port directly, or provide the processId of the remote debuggee in the launch.json.",
type: Type.USAGEERROR,
anchor: anchor.ATTACH_CONFIG_ERROR,
});
}
// Populate the class filters to the debug configuration.
await populateStepFilters(config);
} else {
throw new utility.UserError({
message: `Request type "${config.request}" is not supported. Only "launch" and "attach" are supported.`,
type: Type.USAGEERROR,
anchor: anchor.REQUEST_TYPE_NOT_SUPPORTED,
});
}
if (token?.isCancellationRequested || progressReporter.isCancelled()) {
return undefined;
}
delete config.__progressId;
return config;
} catch (ex) {
if (ex instanceof utility.JavaExtensionNotEnabledError) {
utility.guideToInstallJavaExtension();
return undefined;
}
if (ex instanceof utility.UserError) {
utility.showErrorMessageWithTroubleshooting(ex.context);
return undefined;
}
utility.showErrorMessageWithTroubleshooting(utility.convertErrorToMessage(ex));
return undefined;
} finally {
if (configCopy && config.mainClass) {
configCopy.name = config.name;
configCopy.mainClass = config.mainClass;
configCopy.projectName = config.projectName;
configCopy.__workspaceFolder = folder;
lastUsedLaunchConfig = configCopy;
}
progressReporter.done();
}
}
private async resolvePath(folder: vscode.WorkspaceFolder | undefined, pathArray: string[], mainClass: string,
projectName: string, isModulePath: boolean): Promise<string[]> {
if (_.isEmpty(pathArray)) {
return [];
}
const pathVariables: string[] = [ClasspathVariable.Auto, ClasspathVariable.Runtime, ClasspathVariable.Test];
const containedVariables: string[] = pathArray.filter((cp: string) => pathVariables.includes(cp));
if (_.isEmpty(containedVariables)) {
return this.filterExcluded(folder, pathArray);
}
const scope: string | undefined = this.mergeScope(containedVariables);
const response: any[] = <any[]> await lsPlugin.resolveClasspath(mainClass, projectName, scope);
const resolvedPaths: string[] = isModulePath ? response?.[0] : response?.[1];
if (!resolvedPaths) {
// tslint:disable-next-line:no-console
console.log("The Java Language Server failed to resolve the classpaths/modulepaths");
}
const paths: string[] = [];
let replaced: boolean = false;
for (const p of pathArray) {
if (pathVariables.includes(p)) {
if (!replaced) {
paths.push(...resolvedPaths);
replaced = true;
}
continue;
}
paths.push(p);
}
return this.filterExcluded(folder, paths);
}
private async filterExcluded(folder: vscode.WorkspaceFolder | undefined, paths: string[]): Promise<string[]> {
const result: string[] = [];
const excludes: Map<string, boolean> = new Map<string, boolean>();
for (const p of paths) {
if (p.startsWith("!")) {
let exclude = p.substr(1);
if (!path.isAbsolute(exclude)) {
exclude = path.join(folder?.uri.fsPath || "", exclude);
}
// use Uri to normalize the fs path
excludes.set(vscode.Uri.file(exclude).fsPath, this.isFilePath(exclude));
continue;
}
result.push(vscode.Uri.file(p).fsPath);
}
return result.filter((r) => {
for (const [excludedPath, isFile] of excludes.entries()) {
if (isFile && r === excludedPath) {
return false;
}
if (!isFile && r.startsWith(excludedPath)) {
return false;
}
}
return true;
});
}
private mergeScope(scopes: string[]): string | undefined {
if (scopes.includes(ClasspathVariable.Test)) {
return "test";
}
if (scopes.includes(ClasspathVariable.Auto)) {
return undefined;
}
if (scopes.includes(ClasspathVariable.Runtime)) {
return "runtime";
}
return undefined;
}
/**
* Converts an array of arguments to a string as the args and vmArgs.
*/
private concatArgs(args: any[]): string {
return _.join(_.map(args, (arg: any): string => {
const str = String(arg);
// if it has quotes or spaces, use double quotes to wrap it
if (/["\s]/.test(str)) {
return "\"" + str.replace(/(["\\])/g, "\\$1") + "\"";
}
return str;
// if it has only single quotes
}), " ");
}
/**
* When VS Code cannot find any available DebugConfiguration, it passes a { noDebug?: boolean } to resolve.
* This function judges whether a DebugConfiguration is empty by filtering out the field "noDebug".
*/
private isEmptyConfig(config: vscode.DebugConfiguration): boolean {
return Object.keys(config).filter((key: string) => key !== "noDebug").length === 0;
}
private async resolveAndValidateMainClass(folder: vscode.Uri | undefined, config: vscode.DebugConfiguration,
progressReporter: IProgressReporter): Promise<lsPlugin.IMainClassOption | undefined> {
// Validate it if the mainClass is already set in launch configuration.
if (config.mainClass && !this.isFilePath(config.mainClass)) {
progressReporter.report("Resolving main class...");
const containsExternalClasspaths = !_.isEmpty(config.classPaths) || !_.isEmpty(config.modulePaths);
const validationResponse = await lsPlugin.validateLaunchConfig(config.mainClass, config.projectName, containsExternalClasspaths, folder);
if (progressReporter.isCancelled()) {
return undefined;
} else if (!validationResponse.mainClass.isValid || !validationResponse.projectName.isValid) {
return this.fixMainClass(folder, config, validationResponse, progressReporter);
}
return {
mainClass: config.mainClass,
projectName: config.projectName,
};
}
return this.resolveMainClass(config, progressReporter);
}
private async resolveMainClass(config: vscode.DebugConfiguration, progressReporter: IProgressReporter):
Promise<lsPlugin.IMainClassOption | undefined> {
if (config.projectName) {
progressReporter.report("Resolving main class...");
if (this.isFilePath(config.mainClass)) {
const mainEntries = await lsPlugin.resolveMainMethod(vscode.Uri.file(config.mainClass));
if (progressReporter.isCancelled()) {
return undefined;
} else if (mainEntries.length) {
if (!mainClassPicker.isAutoPicked(mainEntries)) {
progressReporter.hide(true);
}
return mainClassPicker.showQuickPick(mainEntries, "Please select a main class you want to run.");
}
}
return this.promptMainClassUnderProject(config.projectName, progressReporter, "Please select a main class you wan to run");
}
// Try to resolve main class from current file
const currentFile = config.mainClass || vscode.window.activeTextEditor?.document.uri.fsPath;
if (currentFile) {
const mainEntries = await lsPlugin.resolveMainMethod(vscode.Uri.file(currentFile));
if (progressReporter.isCancelled()) {
return undefined;
} else if (mainEntries.length) {
if (!mainClassPicker.isAutoPicked(mainEntries)) {
progressReporter.hide(true);
}
return mainClassPicker.showQuickPick(mainEntries, "Please select a main class you want to run.");
}
}
// If current file is not executable, run previously used launch config.
if (lastUsedLaunchConfig) {
Object.assign(config, lastUsedLaunchConfig);
progressReporter.setJobName(utility.launchJobName(config.name, config.noDebug));
progressReporter.report("Resolving main class...");
return {
mainClass: config.mainClass,
projectName: config.projectName,
};
}
progressReporter.report("Resolving main class...");
const hintMessage = currentFile ?
`The file '${path.basename(currentFile)}' is not executable, please select a main class you want to run.` :
"Please select a main class you want to run.";
return this.promptMainClassUnderPath(undefined, progressReporter, hintMessage);
}
private isFilePath(filePath: string): boolean {
if (!filePath) {
return false;
}
try {
return fs.lstatSync(filePath).isFile();
} catch (error) {
// do nothing
return false;
}
}
private getValidationErrorMessage(error: lsPlugin.IValidationResult): string {
switch (error.kind) {
case lsPlugin.CONFIGERROR_INVALID_CLASS_NAME:
return "ConfigError: mainClass was configured with an invalid class name.";
case lsPlugin.CONFIGERROR_MAIN_CLASS_NOT_EXIST:
return "ConfigError: mainClass does not exist.";
case lsPlugin.CONFIGERROR_MAIN_CLASS_NOT_UNIQUE:
return "ConfigError: mainClass is not unique in the workspace";
case lsPlugin.CONFIGERROR_INVALID_JAVA_PROJECT:
return "ConfigError: could not find a Java project with the configured projectName.";
}
return "ConfigError: Invalid mainClass/projectName configs.";
}
private async fixMainClass(folder: vscode.Uri | undefined, config: vscode.DebugConfiguration,
validationResponse: lsPlugin.ILaunchValidationResponse, progressReporter: IProgressReporter):
Promise<lsPlugin.IMainClassOption | undefined> {
const errors: string[] = [];
if (!validationResponse.mainClass.isValid) {
errors.push(String(validationResponse.mainClass.message));
const errorLog: Error = {
name: "error",
message: this.getValidationErrorMessage(validationResponse.mainClass),
};
setUserError(errorLog);
sendError(errorLog);
}
if (!validationResponse.projectName.isValid) {
errors.push(String(validationResponse.projectName.message));
const errorLog: Error = {
name: "error",
message: this.getValidationErrorMessage(validationResponse.projectName),
};
setUserError(errorLog);
sendError(errorLog);
}
if (validationResponse.proposals && validationResponse.proposals.length) {
progressReporter.hide(true);
const answer = await utility.showErrorMessageWithTroubleshooting({
message: errors.join(os.EOL),
type: Type.USAGEERROR,
anchor: anchor.FAILED_TO_RESOLVE_CLASSPATH,
bypassLog: true, // Avoid logging the raw user input in the logger for privacy.
}, "Fix");
if (answer === "Fix") {
const selectedFix = await mainClassPicker.showQuickPick(validationResponse.proposals,
"Please select main class<project name>.", false);
if (selectedFix) {
sendInfo("", {
fix: "yes",
fixMessage: "Fix the configs of mainClass and projectName",
});
await this.persistMainClassOption(folder, config, selectedFix);
}
return selectedFix;
}
// return undefined if the user clicks "Learn More".
return undefined;
}
throw new utility.UserError({
message: errors.join(os.EOL),
type: Type.USAGEERROR,
anchor: anchor.FAILED_TO_RESOLVE_CLASSPATH,
bypassLog: true, // Avoid logging the raw user input in the logger for privacy.
});
}
private async persistMainClassOption(folder: vscode.Uri | undefined, oldConfig: vscode.DebugConfiguration, change: lsPlugin.IMainClassOption):
Promise<void> {
const newConfig: vscode.DebugConfiguration = _.cloneDeep(oldConfig);
newConfig.mainClass = change.mainClass;
newConfig.projectName = change.projectName;
return this.persistLaunchConfig(folder, oldConfig, newConfig);
}
private async persistLaunchConfig(folder: vscode.Uri | undefined, oldConfig: vscode.DebugConfiguration, newConfig: vscode.DebugConfiguration):
Promise<void> {
const launchConfigurations: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration("launch", folder);
const rawConfigs: vscode.DebugConfiguration[] = launchConfigurations.configurations;
const targetIndex: number = _.findIndex(rawConfigs, (config) => _.isEqual(config, oldConfig));
if (targetIndex >= 0) {
rawConfigs[targetIndex] = newConfig;
await launchConfigurations.update("configurations", rawConfigs);
}
}
private async promptMainClassUnderPath(folder: vscode.Uri | undefined, progressReporter: IProgressReporter, hintMessage?: string):
Promise<lsPlugin.IMainClassOption | undefined> {
const res = await lsPlugin.resolveMainClass(folder);
if (progressReporter.isCancelled()) {
return undefined;
} else if (res.length === 0) {
const workspaceFolder = folder ? vscode.workspace.getWorkspaceFolder(folder) : undefined;
throw new utility.UserError({
message: `Cannot find a class with the main method${ workspaceFolder ? " in the folder '" + workspaceFolder.name + "'" : ""}.`,
type: Type.USAGEERROR,
anchor: anchor.CANNOT_FIND_MAIN_CLASS,
});
}
if (!mainClassPicker.isAutoPicked(res)) {
progressReporter.hide(true);
}
return mainClassPicker.showQuickPickWithRecentlyUsed(res, hintMessage || "Select main class<project name>");
}
private async promptMainClassUnderProject(projectName: string, progressReporter: IProgressReporter, hintMessage?: string):
Promise<lsPlugin.IMainClassOption | undefined> {
const res = await lsPlugin.resolveMainClassFromProject(projectName);
if (progressReporter.isCancelled()) {
return undefined;
} else if (res.length === 0) {
throw new utility.UserError({
message: `Cannot find a class with the main method in the project '${projectName}'.`,
type: Type.USAGEERROR,
anchor: anchor.CANNOT_FIND_MAIN_CLASS,
});
}
if (!mainClassPicker.isAutoPicked(res)) {
progressReporter.hide(true);
}
return mainClassPicker.showQuickPickWithRecentlyUsed(res, hintMessage || "Select main class<project name>");
}
}
async function updateDebugSettings(event?: vscode.ConfigurationChangeEvent) {
const debugSettingsRoot: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration("java.debug");
if (!debugSettingsRoot) {
return;
}
const logLevel = convertLogLevel(debugSettingsRoot.logLevel || "");
const javaHome = await utility.getJavaHome();
if (debugSettingsRoot.settings && Object.keys(debugSettingsRoot.settings).length) {
try {
const stepFilters = {
skipClasses: await substituteFilterVariables(debugSettingsRoot.settings.stepping.skipClasses),
skipSynthetics: debugSettingsRoot.settings.stepping.skipSynthetics,
skipStaticInitializers: debugSettingsRoot.settings.stepping.skipStaticInitializers,
skipConstructors: debugSettingsRoot.settings.stepping.skipConstructors,
};
const exceptionFilters = {
exceptionTypes: debugSettingsRoot.settings.exceptionBreakpoint.exceptionTypes,
allowClasses: debugSettingsRoot.settings.exceptionBreakpoint.allowClasses,
skipClasses: await substituteFilterVariables(debugSettingsRoot.settings.exceptionBreakpoint.skipClasses),
};
const asyncJDWP: string = debugSettingsRoot.settings.jdwp.async;
const settings = await commands.executeJavaLanguageServerCommand(commands.JAVA_UPDATE_DEBUG_SETTINGS, JSON.stringify(
{
...debugSettingsRoot.settings,
logLevel,
javaHome,
stepFilters,
exceptionFilters,
exceptionFiltersUpdated: event &&
(event.affectsConfiguration("java.debug.settings.exceptionBreakpoint.skipClasses")
|| event.affectsConfiguration("java.debug.settings.exceptionBreakpoint.allowClasses")
|| event.affectsConfiguration("java.debug.settings.exceptionBreakpoint.exceptionTypes")),
limitOfVariablesPerJdwpRequest: Math.max(debugSettingsRoot.settings.jdwp.limitOfVariablesPerJdwpRequest, 1),
jdwpRequestTimeout: Math.max(debugSettingsRoot.settings.jdwp.requestTimeout, 100),
asyncJDWP,
}));
if (logLevel === "FINE") {
// tslint:disable-next-line:no-console
console.log("settings:", settings);
}
} catch (err) {
// log a warning message and continue, since update settings failure should not block debug session
// tslint:disable-next-line:no-console
console.log("Cannot update debug settings.", err);
}
}
}
function needsBuildWorkspace(): boolean {
const javaConfig: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration("java");
return javaConfig?.debug?.settings?.forceBuildBeforeLaunch;
}
function convertLogLevel(commonLogLevel: string) {
// convert common log level to java log level
switch (commonLogLevel.toLowerCase()) {
case "verbose":
return "FINE";
case "warn":
return "WARNING";
case "error":
return "SEVERE";
case "info":
return "INFO";
default:
return "FINE";
}
}
// from vscode-js-debug https://github.com/microsoft/vscode-js-debug/blob/master/src/targets/node/nodeLauncherBase.ts
function readEnvFile(file: string): { [key: string]: string } {
if (!fs.existsSync(file)) {
return {};
}
const buffer = stripBOM(fs.readFileSync(file, "utf8"));
const env = dotenv.parse(Buffer.from(buffer));
return env;
}
function stripBOM(s: string): string {
if (s && s[0] === "\uFEFF") {
s = s.substr(1);
}
return s;
}