-
Notifications
You must be signed in to change notification settings - Fork 797
/
Copy pathpathUtils.ts
277 lines (247 loc) · 8.51 KB
/
pathUtils.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
/*---------------------------------------------------------
* 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';
/**
* This file is loaded by both the extension and debug adapter, so it cannot import 'vscode'
*/
import fs = require('fs');
import os = require('os');
import path = require('path');
import { promisify } from 'util';
import { logVerbose } from '../goLogging';
let binPathCache: { [bin: string]: string } = {};
export const envPath = process.env['PATH'] || (process.platform === 'win32' ? process.env['Path'] : null);
// find the tool's path from the given PATH env var, or null if the tool is not found.
export function getBinPathFromEnvVar(
toolName: string,
envVarValue: string | null | undefined,
appendBinToPath: boolean
): string | null {
toolName = correctBinname(toolName);
if (envVarValue) {
const paths = envVarValue.split(path.delimiter);
for (const p of paths) {
const binpath = path.join(p, appendBinToPath ? 'bin' : '', toolName);
if (executableFileExists(binpath)) {
return binpath;
}
}
}
return null;
}
export function getBinPathWithPreferredGopathGoroot(
toolName: string,
preferredGopaths: string[],
preferredGoroot?: string,
alternateTool?: string,
useCache = true
): string {
const r = getBinPathWithPreferredGopathGorootWithExplanation(
toolName,
preferredGopaths,
preferredGoroot,
alternateTool,
useCache
);
return r.binPath;
}
// Is same as getBinPathWithPreferredGopathGoroot, but returns why the
// returned path was chosen.
export function getBinPathWithPreferredGopathGorootWithExplanation(
toolName: string,
preferredGopaths: string[],
preferredGoroot?: string,
alternateTool?: string,
useCache = true
): { binPath: string; why?: string } {
if (alternateTool && path.isAbsolute(alternateTool) && executableFileExists(alternateTool)) {
binPathCache[toolName] = alternateTool;
return { binPath: alternateTool, why: 'alternateTool' };
}
// FIXIT: this cache needs to be invalidated when go.goroot or go.alternateTool is changed.
if (useCache && binPathCache[toolName]) {
return { binPath: binPathCache[toolName], why: 'cached' };
}
const binname = alternateTool && !path.isAbsolute(alternateTool) ? alternateTool : toolName;
const found = (why: string) => (binname === toolName ? why : 'alternateTool');
const pathFromGoBin = getBinPathFromEnvVar(binname, process.env['GOBIN'], false);
if (pathFromGoBin) {
binPathCache[toolName] = pathFromGoBin;
return { binPath: pathFromGoBin, why: binname === toolName ? 'gobin' : 'alternateTool' };
}
for (const preferred of preferredGopaths) {
if (typeof preferred === 'string') {
// Search in the preferred GOPATH workspace's bin folder
const pathFrompreferredGoPath = getBinPathFromEnvVar(binname, preferred, true);
if (pathFrompreferredGoPath) {
binPathCache[toolName] = pathFrompreferredGoPath;
return { binPath: pathFrompreferredGoPath, why: found('gopath') };
}
}
}
// Check GOROOT (go, gofmt, godoc would be found here)
const pathFromGoRoot = getBinPathFromEnvVar(binname, preferredGoroot || getCurrentGoRoot(), true);
if (pathFromGoRoot) {
binPathCache[toolName] = pathFromGoRoot;
return { binPath: pathFromGoRoot, why: found('goroot') };
}
// Finally search PATH parts
const pathFromPath = getBinPathFromEnvVar(binname, envPath, false);
if (pathFromPath) {
binPathCache[toolName] = pathFromPath;
return { binPath: pathFromPath, why: found('path') };
}
// Check common paths for go
if (toolName === 'go') {
const defaultPathsForGo =
process.platform === 'win32'
? ['C:\\Program Files\\Go\\bin\\go.exe', 'C:\\Program Files (x86)\\Go\\bin\\go.exe']
: ['/usr/local/go/bin/go', '/usr/local/bin/go'];
for (const p of defaultPathsForGo) {
if (executableFileExists(p)) {
binPathCache[toolName] = p;
return { binPath: p, why: 'default' };
}
}
return { binPath: '' };
}
// Else return the binary name directly (this will likely always fail downstream)
return { binPath: toolName };
}
/**
* Returns the goroot path if it exists, otherwise returns an empty string
*/
let currentGoRoot = '';
export function getCurrentGoRoot(): string {
return currentGoRoot || process.env['GOROOT'] || '';
}
export function setCurrentGoRoot(goroot: string) {
logVerbose(`setCurrentGoRoot(${goroot})`);
currentGoRoot = goroot;
}
export function correctBinname(toolName: string) {
if (process.platform === 'win32') {
return toolName + '.exe';
}
return toolName;
}
export function executableFileExists(filePath: string): boolean {
let exists = true;
try {
exists = fs.statSync(filePath).isFile();
if (exists) {
fs.accessSync(filePath, fs.constants.F_OK | fs.constants.X_OK);
}
} catch (e) {
exists = false;
}
return exists;
}
export function fileExists(filePath: string): boolean {
try {
return fs.statSync(filePath).isFile();
} catch (e) {
return false;
}
}
export async function dirExists(p: string): Promise<boolean> {
try {
const stat = promisify(fs.stat);
return (await stat(p)).isDirectory();
} catch (e) {
return false;
}
}
export function clearCacheForTools() {
binPathCache = {};
}
/**
* Exapnds ~ to homedir in non-Windows platform
*/
export function resolveHomeDir(inputPath: string): string {
if (!inputPath || !inputPath.trim()) {
return inputPath;
}
return inputPath.startsWith('~') ? path.join(os.homedir(), inputPath.substr(1)) : inputPath;
}
// Walks up given folder path to return the closest ancestor that has `src` as a child
export function getInferredGopath(folderPath: string): string | undefined {
if (!folderPath) {
return;
}
const dirs = folderPath.toLowerCase().split(path.sep);
// find src directory closest to given folder path
const srcIdx = dirs.lastIndexOf('src');
if (srcIdx > 0) {
return folderPath.substr(0, dirs.slice(0, srcIdx).join(path.sep).length);
}
}
/**
* Returns the workspace in the given Gopath to which given directory path belongs to
* @param gopath string Current Gopath. Can be ; or : separated (as per os) to support multiple paths
* @param currentFileDirPath string
*/
export function getCurrentGoWorkspaceFromGOPATH(gopath: string | undefined, currentFileDirPath: string): string {
if (!gopath) {
return '';
}
const workspaces: string[] = gopath.split(path.delimiter);
let currentWorkspace = '';
currentFileDirPath = fixDriveCasingInWindows(currentFileDirPath);
// Find current workspace by checking if current file is
// under any of the workspaces in $GOPATH
for (const workspace of workspaces) {
const possibleCurrentWorkspace = path.join(workspace, 'src');
if (
currentFileDirPath.startsWith(possibleCurrentWorkspace) ||
(process.platform === 'win32' &&
currentFileDirPath.toLowerCase().startsWith(possibleCurrentWorkspace.toLowerCase()))
) {
// In case of nested workspaces, (example: both /Users/me and /Users/me/src/a/b/c are in $GOPATH)
// both parent & child workspace in the nested workspaces pair can make it inside the above if block
// Therefore, the below check will take longer (more specific to current file) of the two
if (possibleCurrentWorkspace.length > currentWorkspace.length) {
currentWorkspace = currentFileDirPath.substr(0, possibleCurrentWorkspace.length);
}
}
}
return currentWorkspace;
}
// Workaround for issue in https://github.com/Microsoft/vscode/issues/9448#issuecomment-244804026
export function fixDriveCasingInWindows(pathToFix: string): string {
return process.platform === 'win32' && pathToFix
? pathToFix.substr(0, 1).toUpperCase() + pathToFix.substr(1)
: pathToFix;
}
/**
* Returns the tool name from the given path to the tool
* @param toolPath
*/
export function getToolFromToolPath(toolPath: string): string | undefined {
if (!toolPath) {
return;
}
let tool = path.basename(toolPath);
if (process.platform === 'win32' && tool.endsWith('.exe')) {
tool = tool.substr(0, tool.length - 4);
}
return tool;
}
/**
* Returns output with relative filepaths expanded using the provided directory
* @param output
* @param cwd
*/
export function expandFilePathInOutput(output: string, cwd: string): string {
const lines = output.split('\n');
for (let i = 0; i < lines.length; i++) {
const matches = lines[i].match(/\s*(\S+\.go):(\d+):/);
if (matches && matches[1] && !path.isAbsolute(matches[1])) {
lines[i] = lines[i].replace(matches[1], path.join(cwd, matches[1]));
}
}
return lines.join('\n');
}