-
Notifications
You must be signed in to change notification settings - Fork 56
/
server.ts
474 lines (432 loc) · 14.9 KB
/
server.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
import * as fsapi from "fs-extra";
import * as vscode from "vscode";
import { Disposable, l10n, LanguageStatusSeverity, LogOutputChannel } from "vscode";
import { State } from "vscode-languageclient";
import {
LanguageClient,
LanguageClientOptions,
RevealOutputChannelOn,
ServerOptions,
} from "vscode-languageclient/node";
import {
BUNDLED_RUFF_EXECUTABLE,
DEBUG_SERVER_SCRIPT_PATH,
RUFF_SERVER_PREVIEW_ARGS,
RUFF_SERVER_SUBCOMMAND,
RUFF_LSP_SERVER_SCRIPT_PATH,
FIND_RUFF_BINARY_SCRIPT_PATH,
RUFF_BINARY_NAME,
} from "./constants";
import { traceError, traceInfo, traceVerbose, traceWarn } from "./log/logging";
import { getDebuggerPath } from "./python";
import {
getExtensionSettings,
getGlobalSettings,
getUserSetLegacyServerSettings,
getUserSetNativeServerSettings,
getWorkspaceSettings,
ISettings,
} from "./settings";
import {
supportsNativeServer,
versionToString,
VersionInfo,
MINIMUM_NATIVE_SERVER_VERSION,
supportsStableNativeServer,
NATIVE_SERVER_STABLE_VERSION,
} from "./version";
import { updateServerKind, updateStatus } from "./status";
import { getProjectRoot } from "./utilities";
import { isVirtualWorkspace } from "./vscodeapi";
import { exec } from "child_process";
import which = require("which");
export type IInitializationOptions = {
settings: ISettings[];
globalSettings: ISettings;
};
/**
* Function to execute a command and return the stdout.
*/
function executeCommand(command: string): Promise<string> {
return new Promise((resolve, reject) => {
exec(command, (error, stdout, _) => {
if (error) {
reject(error);
} else {
resolve(stdout);
}
});
});
}
/**
* Get the version of the Ruff executable at the given path.
*/
async function getRuffVersion(executable: string): Promise<VersionInfo> {
const stdout = await executeCommand(`${executable} --version`);
const version = stdout.trim().split(" ")[1];
const [major, minor, patch] = version.split(".").map((x) => parseInt(x, 10));
return { major, minor, patch };
}
/**
* Finds the Ruff binary path and returns it.
*
* The strategy is as follows:
* 1. If the 'path' setting is set, check each path in order. The first valid
* path is returned.
* 2. If the 'importStrategy' setting is 'useBundled', return the bundled
* executable path.
* 3. Execute a Python script that tries to locate the binary. This uses either
* the user-provided interpreter or the interpreter provided by the Python
* extension.
* 4. If the Python script doesn't return a path, check the global environment
* which checks the PATH environment variable.
* 5. If all else fails, return the bundled executable path.
*/
async function findRuffBinaryPath(
settings: ISettings,
outputChannel: LogOutputChannel,
): Promise<string> {
if (!vscode.workspace.isTrusted) {
traceInfo(`Workspace is not trusted, using bundled executable: ${BUNDLED_RUFF_EXECUTABLE}`);
return BUNDLED_RUFF_EXECUTABLE;
}
// 'path' setting takes priority over everything.
if (settings.path.length > 0) {
for (const path of settings.path) {
if (await fsapi.pathExists(path)) {
traceInfo(`Using 'path' setting: ${path}`);
return path;
}
}
traceInfo(`Could not find executable in 'path': ${settings.path.join(", ")}`);
}
if (settings.importStrategy === "useBundled") {
traceInfo(`Using bundled executable: ${BUNDLED_RUFF_EXECUTABLE}`);
return BUNDLED_RUFF_EXECUTABLE;
}
// Otherwise, we'll call a Python script that tries to locate a binary.
let ruffBinaryPath: string | undefined;
try {
const stdout = await executeCommand(
`${settings.interpreter[0]} ${FIND_RUFF_BINARY_SCRIPT_PATH}`,
);
ruffBinaryPath = stdout.trim();
} catch (err) {
await vscode.window
.showErrorMessage(
"Unexpected error while trying to find the Ruff binary. See the logs for more details.",
"Show Logs",
)
.then((selection) => {
if (selection) {
outputChannel.show();
}
});
traceError(`Error while trying to find the Ruff binary: ${err}`);
}
if (ruffBinaryPath && ruffBinaryPath.length > 0) {
// First choice: the executable found by the script.
traceInfo(`Using the Ruff binary: ${ruffBinaryPath}`);
return ruffBinaryPath;
}
// Second choice: the executable in the global environment.
const environmentPath = await which(RUFF_BINARY_NAME, { nothrow: true });
if (environmentPath) {
traceInfo(`Using environment executable: ${environmentPath}`);
return environmentPath;
}
// Third choice: bundled executable.
traceInfo(`Falling back to bundled executable: ${BUNDLED_RUFF_EXECUTABLE}`);
return BUNDLED_RUFF_EXECUTABLE;
}
async function createNativeServer(
settings: ISettings,
serverId: string,
serverName: string,
outputChannel: LogOutputChannel,
initializationOptions: IInitializationOptions,
ruffExecutable?: RuffExecutable,
): Promise<LanguageClient> {
if (!ruffExecutable) {
const ruffBinaryPath = await findRuffBinaryPath(settings, outputChannel);
const ruffVersion = await getRuffVersion(ruffBinaryPath);
ruffExecutable = { path: ruffBinaryPath, version: ruffVersion };
}
const { path: ruffBinaryPath, version: ruffVersion } = ruffExecutable;
traceInfo(`Found Ruff ${versionToString(ruffVersion)} at ${ruffBinaryPath}`);
if (!supportsNativeServer(ruffVersion)) {
const message = `Native server requires Ruff ${versionToString(
MINIMUM_NATIVE_SERVER_VERSION,
)}, but found ${versionToString(ruffVersion)} at ${ruffBinaryPath} instead`;
traceError(message);
await vscode.window.showErrorMessage(message);
return Promise.reject();
}
let ruffServerArgs: string[];
if (supportsStableNativeServer(ruffVersion)) {
ruffServerArgs = [RUFF_SERVER_SUBCOMMAND];
} else {
ruffServerArgs = [RUFF_SERVER_SUBCOMMAND, ...RUFF_SERVER_PREVIEW_ARGS];
}
traceInfo(`Server run command: ${[ruffBinaryPath, ...ruffServerArgs].join(" ")}`);
let serverOptions = {
command: ruffBinaryPath,
args: ruffServerArgs,
options: { cwd: settings.cwd, env: process.env },
};
const clientOptions = {
// Register the server for python documents
documentSelector: isVirtualWorkspace()
? [{ language: "python" }]
: [
{ scheme: "file", language: "python" },
{ scheme: "untitled", language: "python" },
{ scheme: "vscode-notebook", language: "python" },
{ scheme: "vscode-notebook-cell", language: "python" },
],
outputChannel: outputChannel,
traceOutputChannel: outputChannel,
revealOutputChannelOn: RevealOutputChannelOn.Never,
initializationOptions,
};
return new LanguageClient(serverId, serverName, serverOptions, clientOptions);
}
async function createLegacyServer(
settings: ISettings,
serverId: string,
serverName: string,
outputChannel: LogOutputChannel,
initializationOptions: IInitializationOptions,
): Promise<LanguageClient> {
const command = settings.interpreter[0];
const cwd = settings.cwd;
// Set debugger path needed for debugging python code.
const newEnv = { ...process.env };
const debuggerPath = await getDebuggerPath();
const isDebugScript = await fsapi.pathExists(DEBUG_SERVER_SCRIPT_PATH);
if (newEnv.USE_DEBUGPY && debuggerPath) {
newEnv.DEBUGPY_PATH = debuggerPath;
} else {
newEnv.USE_DEBUGPY = "False";
}
// Set notification type
newEnv.LS_SHOW_NOTIFICATION = settings.showNotifications;
const args =
newEnv.USE_DEBUGPY === "False" || !isDebugScript
? settings.interpreter.slice(1).concat([RUFF_LSP_SERVER_SCRIPT_PATH])
: settings.interpreter.slice(1).concat([DEBUG_SERVER_SCRIPT_PATH]);
traceInfo(`Server run command: ${[command, ...args].join(" ")}`);
const serverOptions: ServerOptions = {
command,
args,
options: { cwd, env: newEnv },
};
// Options to control the language client
const clientOptions: LanguageClientOptions = {
// Register the server for python documents
documentSelector: isVirtualWorkspace()
? [{ language: "python" }]
: [
{ scheme: "file", language: "python" },
{ scheme: "untitled", language: "python" },
{ scheme: "vscode-notebook", language: "python" },
{ scheme: "vscode-notebook-cell", language: "python" },
],
outputChannel: outputChannel,
traceOutputChannel: outputChannel,
revealOutputChannelOn: RevealOutputChannelOn.Never,
initializationOptions,
};
return new LanguageClient(serverId, serverName, serverOptions, clientOptions);
}
async function showWarningMessageWithLogs(message: string, outputChannel: LogOutputChannel) {
const selection = await vscode.window.showWarningMessage(message, "Show Logs");
if (selection) {
outputChannel.show();
}
}
async function legacyServerSettingsWarning(settings: string[], outputChannel: LogOutputChannel) {
await showWarningMessageWithLogs(
"Unsupported settings used with the native server. Refer to the logs for more details.",
outputChannel,
);
traceWarn(
`The following settings are not supported with the native server: ${JSON.stringify(settings)}`,
);
}
async function nativeServerSettingsWarning(
settings: string[],
outputChannel: LogOutputChannel,
suggestion?: string,
) {
await showWarningMessageWithLogs(
"Unsupported settings used with the legacy server (ruff-lsp). Refer to the logs for more details.",
outputChannel,
);
traceWarn(
`The following settings are not supported with the legacy server (ruff-lsp): ${JSON.stringify(
settings,
)}`,
);
if (suggestion) {
traceWarn(suggestion);
}
}
type RuffExecutable = {
path: string;
version: VersionInfo;
};
async function resolveNativeServerSetting(
settings: ISettings,
workspace: vscode.WorkspaceFolder,
serverId: string,
outputChannel: LogOutputChannel,
): Promise<{ useNativeServer: boolean; executable: RuffExecutable | undefined }> {
let useNativeServer: boolean;
let executable: RuffExecutable | undefined;
switch (settings.nativeServer) {
case "on":
case true:
const legacyServerSettings = getUserSetLegacyServerSettings(serverId, workspace);
if (legacyServerSettings.length > 0) {
await legacyServerSettingsWarning(legacyServerSettings, outputChannel);
}
return { useNativeServer: true, executable };
case "off":
case false:
if (!vscode.workspace.isTrusted) {
const message =
"Cannot use the legacy server (ruff-lsp) in an untrusted workspace; switching to the native server using the bundled executable.";
await vscode.window.showWarningMessage(message);
traceWarn(message);
return { useNativeServer: true, executable };
}
let nativeServerSettings = getUserSetNativeServerSettings(serverId, workspace);
if (nativeServerSettings.length > 0) {
await nativeServerSettingsWarning(nativeServerSettings, outputChannel);
}
return { useNativeServer: false, executable };
case "auto":
if (!vscode.workspace.isTrusted) {
traceInfo(
`Resolved '${serverId}.nativeServer: auto' to use the native server in an untrusted workspace`,
);
return { useNativeServer: true, executable };
}
const ruffBinaryPath = await findRuffBinaryPath(settings, outputChannel);
const ruffVersion = await getRuffVersion(ruffBinaryPath);
if (supportsStableNativeServer(ruffVersion)) {
const legacyServerSettings = getUserSetLegacyServerSettings(serverId, workspace);
if (legacyServerSettings.length > 0) {
traceInfo(`Legacy server settings found: ${JSON.stringify(legacyServerSettings)}`);
useNativeServer = false;
} else {
useNativeServer = true;
}
} else {
traceInfo(
`Stable version of the native server requires Ruff ${versionToString(
NATIVE_SERVER_STABLE_VERSION,
)}, but found ${versionToString(ruffVersion)} at ${ruffBinaryPath} instead`,
);
let nativeServerSettings = getUserSetNativeServerSettings(serverId, workspace);
if (nativeServerSettings.length > 0) {
await nativeServerSettingsWarning(
nativeServerSettings,
outputChannel,
"Please remove these settings or set 'nativeServer' to 'on' to use the native server",
);
}
useNativeServer = false;
}
traceInfo(
`Resolved '${serverId}.nativeServer: auto' to use the ${
useNativeServer ? "native" : "legacy (ruff-lsp)"
} server`,
);
return { useNativeServer, executable: { path: ruffBinaryPath, version: ruffVersion } };
}
}
async function createServer(
settings: ISettings,
projectRoot: vscode.WorkspaceFolder,
serverId: string,
serverName: string,
outputChannel: LogOutputChannel,
initializationOptions: IInitializationOptions,
): Promise<LanguageClient> {
const { useNativeServer, executable } = await resolveNativeServerSetting(
settings,
projectRoot,
serverId,
outputChannel,
);
updateServerKind(useNativeServer);
if (useNativeServer) {
return createNativeServer(
settings,
serverId,
serverName,
outputChannel,
initializationOptions,
executable,
);
} else {
return createLegacyServer(settings, serverId, serverName, outputChannel, initializationOptions);
}
}
let _disposables: Disposable[] = [];
export async function restartServer(
serverId: string,
serverName: string,
outputChannel: LogOutputChannel,
lsClient?: LanguageClient,
): Promise<LanguageClient | undefined> {
if (lsClient) {
traceInfo(`Server: Stop requested`);
await lsClient.stop();
_disposables.forEach((d) => d.dispose());
_disposables = [];
}
updateStatus(undefined, LanguageStatusSeverity.Information, true);
const projectRoot = await getProjectRoot();
const workspaceSettings = await getWorkspaceSettings(serverId, projectRoot);
const extensionSettings = await getExtensionSettings(serverId);
const globalSettings = await getGlobalSettings(serverId);
let newLSClient = await createServer(
workspaceSettings,
projectRoot,
serverId,
serverName,
outputChannel,
{
settings: extensionSettings,
globalSettings: globalSettings,
},
);
traceInfo(`Server: Start requested.`);
_disposables.push(
newLSClient.onDidChangeState((e) => {
switch (e.newState) {
case State.Stopped:
traceVerbose(`Server State: Stopped`);
break;
case State.Starting:
traceVerbose(`Server State: Starting`);
break;
case State.Running:
traceVerbose(`Server State: Running`);
updateStatus(undefined, LanguageStatusSeverity.Information, false);
break;
}
}),
);
try {
await newLSClient.start();
} catch (ex) {
updateStatus(l10n.t("Server failed to start."), LanguageStatusSeverity.Error);
traceError(`Server: Start failed: ${ex}`);
return undefined;
}
return newLSClient;
}