-
Notifications
You must be signed in to change notification settings - Fork 906
Expand file tree
/
Copy pathgoLanguageServer.ts
More file actions
1599 lines (1488 loc) · 53.7 KB
/
goLanguageServer.ts
File metadata and controls
1599 lines (1488 loc) · 53.7 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
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
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint-disable @typescript-eslint/no-explicit-any */
/*---------------------------------------------------------
* Copyright (C) Microsoft Corporation. All rights reserved.
* Modification copyright 2020 The Go Authors. All rights reserved.
* Licensed under the MIT License. See LICENSE in the project root for license information.
*--------------------------------------------------------*/
'use strict';
import cp = require('child_process');
import fs = require('fs');
import moment = require('moment');
import path = require('path');
import semver = require('semver');
import util = require('util');
import vscode = require('vscode');
import { InitializeParams, LSPObject } from 'vscode-languageserver-protocol';
import {
CancellationToken,
CloseAction,
ConfigurationParams,
ConfigurationRequest,
ErrorAction,
ExecuteCommandParams,
ExecuteCommandRequest,
ExecuteCommandSignature,
HandleDiagnosticsSignature,
InitializeError,
InitializeResult,
LanguageClientOptions,
Message,
ProgressToken,
ProvideCodeLensesSignature,
ProvideCompletionItemsSignature,
ProvideDocumentFormattingEditsSignature,
Hover,
ResponseError,
RevealOutputChannelOn
} from 'vscode-languageclient';
import { Executable, LanguageClient, ServerOptions } from 'vscode-languageclient/node';
import { getGoConfig, getGoplsConfig, extensionInfo } from '../config';
import { toolExecutionEnvironment } from '../goEnv';
import { GoDocumentFormattingEditProvider, getFormatTool } from './legacy/goFormat';
import { installTools, latestModuleVersion, promptForMissingTool, promptForUpdatingTool } from '../goInstallTools';
import { getTool, Tool } from '../goTools';
import { updateGlobalState, updateWorkspaceState } from '../stateUtils';
import {
getBinPath,
getCheckForToolsUpdatesConfig,
getCurrentGoPath,
getGoVersion,
getWorkspaceFolderPath,
removeDuplicateDiagnostics
} from '../util';
import { getToolFromToolPath } from '../utils/pathUtils';
import fetch from 'node-fetch';
import { CompletionItemKind, FoldingContext } from 'vscode';
import { ProvideFoldingRangeSignature } from 'vscode-languageclient/lib/common/foldingRange';
import { daysBetween, getStateConfig, maybePromptForGoplsSurvey, timeDay, timeMinute } from '../goSurvey';
import { maybePromptForDeveloperSurvey } from '../developerSurvey/prompt';
import { CommandFactory } from '../commands';
import { updateLanguageServerIconGoStatusBar } from '../goStatus';
import { URI } from 'vscode-uri';
import { VulncheckReport, writeVulns } from '../goVulncheck';
import { ActiveProgressTerminals, IProgressTerminal, ProgressTerminal } from '../progressTerminal';
import { createHash } from 'crypto';
import { GoExtensionContext } from '../context';
import { GoDocumentSelector } from '../goMode';
import { COMMAND as GOPLS_ADD_TEST_COMMAND } from '../goGenerateTests';
import { COMMAND as GOPLS_MODIFY_TAGS_COMMAND } from '../goModifytags';
import { TelemetryKey, telemetryReporter } from '../goTelemetry';
import { ResolveCommand } from './form';
export interface LanguageServerConfig {
serverName: string;
path: string;
version?: { version: string; goVersion?: string };
modtime?: Date;
enabled: boolean;
flags: string[];
env: any;
features: {
// A custom formatter can be configured to run instead of gopls.
// This is enabled when the user has configured a specific format
// tool in the "go.formatTool" setting.
formatter?: GoDocumentFormattingEditProvider;
};
checkForUpdates: string;
}
export interface ServerInfo {
Name: string;
Version?: string;
GoVersion?: string;
Commands?: string[];
}
export function updateRestartHistory(goCtx: GoExtensionContext, reason: RestartReason, enabled: boolean) {
// Keep the history limited to 10 elements.
goCtx.restartHistory = goCtx.restartHistory ?? [];
while (goCtx.restartHistory.length > 10) {
goCtx.restartHistory = goCtx.restartHistory.slice(1);
}
goCtx.restartHistory.push(new Restart(reason, new Date(), enabled));
}
export enum RestartReason {
ACTIVATION = 'activation',
MANUAL = 'manual',
CONFIG_CHANGE = 'config change',
INSTALLATION = 'installation'
}
export class Restart {
reason: RestartReason;
timestamp: Date;
enabled: boolean;
constructor(reason: RestartReason, timestamp: Date, enabled: boolean) {
this.reason = reason;
this.timestamp = timestamp;
this.enabled = enabled;
}
}
// computes a bigint fingerprint of the machine id.
function hashMachineID(salt?: string): number {
const hash = createHash('md5').update(`${vscode.env.machineId}${salt}`).digest('hex');
return parseInt(hash.substring(0, 8), 16);
}
// returns true if the proposed upgrade version is mature, or we are selected for staged rollout.
export async function okForStagedRollout(
tool: Tool,
ver: semver.SemVer,
hashFn: (key?: string) => number
): Promise<boolean> {
// patch release is relatively safe to upgrade. Moreover, the patch
// can carry a fix for security which is better to apply sooner.
if (ver.patch !== 0 || ver.prerelease?.length > 0) return true;
const published = await getTimestampForVersion(tool, ver);
if (!published) return true;
const days = daysBetween(new Date(), published.toDate());
if (days <= 1) {
return hashFn(ver.version) % 100 < 10; // upgrade with 10% chance for the first day.
}
if (days <= 3) {
return hashFn(ver.version) % 100 < 30; // upgrade with 30% chance for the first 3 days.
}
return true;
}
// scheduleGoplsSuggestions sets timeouts for the various gopls-specific
// suggestions. We check user's gopls versions once per day to prompt users to
// update to the latest version. We also check if we should prompt users to
// fill out the survey.
export function scheduleGoplsSuggestions(goCtx: GoExtensionContext) {
if (extensionInfo.isInCloudIDE) {
return;
}
// Some helper functions.
const usingGo = (): boolean => {
return vscode.workspace.textDocuments.some((doc) => doc.languageId === 'go');
};
const installGopls = async (cfg: LanguageServerConfig) => {
const tool: Tool = getTool('gopls')!;
const versionToUpdate = await shouldUpdateLanguageServer(tool, cfg);
if (!versionToUpdate) {
return;
}
// If the user has opted in to automatic tool updates, we can update
// without prompting.
const toolsManagementConfig = getGoConfig()['toolsManagement'];
if (toolsManagementConfig && toolsManagementConfig['autoUpdate'] === true) {
if (extensionInfo.isPreview || (await okForStagedRollout(tool, versionToUpdate, hashMachineID))) {
const goVersion = await getGoVersion();
const toolVersion = { ...tool, version: versionToUpdate }; // ToolWithVersion
await installTools([toolVersion], goVersion, { silent: true });
} else {
console.log(`gopls ${versionToUpdate} is too new, try to update later`);
}
} else {
promptForUpdatingTool(tool.name, versionToUpdate);
}
};
const update = async () => {
setTimeout(update, timeDay);
const cfg = goCtx.latestConfig;
// trigger periodic update check only if the user is already using gopls.
// Otherwise, let's check again tomorrow.
if (!cfg || !cfg.enabled || cfg.serverName !== 'gopls') {
return;
}
await installGopls(cfg);
};
const survey = async () => {
setTimeout(survey, timeDay);
// Only prompt for the survey if the user is working on Go code.
if (!usingGo) {
return;
}
maybePromptForGoplsSurvey(goCtx);
maybePromptForDeveloperSurvey(goCtx);
};
const telemetry = () => {
if (!usingGo) {
return;
}
maybePromptForTelemetry(goCtx);
};
setTimeout(update, 10 * timeMinute);
setTimeout(survey, 30 * timeMinute);
setTimeout(telemetry, 6 * timeMinute);
}
// Ask users to fill out opt-out survey.
export async function promptAboutGoplsOptOut(goCtx: GoExtensionContext) {
// Check if the configuration is set in the workspace.
const useLanguageServer = getGoConfig().inspect('useLanguageServer');
const workspace = useLanguageServer?.workspaceFolderValue === false || useLanguageServer?.workspaceValue === false;
let cfg = getGoplsOptOutConfig(workspace);
const promptFn = async (): Promise<GoplsOptOutConfig> => {
if (cfg.prompt === false) {
return cfg;
}
// Prompt the user ~once a month.
if (cfg.lastDatePrompted && daysBetween(new Date(), cfg.lastDatePrompted) < 30) {
return cfg;
}
cfg.lastDatePrompted = new Date();
await promptForGoplsOptOutSurvey(
goCtx,
cfg,
"It looks like you've disabled the Go language server. Would you be willing to tell us why you've disabled it, so that we can improve it?"
);
return cfg;
};
cfg = await promptFn();
flushGoplsOptOutConfig(cfg, workspace);
}
async function promptForGoplsOptOutSurvey(
goCtx: GoExtensionContext,
cfg: GoplsOptOutConfig,
msg: string
): Promise<GoplsOptOutConfig> {
const s = await vscode.window.showInformationMessage(msg, { title: 'Yes' }, { title: 'No' });
if (!s) {
return cfg;
}
const localGoplsVersion = await getLocalGoplsVersion(goCtx.latestConfig);
const goplsVersion = localGoplsVersion?.version || 'na';
const goV = await getGoVersion();
let goVersion = 'na';
if (goV) {
goVersion = goV.format(true);
}
switch (s.title) {
case 'Yes':
cfg.prompt = false;
await vscode.env.openExternal(
vscode.Uri.parse(
`https://google.qualtrics.com/jfe/form/SV_doId0RNgV3pHovc?gopls=${goplsVersion}&go=${goVersion}&os=${process.platform}`
)
);
break;
case 'No':
break;
}
return cfg;
}
export interface GoplsOptOutConfig {
prompt?: boolean;
lastDatePrompted?: Date;
}
const goplsOptOutConfigKey = 'goplsOptOutConfig';
export const getGoplsOptOutConfig = (workspace: boolean): GoplsOptOutConfig => {
return getStateConfig(goplsOptOutConfigKey, workspace) as GoplsOptOutConfig;
};
export const flushGoplsOptOutConfig = (cfg: GoplsOptOutConfig, workspace: boolean) => {
if (workspace) {
updateWorkspaceState(goplsOptOutConfigKey, JSON.stringify(cfg));
}
updateGlobalState(goplsOptOutConfigKey, JSON.stringify(cfg));
};
// exported for testing.
export async function stopLanguageClient(goCtx: GoExtensionContext) {
const c = goCtx.languageClient;
goCtx.crashCount = 0;
goCtx.telemetryService = undefined;
goCtx.languageClient = undefined;
if (!c) return false;
if (c.diagnostics) {
c.diagnostics.clear();
}
// LanguageClient.stop may hang if the language server
// crashes during shutdown before responding to the
// shutdown request. Enforce client-side timeout.
try {
c.stop(2000);
} catch (e) {
c.outputChannel?.appendLine(`Failed to stop client: ${e}`);
}
}
export function toServerInfo(res?: InitializeResult): ServerInfo | undefined {
if (!res) return undefined;
const info: ServerInfo = {
Commands: res.capabilities?.executeCommandProvider?.commands || [],
Name: res.serverInfo?.name || 'unknown'
};
try {
interface serverVersionJSON {
GoVersion?: string;
Version?: string;
// before gopls 0.8.0
version?: string;
}
const v = <serverVersionJSON>(res.serverInfo?.version ? JSON.parse(res.serverInfo.version) : {});
info.Version = v.Version || v.version;
info.GoVersion = v.GoVersion;
} catch (e) {
// gopls is not providing any info, that's ok.
}
return info;
}
export class GoLanguageClient extends LanguageClient implements vscode.Disposable {
constructor(
id: string,
name: string,
serverOptions: ServerOptions,
clientOptions: LanguageClientOptions,
private onDidChangeVulncheckResultEmitter: vscode.EventEmitter<VulncheckEvent>
) {
super(id, name, serverOptions, clientOptions);
}
dispose(timeout?: number) {
this.onDidChangeVulncheckResultEmitter.dispose();
return super.dispose(timeout);
}
public get onDidChangeVulncheckResult(): vscode.Event<VulncheckEvent> {
return this.onDidChangeVulncheckResultEmitter.event;
}
protected fillInitializeParams(params: InitializeParams): void {
super.fillInitializeParams(params);
// VSCode-Go honors most client capabilities from the vscode-languageserver-node
// library. Experimental capabilities not used by vscode-languageserver-node
// can be used for custom communication between vscode-go and gopls.
// See https://github.com/microsoft/vscode-languageserver-node/issues/1607
const experimental: LSPObject = {
progressMessageStyles: ['log'],
interactiveInputTypes: ['bool', 'documentURI', 'enum', 'lazyEnum', 'number', 'string']
};
params.capabilities.experimental = experimental;
}
}
type VulncheckEvent = {
URI?: URI;
message?: string;
};
// buildLanguageClient returns a language client built using the given language server config.
// The returned language client need to be started before use.
export async function buildLanguageClient(
goCtx: GoExtensionContext,
cfg: LanguageServerConfig
): Promise<GoLanguageClient> {
// Reuse the same output channel for each instance of the server.
if (cfg.enabled) {
if (!goCtx.serverOutputChannel) {
goCtx.serverOutputChannel = vscode.window.createOutputChannel(cfg.serverName + ' (server)');
}
if (!goCtx.serverTraceChannel) {
goCtx.serverTraceChannel = vscode.window.createOutputChannel(cfg.serverName);
}
}
await getLocalGoplsVersion(cfg); // populate and cache cfg.version
const goplsWorkspaceConfig = await adjustGoplsWorkspaceConfiguration(cfg, getGoplsConfig(), 'gopls', undefined);
// when initialization is failed after the connection is established,
// we want to handle the connection close error case specially. Capture the error
// in initializationFailedHandler and handle it in the connectionCloseHandler.
let initializationError: ResponseError<InitializeError> | undefined = undefined;
// TODO(hxjiang): deprecate special handling for async call gopls.run_govulncheck.
let govulncheckTerminal: IProgressTerminal | undefined;
const pendingVulncheckProgressToken = new Map<ProgressToken, any>();
const onDidChangeVulncheckResultEmitter = new vscode.EventEmitter<VulncheckEvent>();
// VSCode-Go prepares the information needed to start the language server.
// vscode-languageclient-node.LanguageClient will spin up the language
// server based on the provided information below.
const serverOption: Executable = {
command: cfg.path,
args: cfg.flags,
options: { env: cfg.env }
};
// cfg is captured by closures for later use during error report.
const c = new GoLanguageClient(
'go', // id
cfg.serverName, // name e.g. gopls
serverOption as ServerOptions,
{
initializationOptions: goplsWorkspaceConfig,
documentSelector: GoDocumentSelector,
uriConverters: {
// Apply file:/// scheme to all file paths.
code2Protocol: (uri: vscode.Uri): string =>
(uri.scheme ? uri : uri.with({ scheme: 'file' })).toString(),
protocol2Code: (uri: string) => vscode.Uri.parse(uri)
},
outputChannel: goCtx.serverOutputChannel,
traceOutputChannel: goCtx.serverTraceChannel,
revealOutputChannelOn: RevealOutputChannelOn.Never,
initializationFailedHandler: (error: ResponseError<InitializeError>): boolean => {
initializationError = error;
return false;
},
errorHandler: {
error: (error: Error, message: Message, count: number) => {
// Allow 5 crashes before shutdown.
if (count < 5) {
return {
message: '', // suppresses error popups
action: ErrorAction.Continue
};
}
return {
message: '', // suppresses error popups
action: ErrorAction.Shutdown
};
},
closed: () => {
if (initializationError !== undefined) {
suggestActionAfterGoplsStartError(goCtx, cfg);
initializationError = undefined;
// In case of initialization failure, do not try to restart.
return {
message: '', // suppresses error popups - there will be other popups. :-(
action: CloseAction.DoNotRestart
};
}
// Allow 5 crashes before shutdown.
const { crashCount = 0 } = goCtx;
goCtx.crashCount = crashCount + 1;
if (goCtx.crashCount < 5) {
updateLanguageServerIconGoStatusBar(c, true);
return {
message: '', // suppresses error popups
action: CloseAction.Restart
};
}
suggestActionAfterGoplsStartError(goCtx, cfg);
updateLanguageServerIconGoStatusBar(c, true);
return {
message: '', // suppresses error popups - there will be other popups.
action: CloseAction.DoNotRestart
};
}
},
middleware: {
provideTypeDefinition: async (doc, pos, token, next) => {
if (!goCtx.languageClient) {
return await next(doc, pos, token);
}
const editor = vscode.window.activeTextEditor;
if (!editor || doc !== editor.document) {
return await next(doc, pos, token);
}
const selection = editor?.selection;
if (selection.isEmpty || !selection.contains(pos)) {
return await next(doc, pos, token);
}
// Attaching selected range to gopls type def request.
const param = goCtx.languageClient.code2ProtocolConverter.asTextDocumentPositionParams(doc, pos);
(param as any).range = goCtx.languageClient.code2ProtocolConverter.asRange(selection);
const result: any = await vscode.commands.executeCommand('gopls.lsp', {
method: 'textDocument/typeDefinition',
param: param
});
return goCtx.languageClient.protocol2CodeConverter.asDefinitionResult(result);
},
provideHover: async (doc, pos, token, next) => {
// gopls.lsp is a command that acts as a dispatcher, allowing
// the client to trigger any LSP RPC via "workspace/executeCommand"
// request with custom param.
const supportLSPCommand = goCtx.serverInfo?.Commands?.includes('gopls.lsp');
if (!supportLSPCommand) {
return await next(doc, pos, token);
}
const editor = vscode.window.activeTextEditor;
if (!editor || doc !== editor.document) {
return await next(doc, pos, token);
}
const selection = editor?.selection;
if (selection.isEmpty || !selection.contains(pos)) {
return await next(doc, pos, token);
}
if (!goCtx.languageClient) {
return await next(doc, pos, token);
}
// Attaching selected range to gopls hover request.
// See golang/go#69058.
const param = goCtx.languageClient.code2ProtocolConverter.asTextDocumentPositionParams(doc, pos);
(param as any).range = goCtx.languageClient.code2ProtocolConverter.asRange(selection);
const result: Hover = await vscode.commands.executeCommand('gopls.lsp', {
method: 'textDocument/hover',
param: param
});
return goCtx.languageClient.protocol2CodeConverter.asHover(result);
},
handleWorkDoneProgress: async (token, params, next) => {
switch (params.kind) {
case 'begin':
if (typeof params.message === 'string') {
const paragraphs = params.message.split('\n\n', 2);
const metadata = paragraphs[0].trim();
if (!metadata.startsWith('style: ')) {
break;
}
const style = metadata.substring('style: '.length);
if (style === 'log') {
const term = ProgressTerminal.Open(params.title, token);
if (paragraphs.length > 1) {
term.appendLine(paragraphs[1]);
}
term.show();
}
}
break;
case 'report':
if (params.message) {
ActiveProgressTerminals.get(token)?.appendLine(params.message);
}
if (pendingVulncheckProgressToken.has(token) && params.message) {
govulncheckTerminal?.appendLine(params.message);
}
break;
case 'end':
if (params.message) {
ActiveProgressTerminals.get(token)?.appendLine(params.message);
}
if (pendingVulncheckProgressToken.has(token)) {
const out = pendingVulncheckProgressToken.get(token);
pendingVulncheckProgressToken.delete(token);
// success. In case of failure, it will be 'failed'
onDidChangeVulncheckResultEmitter.fire({ URI: out.URI, message: params.message });
}
}
next(token, params);
},
executeCommand: async (command: string, args: any[], next: ExecuteCommandSignature) => {
const supported = c.initializeResult?.capabilities?.experimental?.interactiveResolveProvider;
if (Array.isArray(supported) && supported.includes('command')) {
const resolved = await ResolveCommand(goCtx, command, args);
if (!resolved) {
return undefined;
}
// Replace original command and result with resolved command and args.
command = resolved.command;
args = resolved.args;
}
try {
if (command === 'gopls.tidy' || command === 'gopls.vulncheck') {
await vscode.workspace.saveAll(false);
}
if (command === 'gopls.run_govulncheck' && args.length && args[0].URI) {
if (govulncheckTerminal) {
vscode.window.showErrorMessage(
'cannot start vulncheck while another vulncheck is in progress'
);
return;
}
await vscode.workspace.saveAll(false);
const uri = args[0].URI ? URI.parse(args[0].URI) : undefined;
const dir = uri?.fsPath?.endsWith('.mod') ? path.dirname(uri.fsPath) : uri?.fsPath;
govulncheckTerminal = ProgressTerminal.Open('govulncheck');
govulncheckTerminal.appendLine(`⚡ govulncheck -C ${dir} ./...\n\n`);
govulncheckTerminal.show();
}
const res = await next(command, args);
const progressToken = res?.Token as ProgressToken;
// The progressToken from executeCommand indicates that
// gopls may trigger a related workDoneProgress
// notification, either before or after the command
// completes.
// https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#serverInitiatedProgress
if (progressToken !== undefined) {
switch (command) {
case 'gopls.run_govulncheck':
pendingVulncheckProgressToken.set(progressToken, args[0]);
break;
case 'gopls.vulncheck':
// Write the vulncheck report to the terminal.
if (ActiveProgressTerminals.has(progressToken)) {
writeVulns(res.Result, ActiveProgressTerminals.get(progressToken), cfg.path);
}
break;
default:
// By default, dump the result to the terminal.
ActiveProgressTerminals.get(progressToken)?.appendLine(res.Result);
}
}
return res;
} catch (e) {
// Suppress error messages for frequently triggered
// or programmatically triggered commads.
if (command === 'gopls.package_symbols' || command === 'gopls.lsp') {
return null;
}
// TODO: how to print ${e} reliably???
const answer = await vscode.window.showErrorMessage(
`Command '${command}' failed: ${e}.`,
'Show Trace'
);
if (answer === 'Show Trace') {
goCtx.serverOutputChannel?.show();
}
return null;
}
},
provideFoldingRanges: async (
doc: vscode.TextDocument,
context: FoldingContext,
token: CancellationToken,
next: ProvideFoldingRangeSignature
) => {
const ranges = await next(doc, context, token);
if ((!ranges || ranges.length === 0) && doc.lineCount > 0) {
return undefined;
}
return ranges;
},
provideCodeLenses: async (
doc: vscode.TextDocument,
token: vscode.CancellationToken,
next: ProvideCodeLensesSignature
): Promise<vscode.CodeLens[]> => {
const codeLens = await next(doc, token);
if (!codeLens || codeLens.length === 0) {
return codeLens ?? [];
}
return codeLens.reduce((lenses: vscode.CodeLens[], lens: vscode.CodeLens) => {
switch (lens.command?.title) {
case 'run test': {
return [...lenses, ...createTestCodeLens(lens)];
}
case 'run benchmark': {
return [...lenses, ...createBenchmarkCodeLens(lens)];
}
default: {
return [...lenses, lens];
}
}
}, []);
},
provideDocumentFormattingEdits: async (
document: vscode.TextDocument,
options: vscode.FormattingOptions,
token: vscode.CancellationToken,
next: ProvideDocumentFormattingEditsSignature
) => {
// If a custom formatter is configured, use it.
if (cfg.features.formatter) {
return cfg.features.formatter.provideDocumentFormattingEdits(document, options, token);
}
// Otherwise, fall back to gopls.
return next(document, options, token);
},
handleDiagnostics: (
uri: vscode.Uri,
diagnostics: vscode.Diagnostic[],
next: HandleDiagnosticsSignature
) => {
const { buildDiagnosticCollection, lintDiagnosticCollection, vetDiagnosticCollection } = goCtx;
// Deduplicate diagnostics with those found by the other tools.
removeDuplicateDiagnostics(vetDiagnosticCollection, uri, diagnostics);
removeDuplicateDiagnostics(buildDiagnosticCollection, uri, diagnostics);
removeDuplicateDiagnostics(lintDiagnosticCollection, uri, diagnostics);
return next(uri, diagnostics);
},
provideCompletionItem: async (
document: vscode.TextDocument,
position: vscode.Position,
context: vscode.CompletionContext,
token: vscode.CancellationToken,
next: ProvideCompletionItemsSignature
) => {
const list = await next(document, position, context, token);
if (!list) {
return list;
}
const items = Array.isArray(list) ? list : list.items;
// Give all the candidates the same filterText to trick VSCode
// into not reordering our candidates. All the candidates will
// appear to be equally good matches, so VSCode's fuzzy
// matching/ranking just maintains the natural "sortText"
// ordering. We can only do this in tandem with
// "incompleteResults" since otherwise client side filtering is
// important.
if (!Array.isArray(list) && list.isIncomplete && list.items.length > 1) {
let hardcodedFilterText = items[0].filterText;
if (!hardcodedFilterText) {
// tslint:disable:max-line-length
// According to LSP spec,
// https://microsoft.github.io/language-server-protocol/specifications/specification-current/#textDocument_completion
// if filterText is falsy, the `label` should be used.
// But we observed that's not the case.
// Even if vscode picked the label value, that would
// cause to reorder candiates, which is not ideal.
// Force to use non-empty `label`.
// https://github.com/golang/vscode-go/issues/441
let { label } = items[0];
if (typeof label !== 'string') label = label.label;
hardcodedFilterText = label;
}
for (const item of items) {
item.filterText = hardcodedFilterText;
}
}
const paramHints = vscode.workspace.getConfiguration('editor.parameterHints', {
languageId: 'go',
uri: document.uri
});
// If the user has parameterHints (signature help) enabled,
// trigger it for function or method completion items.
if (paramHints.get<boolean>('enabled') === true) {
for (const item of items) {
if (item.kind === CompletionItemKind.Method || item.kind === CompletionItemKind.Function) {
item.command = {
title: 'triggerParameterHints',
command: 'editor.action.triggerParameterHints'
};
}
}
}
return list;
},
// Keep track of the last file change in order to not prompt
// user if they are actively working.
didOpen: async (e, next) => {
goCtx.lastUserAction = new Date();
next(e);
},
didChange: async (e, next) => {
goCtx.lastUserAction = new Date();
next(e);
},
didClose: async (e, next) => {
goCtx.lastUserAction = new Date();
next(e);
},
didSave: async (e, next) => {
goCtx.lastUserAction = new Date();
next(e);
},
workspace: {
configuration: async (
params: ConfigurationParams,
token: CancellationToken,
next: ConfigurationRequest.HandlerSignature
): Promise<any[] | ResponseError<void>> => {
const configs = await next(params, token);
if (!configs || !Array.isArray(configs)) {
return configs;
}
const ret = [] as any[];
for (let i = 0; i < configs.length; i++) {
let workspaceConfig = configs[i];
if (!!workspaceConfig && typeof workspaceConfig === 'object') {
const scopeUri = params.items[i].scopeUri;
const resource = scopeUri ? vscode.Uri.parse(scopeUri) : undefined;
const section = params.items[i].section;
workspaceConfig = await adjustGoplsWorkspaceConfiguration(
cfg,
workspaceConfig,
section,
resource
);
}
ret.push(workspaceConfig);
}
return ret;
}
},
resolveCodeAction: async (item, token, next) => {
if (item.command) {
switch (item.command.command) {
case GOPLS_ADD_TEST_COMMAND:
telemetryReporter.add(TelemetryKey.COMMAND_TRIGGER_GOPLS_ADD_TEST_CODE_ACTION, 1);
break;
case GOPLS_MODIFY_TAGS_COMMAND:
telemetryReporter.add(TelemetryKey.COMMAND_TRIGGER_GOPLS_MODIFY_TAGS_CODE_ACTION, 1);
break;
}
}
try {
return await next(item, token);
} catch (e) {
const answer = await vscode.window.showErrorMessage(
`code action resolve failed: ${e}.`,
'Show Trace'
);
if (answer === 'Show Trace') {
goCtx.serverOutputChannel?.show();
}
return null;
}
}
}
} as LanguageClientOptions,
onDidChangeVulncheckResultEmitter
);
onDidChangeVulncheckResultEmitter.event(async (e: VulncheckEvent) => {
if (!govulncheckTerminal) {
return;
}
if (!e || !e.URI) {
govulncheckTerminal.appendLine(`unexpected vulncheck event: ${JSON.stringify(e)}`);
return;
}
try {
if (e.message === 'completed') {
const res = await goplsFetchVulncheckResult(goCtx, e.URI.toString());
if (res!.Vulns) {
vscode.window.showWarningMessage(
'upgrade gopls (v0.14.0 or newer) to see the details about detected vulnerabilities'
);
} else {
await writeVulns(res, govulncheckTerminal, cfg.path);
}
} else {
govulncheckTerminal.appendLine(`terminated without result: ${e.message}`);
}
} catch (e) {
govulncheckTerminal.appendLine(`Fetching govulncheck output from gopls failed ${e}`);
} finally {
govulncheckTerminal.show();
govulncheckTerminal = undefined;
}
});
return c;
}
// filterGoplsDefaultConfigValues removes the entries filled based on the default values
// and selects only those the user explicitly specifies in their settings.
// This returns a new object created based on the filtered properties of workspaceConfig.
// Exported for testing.
export function filterGoplsDefaultConfigValues(workspaceConfig: any, resource?: vscode.Uri): any {
if (!workspaceConfig) {
workspaceConfig = {};
}
const cfg = getGoplsConfig(resource);
const filtered = {} as { [key: string]: any };
for (const [key, value] of Object.entries(workspaceConfig)) {
if (typeof value === 'function') {
continue;
}
const c = cfg.inspect(key);
// select only the field whose current value comes from non-default setting.
if (
!c ||
!util.isDeepStrictEqual(c.defaultValue, value) ||
// c.defaultValue !== value would be most likely sufficient, except
// when gopls' default becomes different from extension's default.
// So, we also forward the key if ever explicitely stated in one of the
// settings layers.
c.globalLanguageValue !== undefined ||
c.globalValue !== undefined ||
c.workspaceFolderLanguageValue !== undefined ||
c.workspaceFolderValue !== undefined ||
c.workspaceLanguageValue !== undefined ||
c.workspaceValue !== undefined
) {
filtered[key] = value;
}
}
return filtered;
}
// passGoConfigToGoplsConfigValues passes some of the relevant 'go.' settings to gopls settings.
// This assumes `goplsWorkspaceConfig` is an output of filterGoplsDefaultConfigValues,
// so it is modifiable and doesn't contain properties that are not explicitly set.
// - go.buildTags and go.buildFlags are passed as gopls.build.buildFlags
// if goplsWorkspaceConfig doesn't explicitly set it yet.
// Exported for testing.
export function passGoConfigToGoplsConfigValues(goplsWorkspaceConfig: any, goWorkspaceConfig: any): any {
if (!goplsWorkspaceConfig) {
goplsWorkspaceConfig = {};
}
const buildFlags = [] as string[];
if (goWorkspaceConfig?.buildFlags) {
buildFlags.push(...goWorkspaceConfig.buildFlags);
}
if (goWorkspaceConfig?.buildTags && buildFlags.indexOf('-tags') === -1) {
buildFlags.push('-tags', goWorkspaceConfig?.buildTags);
}
// If gopls.build.buildFlags is set, don't touch it.
if (buildFlags.length > 0 && goplsWorkspaceConfig['build.buildFlags'] === undefined) {
goplsWorkspaceConfig['build.buildFlags'] = buildFlags;
}
return goplsWorkspaceConfig;
}
// adjustGoplsWorkspaceConfiguration filters unnecessary options and adds any necessary, additional
// options to the gopls config. See filterGoplsDefaultConfigValues, passGoConfigToGoplsConfigValues.
// If this is for the nightly extension, we also request to activate features under experiments.
async function adjustGoplsWorkspaceConfiguration(
cfg: LanguageServerConfig,
workspaceConfig: any,
section?: string,
resource?: vscode.Uri
): Promise<any> {
// We process only gopls config
if (section !== 'gopls') {
return workspaceConfig;
}
workspaceConfig = filterGoplsDefaultConfigValues(workspaceConfig, resource) || {};
// note: workspaceConfig is a modifiable, valid object.
const goConfig = getGoConfig(resource);
workspaceConfig = passGoConfigToGoplsConfigValues(workspaceConfig, goConfig);
workspaceConfig = await passInlayHintConfigToGopls(cfg, workspaceConfig, goConfig);
workspaceConfig = await passVulncheckConfigToGopls(cfg, workspaceConfig, goConfig);
workspaceConfig = await passLinkifyShowMessageToGopls(cfg, workspaceConfig);
// Only modify the user's configurations for the Nightly.
if (!extensionInfo.isPreview) {
return workspaceConfig;
}
if (workspaceConfig && !workspaceConfig['allExperiments']) {
workspaceConfig['allExperiments'] = true;
}
return workspaceConfig;
}
async function passInlayHintConfigToGopls(cfg: LanguageServerConfig, goplsConfig: any, goConfig: any) {
const goplsVersion = await getLocalGoplsVersion(cfg);
if (!goplsVersion) return goplsConfig ?? {};
const version = semver.parse(goplsVersion.version);
if ((version?.compare('0.8.4') ?? 1) > 0) {
const { inlayHints } = goConfig;
if (inlayHints) {
goplsConfig['ui.inlayhint.hints'] = { ...inlayHints };
}
}
return goplsConfig;
}
async function passVulncheckConfigToGopls(cfg: LanguageServerConfig, goplsConfig: any, goConfig: any) {
const goplsVersion = await getLocalGoplsVersion(cfg);
if (!goplsVersion) return goplsConfig ?? {};
const version = semver.parse(goplsVersion.version);
if ((version?.compare('0.10.1') ?? 1) > 0) {
const vulncheck = goConfig.get('diagnostic.vulncheck');
if (vulncheck) {
goplsConfig['ui.vulncheck'] = vulncheck;
}
}
return goplsConfig;
}