This repository has been archived by the owner on Jul 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 645
/
Copy pathgoInstallTools.ts
533 lines (484 loc) · 18 KB
/
goInstallTools.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
/*---------------------------------------------------------
* Copyright (C) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------*/
'use strict';
import vscode = require('vscode');
import fs = require('fs');
import path = require('path');
import cp = require('child_process');
import { showGoStatus, hideGoStatus, outputChannel } from './goStatus';
import { getBinPath, getToolsGopath, getGoVersion, SemVersion, isVendorSupported, getCurrentGoPath, resolvePath } from './util';
import { goLiveErrorsEnabled } from './goLiveErrors';
let updatesDeclinedTools: string[] = [];
let installsDeclinedTools: string[] = [];
const _allTools: { [key: string]: string } = {
'gocode': 'github.com/mdempsky/gocode',
'gocode-gomod': 'github.com/stamblerre/gocode',
'gopkgs': 'github.com/uudashr/gopkgs/cmd/gopkgs',
'go-outline': 'github.com/ramya-rao-a/go-outline',
'go-symbols': 'github.com/acroca/go-symbols',
'guru': 'golang.org/x/tools/cmd/guru',
'gorename': 'golang.org/x/tools/cmd/gorename',
'gomodifytags': 'github.com/fatih/gomodifytags',
'goplay': 'github.com/haya14busa/goplay/cmd/goplay',
'impl': 'github.com/josharian/impl',
'gotype-live': 'github.com/tylerb/gotype-live',
'godef': 'github.com/rogpeppe/godef',
'godef-gomod': 'github.com/ianthehat/godef',
'gogetdoc': 'github.com/zmb3/gogetdoc',
'goimports': 'golang.org/x/tools/cmd/goimports',
'goreturns': 'github.com/sqs/goreturns',
'goformat': 'winterdrache.de/goformat/goformat',
'golint': 'golang.org/x/lint/golint',
'gotests': 'github.com/cweill/gotests/...',
'gometalinter': 'github.com/alecthomas/gometalinter',
'megacheck': 'honnef.co/go/tools/...',
'golangci-lint': 'github.com/golangci/golangci-lint/cmd/golangci-lint',
'revive': 'github.com/mgechev/revive',
'go-langserver': 'github.com/sourcegraph/go-langserver',
'dlv': 'github.com/derekparker/delve/cmd/dlv',
'fillstruct': 'github.com/davidrjenni/reftools/cmd/fillstruct',
};
function getToolImportPath(tool: string, goVersion: SemVersion) {
if (tool === 'gocode' && goVersion && goVersion.major < 2 && goVersion.minor < 9) {
return 'github.com/nsf/gocode';
}
return _allTools[tool];
}
// Tools used explicitly by the basic features of the extension
const importantTools = [
'gocode',
'gocode-gomod',
'gopkgs',
'go-outline',
'go-symbols',
'guru',
'gorename',
'godef',
'godef-gomod',
'gogetdoc',
'goreturns',
'goimports',
'golint',
'gometalinter',
'megacheck',
'golangci-lint',
'revive',
'dlv'
];
function getTools(goVersion: SemVersion): string[] {
let goConfig = vscode.workspace.getConfiguration('go', vscode.window.activeTextEditor ? vscode.window.activeTextEditor.document.uri : null);
let tools: string[] = [
'gocode',
'gopkgs',
'go-outline',
'go-symbols',
'guru',
'gorename',
'dlv'
];
// gocode-gomod needed in go 1.11 & higher
if (!goVersion || (goVersion.major === 1 && goVersion.minor >= 11)) {
tools.push('gocode-gomod');
}
// Install the doc/def tool that was chosen by the user
if (goConfig['docsTool'] === 'godoc') {
tools.push('godef');
// godef-gomod needed in go 1.11 & higher
if (!goVersion || (goVersion.major === 1 && goVersion.minor >= 11)) {
tools.push('godef-gomod');
}
}
// Install the formattool that was chosen by the user
if (goConfig['formatTool'] === 'goimports') {
tools.push('goimports');
} else if (goConfig['formatTool'] === 'goformat') {
tools.push('goformat');
} else if (goConfig['formatTool'] === 'goreturns') {
tools.push('goreturns');
}
// Tools not supported in go1.8
if (!goVersion || (goVersion.major > 1 || (goVersion.major === 1 && goVersion.minor > 8))) {
if (goConfig['lintTool'] === 'golint') {
tools.push('golint');
}
if (goConfig['docsTool'] === 'gogetdoc') {
tools.push('gogetdoc');
}
}
if (goConfig['lintTool'] === 'gometalinter') {
tools.push('gometalinter');
}
if (goConfig['lintTool'] === 'megacheck') {
tools.push('megacheck');
}
if (goConfig['lintTool'] === 'golangci-lint') {
tools.push('golangci-lint');
}
if (goConfig['lintTool'] === 'revive') {
tools.push('revive');
}
if (goConfig['useLanguageServer']) {
tools.push('go-langserver');
}
if (goLiveErrorsEnabled()) {
tools.push('gotype-live');
}
// gotests is not supported in go1.5
if (!goVersion || (goVersion.major > 1 || (goVersion.major === 1 && goVersion.minor > 5))) {
tools.push('gotests');
}
tools.push(
'gomodifytags',
'impl',
'fillstruct',
'goplay'
);
return tools;
}
export function installAllTools(updateExistingToolsOnly: boolean = false) {
const allToolsDescription: { [key: string]: string } = {
'gocode': '\t\t(Auto-completion)',
'gocode-gomod': '(Autocompletion, works with Modules)',
'gopkgs': '\t\t(Auto-completion of unimported packages & Add Import feature)',
'go-outline': '\t(Go to symbol in file)',
'go-symbols': '\t(Go to symbol in workspace)',
'guru': '\t\t(Find all references and Go to implementation of symbols)',
'gorename': '\t(Rename symbols)',
'gomodifytags': '(Modify tags on structs)',
'goplay': '\t\t(The Go playground)',
'impl': '\t\t(Stubs for interfaces)',
'gotype-live': 'Show errors as you type)',
'godef': '\t\t(Go to definition)',
'godef-gomod': '\t(Go to definition, works with Modules)',
'gogetdoc': '\t(Go to definition & text shown on hover)',
'goimports': '\t(Formatter)',
'goreturns': '\t(Formatter)',
'goformat': '\t(Formatter)',
'golint': '\t\t(Linter)',
'gotests': '\t\t(Generate unit tests)',
'gometalinter': 'Linter)',
'megacheck': '\t(Linter)',
'golangci-lint': 'Linter)',
'revive': '\t\t(Linter)',
'go-langserver': '(Language Server)',
'dlv': '\t\t\t(Debugging)',
'fillstruct': '\t\t(Fill structs with defaults)'
};
getGoVersion().then((goVersion) => {
const allTools = getTools(goVersion);
if (updateExistingToolsOnly) {
installTools(allTools.filter(tool => {
const toolPath = getBinPath(tool);
return toolPath && path.isAbsolute(toolPath);
}), goVersion);
return;
}
vscode.window.showQuickPick(allTools.map(x => `${x} ${allToolsDescription[x]}`), {
canPickMany: true,
placeHolder: 'Select the tool to install/update.'
}).then(selectedTools => {
if (!selectedTools) {
return;
}
installTools(selectedTools.map(x => x.substr(0, x.indexOf(' '))), goVersion);
});
});
}
export function promptForMissingTool(tool: string) {
// If user has declined to install, then don't prompt
if (installsDeclinedTools.indexOf(tool) > -1) {
return;
}
getGoVersion().then((goVersion) => {
if (goVersion && goVersion.major === 1 && goVersion.minor < 6) {
if (tool === 'golint') {
vscode.window.showInformationMessage('golint no longer supports go1.8, update your settings to use gometalinter as go.lintTool and install gometalinter');
return;
}
if (tool === 'gotests') {
vscode.window.showInformationMessage('Generate unit tests feature is not supported as gotests tool needs go1.6 or higher.');
return;
}
}
const items = ['Install'];
getMissingTools(goVersion).then(missing => {
if (missing.indexOf(tool) === -1) {
return;
}
missing = missing.filter(x => x === tool || importantTools.indexOf(x) > -1);
if (missing.length > 1 && tool.indexOf('-gomod') === -1) {
items.push('Install All');
}
let msg = `The "${tool}" command is not available. Use "go get -v ${getToolImportPath(tool, goVersion)}" to install.`;
if (tool === 'gocode-gomod') {
msg = `To provide auto-completions when using Go modules, we are testing a fork(${getToolImportPath(tool, goVersion)}) of "gocode" and an updated version of "gopkgs". Please press the Install button to install them.`;
} else if (tool === 'godef-gomod') {
msg = `To provide the Go to definition feature when using Go modules, we are testing a fork(${getToolImportPath(tool, goVersion)}) of "godef". Please press the Install button to install it.`;
}
vscode.window.showInformationMessage(msg, ...items).then(selected => {
if (selected === 'Install') {
if (tool === 'gocode-gomod') {
installTools(['gocode-gomod', 'gopkgs'], goVersion);
} else {
installTools([tool], goVersion);
}
} else if (selected === 'Install All') {
installTools(missing, goVersion);
hideGoStatus();
} else {
installsDeclinedTools.push(tool);
}
});
});
});
}
export function promptForUpdatingTool(tool: string) {
// If user has declined to update, then don't prompt
if (updatesDeclinedTools.indexOf(tool) > -1) {
return;
}
getGoVersion().then((goVersion) => {
vscode.window.showInformationMessage(`The Go extension is better with the latest version of "${tool}". Use "go get -u -v ${getToolImportPath(tool, goVersion)}" to update`, 'Update').then(selected => {
if (selected === 'Update') {
installTools([tool], goVersion);
} else {
updatesDeclinedTools.push(tool);
}
});
});
}
/**
* Installs given array of missing tools. If no input is given, the all tools are installed
*
* @param string[] array of tool names to be installed
*/
export function installTools(missing: string[], goVersion: SemVersion) {
let goRuntimePath = getBinPath('go');
if (!goRuntimePath) {
vscode.window.showInformationMessage('Cannot find "go" binary. Update PATH or GOROOT appropriately');
return;
}
if (!missing) {
return;
}
// http.proxy setting takes precedence over environment variables
let httpProxy = vscode.workspace.getConfiguration('http').get('proxy');
let envForTools = Object.assign({}, process.env);
if (httpProxy) {
envForTools = Object.assign({}, process.env, {
http_proxy: httpProxy,
HTTP_PROXY: httpProxy,
https_proxy: httpProxy,
HTTPS_PROXY: httpProxy,
});
}
// If the go.toolsGopath is set, use its value as the GOPATH for the "go get" child process.
// Else use the Current Gopath
let toolsGopath = getToolsGopath() || getCurrentGoPath();
if (toolsGopath) {
let paths = toolsGopath.split(path.delimiter);
toolsGopath = paths[0];
envForTools['GOPATH'] = toolsGopath;
} else {
vscode.window.showInformationMessage('Cannot install Go tools. Set either go.gopath or go.toolsGopath in settings.', 'Open User Settings', 'Open Workspace Settings').then(selected => {
if (selected === 'Open User Settings') {
vscode.commands.executeCommand('workbench.action.openGlobalSettings');
} else if (selected === 'Open Workspace Settings') {
vscode.commands.executeCommand('workbench.action.openWorkspaceSettings');
}
});
return;
}
envForTools['GO111MODULE'] = 'off';
outputChannel.show();
outputChannel.clear();
outputChannel.appendLine(`Installing ${missing.length} ${missing.length > 1 ? 'tools' : 'tool'} at ${toolsGopath}${path.sep}bin`);
missing.forEach((missingTool, index, missing) => {
outputChannel.appendLine(' ' + missingTool);
});
outputChannel.appendLine(''); // Blank line for spacing.
missing.reduce((res: Promise<string[]>, tool: string) => {
return res.then(sofar => new Promise<string[]>((resolve, reject) => {
const callback = (err: Error, stdout: string, stderr: string) => {
if (err) {
outputChannel.appendLine('Installing ' + getToolImportPath(tool, goVersion) + ' FAILED');
let failureReason = tool + ';;' + err + stdout.toString() + stderr.toString();
resolve([...sofar, failureReason]);
} else {
outputChannel.appendLine('Installing ' + getToolImportPath(tool, goVersion) + ' SUCCEEDED');
if (tool === 'gometalinter') {
// Gometalinter needs to install all the linters it uses.
outputChannel.appendLine('Installing all linters used by gometalinter....');
let gometalinterBinPath = getBinPath('gometalinter');
cp.execFile(gometalinterBinPath, ['--install'], { env: envForTools }, (err, stdout, stderr) => {
if (!err) {
outputChannel.appendLine('Installing all linters used by gometalinter SUCCEEDED.');
resolve([...sofar, null]);
} else {
let failureReason = `Error while running gometalinter --install;; ${stderr}`;
resolve([...sofar, failureReason]);
}
});
} else {
resolve([...sofar, null]);
}
}
};
let closeToolPromise = Promise.resolve(true);
const toolBinPath = getBinPath(tool);
if (path.isAbsolute(toolBinPath) && (tool === 'gocode' || tool === 'gocode-gomod')) {
closeToolPromise = new Promise<boolean>((innerResolve) => {
cp.execFile(toolBinPath, ['close'], {}, (err, stdout, stderr) => {
if (stderr && stderr.indexOf('rpc: can\'t find service Server.') > -1) {
outputChannel.appendLine('Installing gocode aborted as existing process cannot be closed. Please kill the running process for gocode and try again.');
return innerResolve(false);
}
innerResolve(true);
});
});
}
closeToolPromise.then((success) => {
if (!success) {
resolve([...sofar, null]);
return;
}
let args = ['get', '-u', '-v'];
if (tool.endsWith('-gomod')) {
args.push('-d');
}
args.push(getToolImportPath(tool, goVersion));
cp.execFile(goRuntimePath, args, { env: envForTools }, (err, stdout, stderr) => {
if (stderr.indexOf('unexpected directory layout:') > -1) {
outputChannel.appendLine(`Installing ${tool} failed with error "unexpected directory layout". Retrying...`);
cp.execFile(goRuntimePath, args, { env: envForTools }, callback);
} else if (!err && tool.endsWith('-gomod')) {
const outputFile = path.join(toolsGopath, 'bin', process.platform === 'win32' ? `${tool}.exe` : tool);
cp.execFile(goRuntimePath, ['build', '-o', outputFile, getToolImportPath(tool, goVersion)], { env: envForTools }, callback);
} else {
callback(err, stdout, stderr);
}
});
});
}));
}, Promise.resolve([])).then(res => {
outputChannel.appendLine(''); // Blank line for spacing
let failures = res.filter(x => x != null);
if (failures.length === 0) {
if (missing.indexOf('go-langserver') > -1) {
outputChannel.appendLine('Reload VS Code window to use the Go language server');
}
outputChannel.appendLine('All tools successfully installed. You\'re ready to Go :).');
return;
}
outputChannel.appendLine(failures.length + ' tools failed to install.\n');
failures.forEach((failure, index, failures) => {
let reason = failure.split(';;');
outputChannel.appendLine(reason[0] + ':');
outputChannel.appendLine(reason[1]);
});
});
}
export function updateGoPathGoRootFromConfig(): Promise<void> {
let goroot = vscode.workspace.getConfiguration('go', vscode.window.activeTextEditor ? vscode.window.activeTextEditor.document.uri : null)['goroot'];
if (goroot) {
process.env['GOROOT'] = resolvePath(goroot);
}
if (process.env['GOPATH'] && process.env['GOROOT']) {
return Promise.resolve();
}
// If GOPATH is still not set, then use the one from `go env`
let goRuntimePath = getBinPath('go');
if (!goRuntimePath) {
return Promise.reject(new Error('Cannot find "go" binary. Update PATH or GOROOT appropriately'));
}
return new Promise<void>((resolve, reject) => {
cp.execFile(goRuntimePath, ['env', 'GOPATH', 'GOROOT'], (err, stdout, stderr) => {
if (err) {
return reject();
}
let envOutput = stdout.split('\n');
if (!process.env['GOPATH'] && envOutput[0].trim()) {
process.env['GOPATH'] = envOutput[0].trim();
}
if (!process.env['GOROOT'] && envOutput[1] && envOutput[1].trim()) {
process.env['GOROOT'] = envOutput[1].trim();
}
return resolve();
});
});
}
export function offerToInstallTools() {
isVendorSupported();
getGoVersion().then(goVersion => {
getMissingTools(goVersion).then(missing => {
missing = missing.filter(x => importantTools.indexOf(x) > -1);
if (missing.length > 0) {
showGoStatus('Analysis Tools Missing', 'go.promptforinstall', 'Not all Go tools are available on the GOPATH');
vscode.commands.registerCommand('go.promptforinstall', () => {
promptForInstall(missing, goVersion);
});
}
});
});
function promptForInstall(missing: string[], goVersion: SemVersion) {
let installItem = {
title: 'Install',
command() {
hideGoStatus();
installTools(missing, goVersion);
}
};
let showItem = {
title: 'Show',
command() {
outputChannel.clear();
outputChannel.appendLine('Below tools are needed for the basic features of the Go extension.');
missing.forEach(x => outputChannel.appendLine(x));
}
};
vscode.window.showInformationMessage('Some Go analysis tools are missing from your GOPATH. Would you like to install them?', installItem, showItem).then(selection => {
if (selection) {
selection.command();
} else {
hideGoStatus();
}
});
}
}
function getMissingTools(goVersion: SemVersion): Promise<string[]> {
let keys = getTools(goVersion);
return Promise.all<string>(keys.map(tool => new Promise<string>((resolve, reject) => {
let toolPath = getBinPath(tool);
fs.exists(toolPath, exists => {
resolve(exists ? null : tool);
});
}))).then(res => {
return res.filter(x => x != null);
});
}
// If langserver needs to be used, but is not installed, this will prompt user to install and Reload
// If langserver needs to be used, and is installed, this will return true
// Returns false in all other cases
export function checkLanguageServer(): boolean {
let latestGoConfig = vscode.workspace.getConfiguration('go');
if (!latestGoConfig['useLanguageServer']) return false;
if (!allFoldersHaveSameGopath()) {
vscode.window.showInformationMessage('The Go language server is not supported in a multi root set up with different GOPATHs.');
return false;
}
let langServerAvailable = getBinPath('go-langserver') !== 'go-langserver';
if (!langServerAvailable) {
promptForMissingTool('go-langserver');
vscode.window.showInformationMessage('Reload VS Code window after installing the Go language server');
}
return langServerAvailable;
}
function allFoldersHaveSameGopath(): boolean {
if (!vscode.workspace.workspaceFolders || vscode.workspace.workspaceFolders.length <= 1) {
return true;
}
let tempGopath = getCurrentGoPath(vscode.workspace.workspaceFolders[0].uri);
return vscode.workspace.workspaceFolders.find(x => tempGopath !== getCurrentGoPath(x.uri)) ? false : true;
}