/
client.ts
397 lines (340 loc) · 11.8 KB
/
client.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
import path from "path";
import { performance as Perf } from "perf_hooks";
import * as vscode from "vscode";
import {
LanguageClientOptions,
LanguageClient,
Executable,
RevealOutputChannelOn,
CodeLens,
Range,
ExecutableOptions,
ServerOptions,
MessageSignature,
} from "vscode-languageclient/node";
import { LSP_NAME, ClientInterface } from "./common";
import { Telemetry, RequestEvent } from "./telemetry";
import { Ruby } from "./ruby";
import { WorkspaceChannel } from "./workspaceChannel";
type EnabledFeatures = Record<string, boolean>;
// Get the executables to start the server based on the user's configuration
function getLspExecutables(
workspaceFolder: vscode.WorkspaceFolder,
env: NodeJS.ProcessEnv,
): ServerOptions {
let run: Executable;
let debug: Executable;
const config = vscode.workspace.getConfiguration("rubyLsp");
const branch: string = config.get("branch")!;
const customBundleGemfile: string = config.get("bundleGemfile")!;
const useBundlerCompose: boolean = config.get("useBundlerCompose")!;
const bypassTypechecker: boolean = config.get("bypassTypechecker")!;
const executableOptions: ExecutableOptions = {
cwd: workspaceFolder.uri.fsPath,
env: bypassTypechecker
? { ...env, RUBY_LSP_BYPASS_TYPECHECKER: "true" }
: env,
shell: true,
};
// If there's a user defined custom bundle, we run the LSP with `bundle exec` and just trust the user configured
// their bundle. Otherwise, we run the global install of the LSP and use our custom bundle logic in the server
if (customBundleGemfile.length > 0) {
run = {
command: "bundle",
args: ["exec", "ruby-lsp"],
options: executableOptions,
};
debug = {
command: "bundle",
args: ["exec", "ruby-lsp", "--debug"],
options: executableOptions,
};
} else if (useBundlerCompose) {
run = {
command: "bundle",
args: ["compose", "gem", "ruby-lsp"],
options: executableOptions,
};
debug = {
command: "bundle",
args: ["compose", "gem", "ruby-lsp", "--", "--debug"],
options: executableOptions,
};
} else {
const argsWithBranch = branch.length > 0 ? ["--branch", branch] : [];
run = {
command: "ruby-lsp",
args: argsWithBranch,
options: executableOptions,
};
debug = {
command: "ruby-lsp",
args: argsWithBranch.concat(["--debug"]),
options: executableOptions,
};
}
return { run, debug };
}
function collectClientOptions(
configuration: vscode.WorkspaceConfiguration,
workspaceFolder: vscode.WorkspaceFolder,
outputChannel: WorkspaceChannel,
): LanguageClientOptions {
const pullOn: "change" | "save" | "both" =
configuration.get("pullDiagnosticsOn")!;
const diagnosticPullOptions = {
onChange: pullOn === "change" || pullOn === "both",
onSave: pullOn === "save" || pullOn === "both",
};
const features: EnabledFeatures = configuration.get("enabledFeatures")!;
const enabledFeatures = Object.keys(features).filter((key) => features[key]);
return {
documentSelector: [{ language: "ruby" }],
workspaceFolder,
diagnosticCollectionName: LSP_NAME,
outputChannel,
revealOutputChannelOn: RevealOutputChannelOn.Never,
diagnosticPullOptions,
initializationOptions: {
enabledFeatures,
experimentalFeaturesEnabled: configuration.get(
"enableExperimentalFeatures",
),
featuresConfiguration: configuration.get("featuresConfiguration"),
formatter: configuration.get("formatter"),
linters: configuration.get("linters"),
},
};
}
export default class Client extends LanguageClient implements ClientInterface {
public readonly ruby: Ruby;
public serverVersion?: string;
private readonly workingDirectory: string;
private readonly telemetry: Telemetry;
private readonly createTestItems: (response: CodeLens[]) => void;
private readonly baseFolder;
private requestId = 0;
#context: vscode.ExtensionContext;
#formatter: string;
constructor(
context: vscode.ExtensionContext,
telemetry: Telemetry,
ruby: Ruby,
createTestItems: (response: CodeLens[]) => void,
workspaceFolder: vscode.WorkspaceFolder,
outputChannel: WorkspaceChannel,
) {
super(
LSP_NAME,
getLspExecutables(workspaceFolder, ruby.env),
collectClientOptions(
vscode.workspace.getConfiguration("rubyLsp"),
workspaceFolder,
outputChannel,
),
);
// Middleware are part of client options, but because they must reference `this`, we cannot make it a part of the
// `super` call (TypeScript does not allow accessing `this` before invoking `super`)
this.registerMiddleware();
this.workingDirectory = workspaceFolder.uri.fsPath;
this.baseFolder = path.basename(this.workingDirectory);
this.telemetry = telemetry;
this.createTestItems = createTestItems;
this.#context = context;
this.ruby = ruby;
this.#formatter = "";
}
override async start() {
await super.start();
this.#formatter = this.initializeResult?.formatter;
this.serverVersion = this.initializeResult?.serverInfo?.version;
}
get formatter(): string {
return this.#formatter;
}
get context(): vscode.ExtensionContext {
return this.#context;
}
private set context(context: vscode.ExtensionContext) {
this.#context = context;
}
async sendShowSyntaxTreeRequest(
uri: vscode.Uri,
range?: Range,
): Promise<{ ast: string } | null> {
return this.sendRequest("rubyLsp/textDocument/showSyntaxTree", {
textDocument: { uri: uri.toString() },
range,
});
}
private async benchmarkMiddleware<T>(
type: string | MessageSignature,
params: any,
runRequest: () => Promise<T>,
): Promise<T> {
// Because of the custom bundle logic in the server, we can only fetch the server version after launching it. That
// means some requests may be received before the computed the version. For those, we cannot send telemetry
if (this.serverVersion === undefined) {
return runRequest();
}
const request = typeof type === "string" ? type : type.method;
// The first few requests are not representative for telemetry. Their response time is much higher than the rest
// because they are inflate by the time we spend indexing and by regular "warming up" of the server (like
// autoloading constants or running signature blocks).
if (this.requestId < 50) {
this.requestId++;
return runRequest();
}
const telemetryData: RequestEvent = {
request,
rubyVersion: this.ruby.rubyVersion!,
yjitEnabled: this.ruby.yjitEnabled!,
lspVersion: this.serverVersion,
requestTime: 0,
};
// If there are parameters in the request, include those
if (params) {
const castParam = { ...params } as { textDocument?: { uri: string } };
if ("textDocument" in castParam) {
const uri = castParam.textDocument?.uri.replace(
// eslint-disable-next-line no-process-env
process.env.HOME!,
"~",
);
delete castParam.textDocument;
telemetryData.uri = uri;
}
telemetryData.params = JSON.stringify(castParam);
}
let result: T | undefined;
let errorResult;
const benchmarkId = this.requestId++;
// Execute the request measuring the time it takes to receive the response
Perf.mark(`${benchmarkId}.start`);
try {
result = await runRequest();
} catch (error: any) {
// If any errors occurred in the request, we'll receive these from the LSP server
telemetryData.errorClass = error.data.errorClass;
telemetryData.errorMessage = error.data.errorMessage;
telemetryData.backtrace = error.data.backtrace;
errorResult = error;
}
Perf.mark(`${benchmarkId}.end`);
// Insert benchmarked response time into telemetry data
const bench = Perf.measure(
"benchmarks",
`${benchmarkId}.start`,
`${benchmarkId}.end`,
);
telemetryData.requestTime = bench.duration;
await this.telemetry.sendEvent(telemetryData);
// If there has been an error, we must throw it again. Otherwise we can return the result
if (errorResult) {
if (
this.baseFolder === "ruby-lsp" ||
this.baseFolder === "ruby-lsp-rails"
) {
await vscode.window.showErrorMessage(
`Ruby LSP error ${errorResult.data.errorClass}: ${errorResult.data.errorMessage}\n\n
${errorResult.data.backtrace}`,
);
}
throw errorResult;
}
return result!;
}
// Register the middleware in the client options
private registerMiddleware() {
this.clientOptions.middleware = {
provideCodeLenses: async (document, token, next) => {
const response = await next(document, token);
if (response) {
const testLenses = response.filter(
(codeLens) => (codeLens as CodeLens).data.type === "test",
) as CodeLens[];
if (testLenses.length) {
this.createTestItems(testLenses);
}
}
return response;
},
provideOnTypeFormattingEdits: async (
document,
position,
ch,
options,
token,
_next,
) => {
const response: vscode.TextEdit[] | null = await this.sendRequest(
"textDocument/onTypeFormatting",
{
textDocument: { uri: document.uri.toString() },
position,
ch,
options,
},
token,
);
if (!response) {
return null;
}
// Find the $0 anchor to move the cursor
const cursorPosition = response.find((edit) => edit.newText === "$0");
if (!cursorPosition) {
return response;
}
// Remove the edit including the $0 anchor
response.splice(response.indexOf(cursorPosition), 1);
const workspaceEdit = new vscode.WorkspaceEdit();
workspaceEdit.set(document.uri, response);
const editor = vscode.window.activeTextEditor!;
// This should happen before applying the edits, otherwise the cursor will be moved to the wrong position
const existingText = editor.document.lineAt(
cursorPosition.range.start.line,
).text;
await vscode.workspace.applyEdit(workspaceEdit);
const indentChar = vscode.window.activeTextEditor?.options.insertSpaces
? " "
: "\t";
// If the line is not empty, we don't want to indent the cursor
let indentationLength = 0;
// If the line is empty or only contains whitespace, we want to indent the cursor to the requested position
if (/^\s*$/.exec(existingText)) {
indentationLength = cursorPosition.range.end.character;
}
const indentation = indentChar.repeat(indentationLength);
await vscode.window.activeTextEditor!.insertSnippet(
new vscode.SnippetString(`${indentation}${cursorPosition.newText}`),
new vscode.Selection(
cursorPosition.range.start,
cursorPosition.range.end,
),
);
return null;
},
sendRequest: async <TP, T>(
type: string | MessageSignature,
param: TP | undefined,
token: vscode.CancellationToken,
next: (
type: string | MessageSignature,
param?: TP,
token?: vscode.CancellationToken,
) => Promise<T>,
) => {
return this.benchmarkMiddleware(type, param, () =>
next(type, param, token),
);
},
sendNotification: async <TR>(
type: string | MessageSignature,
next: (type: string | MessageSignature, params?: TR) => Promise<void>,
params: TR,
) => {
return this.benchmarkMiddleware(type, params, () => next(type, params));
},
};
}
}