forked from golang/vscode-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgoImport.ts
211 lines (189 loc) · 7.14 KB
/
goImport.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
/*---------------------------------------------------------
* 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 cp = require('child_process');
import vscode = require('vscode');
import { promptForMissingTool } from './goInstallTools';
import { documentSymbols, GoOutlineImportsOptions } from './goOutline';
import { getImportablePackages } from './goPackages';
import { envPath } from './goPath';
import { sendTelemetryEventForAddImportCmd } from './telemetry';
import { getBinPath, getImportPath, getToolsEnvVars, parseFilePrelude } from './util';
const missingToolMsg = 'Missing tool: ';
export async function listPackages(excludeImportedPkgs: boolean = false): Promise<string[]> {
const importedPkgs =
excludeImportedPkgs && vscode.window.activeTextEditor
? await getImports(vscode.window.activeTextEditor.document)
: [];
const pkgMap = await getImportablePackages(vscode.window.activeTextEditor.document.fileName, true);
const stdLibs: string[] = [];
const nonStdLibs: string[] = [];
pkgMap.forEach((value, key) => {
if (importedPkgs.some((imported) => imported === key)) {
return;
}
if (value.isStd) {
stdLibs.push(key);
} else {
nonStdLibs.push(key);
}
});
return [...stdLibs.sort(), ...nonStdLibs.sort()];
}
/**
* Returns the imported packages in the given file
*
* @param document TextDocument whose imports need to be returned
* @returns Array of imported package paths wrapped in a promise
*/
async function getImports(document: vscode.TextDocument): Promise<string[]> {
const options = {
fileName: document.fileName,
importsOption: GoOutlineImportsOptions.Only,
document
};
const symbols = await documentSymbols(options, null);
if (!symbols || !symbols.length) {
return [];
}
// import names will be of the form "math", so strip the quotes in the beginning and the end
const imports = symbols[0].children
.filter((x: any) => x.kind === vscode.SymbolKind.Namespace)
.map((x: any) => x.name.substr(1, x.name.length - 2));
return imports;
}
async function askUserForImport(): Promise<string | undefined> {
try {
const packages = await listPackages(true);
return vscode.window.showQuickPick(packages);
} catch (err) {
if (typeof err === 'string' && err.startsWith(missingToolMsg)) {
promptForMissingTool(err.substr(missingToolMsg.length));
}
}
}
export function getTextEditForAddImport(arg: string): vscode.TextEdit[] {
// Import name wasn't provided
if (arg === undefined) {
return null;
}
const { imports, pkg } = parseFilePrelude(vscode.window.activeTextEditor.document.getText());
if (imports.some((block) => block.pkgs.some((pkgpath) => pkgpath === arg))) {
return [];
}
const multis = imports.filter((x) => x.kind === 'multi');
const minusCgo = imports.filter((x) => x.kind !== 'pseudo');
if (multis.length > 0) {
// There is a multiple import declaration, add to the last one
const lastImportSection = multis[multis.length - 1];
if (lastImportSection.end === -1) {
// For some reason there was an empty import section like `import ()`
return [vscode.TextEdit.insert(new vscode.Position(lastImportSection.start + 1, 0), `import "${arg}"\n`)];
}
// Add import at the start of the block so that goimports/goreturns can order them correctly
return [vscode.TextEdit.insert(new vscode.Position(lastImportSection.start + 1, 0), '\t"' + arg + '"\n')];
} else if (minusCgo.length > 0) {
// There are some number of single line imports, which can just be collapsed into a block import.
const edits = [];
edits.push(vscode.TextEdit.insert(new vscode.Position(minusCgo[0].start, 0), 'import (\n\t"' + arg + '"\n'));
minusCgo.forEach((element) => {
const currentLine = vscode.window.activeTextEditor.document.lineAt(element.start).text;
const updatedLine = currentLine.replace(/^\s*import\s*/, '\t');
edits.push(
vscode.TextEdit.replace(
new vscode.Range(element.start, 0, element.start, currentLine.length),
updatedLine
)
);
});
edits.push(vscode.TextEdit.insert(new vscode.Position(minusCgo[minusCgo.length - 1].end + 1, 0), ')\n'));
return edits;
} else if (pkg && pkg.start >= 0) {
// There are no import declarations, but there is a package declaration
return [vscode.TextEdit.insert(new vscode.Position(pkg.start + 1, 0), '\nimport (\n\t"' + arg + '"\n)\n')];
} else {
// There are no imports and no package declaration - give up
return [];
}
}
export function addImport(arg: { importPath: string; from: string }) {
const editor = vscode.window.activeTextEditor;
if (!editor) {
vscode.window.showErrorMessage('No active editor found to add imports.');
return;
}
const p = arg && arg.importPath ? Promise.resolve(arg.importPath) : askUserForImport();
p.then((imp) => {
if (!imp) {
return;
}
sendTelemetryEventForAddImportCmd(arg);
const edits = getTextEditForAddImport(imp);
if (edits && edits.length > 0) {
const edit = new vscode.WorkspaceEdit();
edit.set(editor.document.uri, edits);
vscode.workspace.applyEdit(edit);
}
});
}
export function addImportToWorkspace() {
const editor = vscode.window.activeTextEditor;
if (!editor) {
vscode.window.showErrorMessage('No active editor found to determine current package.');
return;
}
const selection = editor.selection;
let importPath = '';
if (!selection.isEmpty) {
let selectedText = editor.document.getText(selection).trim();
if (selectedText.length > 0) {
if (selectedText.indexOf(' ') === -1) {
// Attempt to load a partial import path based on currently selected text
if (!selectedText.startsWith('"')) {
selectedText = '"' + selectedText;
}
if (!selectedText.endsWith('"')) {
selectedText = selectedText + '"';
}
}
importPath = getImportPath(selectedText);
}
}
if (importPath === '') {
// Failing that use the current line
const selectedText = editor.document.lineAt(selection.active.line).text;
importPath = getImportPath(selectedText);
}
if (importPath === '') {
vscode.window.showErrorMessage('No import path to add');
return;
}
const goRuntimePath = getBinPath('go');
if (!goRuntimePath) {
vscode.window.showErrorMessage(
`Failed to run "go list" to find the package as the "go" binary cannot be found in either GOROOT(${process.env['GOROOT']}) or PATH(${envPath})`
);
return;
}
const env = getToolsEnvVars();
cp.execFile(goRuntimePath, ['list', '-f', '{{.Dir}}', importPath], { env }, (err, stdout, stderr) => {
const dirs = (stdout || '').split('\n');
if (!dirs.length || !dirs[0].trim()) {
vscode.window.showErrorMessage(`Could not find package ${importPath}`);
return;
}
const importPathUri = vscode.Uri.file(dirs[0]);
const existingWorkspaceFolder = vscode.workspace.getWorkspaceFolder(importPathUri);
if (existingWorkspaceFolder !== undefined) {
vscode.window.showInformationMessage('Already available under ' + existingWorkspaceFolder.name);
return;
}
vscode.workspace.updateWorkspaceFolders(
vscode.workspace.workspaceFolders ? vscode.workspace.workspaceFolders.length : 0,
null,
{ uri: importPathUri }
);
});
}