-
-
Notifications
You must be signed in to change notification settings - Fork 465
/
Copy pathFiles.ts
300 lines (280 loc) · 7.85 KB
/
Files.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
/* --------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* COPIED FROM: https://github.com/microsoft/vscode-languageserver-node/blob/master/server/src/files.ts
* ------------------------------------------------------------------------------------------ */
"use strict";
import {
ChildProcess,
fork,
spawnSync,
SpawnSyncOptionsWithStringEncoding
} from "child_process";
import * as fs from "fs";
import * as path from "path";
function isWindows(): boolean {
return process.platform === "win32";
}
export function resolve(
moduleName: string,
nodePath: string | undefined,
cwd: string | undefined,
tracer: (message: string, verbose?: string) => void
): Promise<string> {
interface Message {
c: string;
s?: boolean;
a?: any;
r?: any;
}
const nodePathKey: string = "NODE_PATH";
const app: string = [
"var p = process;",
"p.on('message',function(m){",
"if(m.c==='e'){",
"p.exit(0);",
"}",
"else if(m.c==='rs'){",
"try{",
"var r=require.resolve(m.a);",
"p.send({c:'r',s:true,r:r});",
"}",
"catch(err){",
"p.send({c:'r',s:false});",
"}",
"}",
"});"
].join("");
// tslint:disable-next-line: no-shadowed-variable
return new Promise<any>((resolve, reject) => {
const env = process.env;
const newEnv = Object.create(null);
Object.keys(env).forEach(key => (newEnv[key] = env[key]));
if (nodePath && fs.existsSync(nodePath) /* see issue 545 */) {
// tslint:disable-next-line: prefer-conditional-expression
if (newEnv[nodePathKey]) {
newEnv[nodePathKey] = nodePath + path.delimiter + newEnv[nodePathKey];
} else {
newEnv[nodePathKey] = nodePath;
}
if (tracer) {
tracer(`NODE_PATH value is: ${newEnv[nodePathKey]}`);
}
}
newEnv.ELECTRON_RUN_AS_NODE = "1";
try {
const cp: ChildProcess = fork("", [], {
cwd,
env: newEnv,
execArgv: ["-e", app]
} as any);
if (cp.pid === void 0) {
reject(
new Error(
`Starting process to resolve node module ${moduleName} failed`
)
);
return;
}
cp.on("error", (error: any) => {
reject(error);
});
// tslint:disable-next-line: no-shadowed-variable
cp.on("message", (message: Message) => {
if (message.c === "r") {
cp.send({ c: "e" });
if (message.s) {
resolve(message.r);
} else {
reject(new Error(`Failed to resolve module: ${moduleName}`));
}
}
});
const message: Message = {
c: "rs",
// tslint:disable-next-line: object-literal-sort-keys
a: moduleName
};
cp.send(message);
} catch (error) {
reject(error);
}
});
}
/**
* Resolve the global npm package path.
* @deprecated Since this depends on the used package manager and their version the best is that servers
* implement this themselves since they know best what kind of package managers to support.
* @param tracer the tracer to use
*/
export function resolveGlobalNodePath(
tracer?: (message: string) => void
): string | undefined {
let npmCommand = "npm";
const options: SpawnSyncOptionsWithStringEncoding = {
encoding: "utf8"
};
if (isWindows()) {
npmCommand = "npm.cmd";
options.shell = true;
}
// tslint:disable-next-line: no-empty
const handler = () => {};
try {
process.on("SIGPIPE", handler);
const stdout = spawnSync(npmCommand, ["config", "get", "prefix"], options)
.stdout;
if (!stdout) {
if (tracer) {
tracer(`'npm config get prefix' didn't return a value.`);
}
return undefined;
}
const prefix = stdout.trim();
if (tracer) {
tracer(`'npm config get prefix' value is: ${prefix}`);
}
if (prefix.length > 0) {
if (isWindows()) {
return path.join(prefix, "node_modules");
} else {
return path.join(prefix, "lib", "node_modules");
}
}
return undefined;
} catch (err) {
return undefined;
} finally {
process.removeListener("SIGPIPE", handler);
}
}
interface YarnJsonFormat {
type: string;
data: string;
}
/*
* Resolve the global yarn package path.
* @deprecated Since this depends on the used package manager and their version the best is that servers
* implement this themselves since they know best what kind of package managers to support.
* @param tracer the tracer to use
*/
export function resolveGlobalYarnPath(
tracer?: (message: string) => void
): string | undefined {
let yarnCommand = "yarn";
const options: SpawnSyncOptionsWithStringEncoding = {
encoding: "utf8"
};
if (isWindows()) {
yarnCommand = "yarn.cmd";
options.shell = true;
}
// tslint:disable-next-line: no-empty
const handler = () => {};
try {
process.on("SIGPIPE", handler);
const results = spawnSync(
yarnCommand,
["global", "dir", "--json"],
options
);
const stdout = results.stdout;
if (!stdout) {
if (tracer) {
tracer(`'yarn global dir' didn't return a value.`);
if (results.stderr) {
tracer(results.stderr);
}
}
return undefined;
}
const lines = stdout.trim().split(/\r?\n/);
for (const line of lines) {
try {
const yarn: YarnJsonFormat = JSON.parse(line);
if (yarn.type === "log") {
return path.join(yarn.data, "node_modules");
}
} catch (e) {
// Do nothing. Ignore the line
}
}
return undefined;
} catch (err) {
return undefined;
} finally {
process.removeListener("SIGPIPE", handler);
}
}
// tslint:disable-next-line: no-namespace
export namespace FileSystem {
// tslint:disable-next-line: variable-name
let _isCaseSensitive: boolean | undefined;
export function isCaseSensitive(): boolean {
if (_isCaseSensitive !== void 0) {
return _isCaseSensitive;
}
if (process.platform === "win32") {
_isCaseSensitive = false;
} else {
// convert current file name to upper case / lower case and check if file exists
// (guards against cases when name is already all uppercase or lowercase)
_isCaseSensitive =
!fs.existsSync(__filename.toUpperCase()) ||
!fs.existsSync(__filename.toLowerCase());
}
return _isCaseSensitive;
}
export function isParent(parent: string, child: string): boolean {
if (isCaseSensitive()) {
return path.normalize(child).indexOf(path.normalize(parent)) === 0;
} else {
return (
path
.normalize(child)
.toLowerCase()
.indexOf(path.normalize(parent).toLowerCase()) === 0
);
}
}
}
export function resolveModulePath(
workspaceRoot: string,
moduleName: string,
nodePath: string,
tracer: (message: string, verbose?: string) => void
): Promise<string> {
if (nodePath) {
if (!path.isAbsolute(nodePath)) {
nodePath = path.join(workspaceRoot, nodePath);
}
return (
resolve(moduleName, nodePath, nodePath, tracer)
.then(value => {
if (FileSystem.isParent(nodePath, value)) {
return value;
} else {
return Promise.reject<string>(
new Error(`Failed to load ${moduleName} from node path location.`)
);
}
})
// tslint:disable-next-line: variable-name
.then<string, string>(undefined, (_error: any) => {
return resolve(
moduleName,
resolveGlobalNodePath(tracer),
workspaceRoot,
tracer
);
})
);
} else {
return resolve(
moduleName,
resolveGlobalNodePath(tracer),
workspaceRoot,
tracer
);
}
}