-
Notifications
You must be signed in to change notification settings - Fork 172
/
rubyLsp.ts
505 lines (439 loc) · 17.4 KB
/
rubyLsp.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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
import * as vscode from "vscode";
import { Range } from "vscode-languageclient/node";
import { Telemetry } from "./telemetry";
import DocumentProvider from "./documentProvider";
import { Workspace } from "./workspace";
import { Command, STATUS_EMITTER } from "./common";
import { ManagerIdentifier, ManagerConfiguration } from "./ruby";
import { StatusItems } from "./status";
import { TestController } from "./testController";
import { Debugger } from "./debugger";
import { DependenciesTree } from "./dependenciesTree";
// The RubyLsp class represents an instance of the entire extension. This should only be instantiated once at the
// activation event. One instance of this class controls all of the existing workspaces, telemetry and handles all
// commands
export class RubyLsp {
private readonly workspaces: Map<string, Workspace> = new Map();
private readonly telemetry: Telemetry;
private readonly context: vscode.ExtensionContext;
private readonly statusItems: StatusItems;
private readonly testController: TestController;
private readonly debug: Debugger;
constructor(context: vscode.ExtensionContext) {
this.context = context;
this.telemetry = new Telemetry(context);
this.testController = new TestController(
context,
this.telemetry,
this.currentActiveWorkspace.bind(this),
);
this.debug = new Debugger(context, this.workspaceResolver.bind(this));
this.registerCommands(context);
this.statusItems = new StatusItems();
const dependenciesTree = new DependenciesTree();
context.subscriptions.push(this.statusItems, this.debug, dependenciesTree);
// Switch the status items based on which workspace is currently active
vscode.window.onDidChangeActiveTextEditor((editor) => {
STATUS_EMITTER.fire(this.currentActiveWorkspace(editor));
});
vscode.workspace.onDidChangeWorkspaceFolders(async (event) => {
// Stop the language server and dispose all removed workspaces
for (const workspaceFolder of event.removed) {
const workspace = this.getWorkspace(workspaceFolder.uri);
if (workspace) {
await workspace.stop();
await workspace.dispose();
this.workspaces.delete(workspaceFolder.uri.toString());
}
}
});
// Lazily activate workspaces that do not contain a lockfile
vscode.workspace.onDidOpenTextDocument(async (document) => {
if (document.languageId !== "ruby") {
return;
}
const workspaceFolder = vscode.workspace.getWorkspaceFolder(document.uri);
if (!workspaceFolder) {
return;
}
const workspace = this.getWorkspace(workspaceFolder.uri);
// If the workspace entry doesn't exist, then we haven't activated the workspace yet
if (!workspace) {
await this.activateWorkspace(workspaceFolder, false);
}
});
}
// Activate the extension. This method should perform all actions necessary to start the extension, such as booting
// all language servers for each existing workspace
async activate() {
await vscode.commands.executeCommand("testing.clearTestResults");
await this.telemetry.sendConfigurationEvents();
const firstWorkspace = vscode.workspace.workspaceFolders?.[0];
// We only activate the first workspace eagerly to avoid running into performance and memory issues. Having too many
// workspaces spawning the Ruby LSP server and indexing can grind the editor to a halt. All other workspaces are
// activated lazily once a Ruby document is opened inside of it through the `onDidOpenTextDocument` event
if (firstWorkspace) {
await this.activateWorkspace(firstWorkspace, true);
}
this.context.subscriptions.push(
vscode.workspace.registerTextDocumentContentProvider(
"ruby-lsp",
new DocumentProvider(),
),
);
STATUS_EMITTER.fire(this.currentActiveWorkspace());
}
// Deactivate the extension, which should stop all language servers. Notice that this just stops anything that is
// running, but doesn't dispose of existing instances
async deactivate() {
for (const workspace of this.workspaces.values()) {
await workspace.stop();
}
}
private async activateWorkspace(
workspaceFolder: vscode.WorkspaceFolder,
eager: boolean,
) {
const workspaceDir = workspaceFolder.uri.fsPath;
const customBundleGemfile: string = vscode.workspace
.getConfiguration("rubyLsp")
.get("bundleGemfile")!;
const lockfileExists = await this.lockfileExists(workspaceFolder.uri);
// When eagerly activating workspaces, we skip the ones that do not have a lockfile since they may not be a Ruby
// workspace. Those cases are activated lazily below
if (eager && !lockfileExists) {
return;
}
// If no lockfile exists and we're activating lazily (if the user opened a Ruby file inside a workspace we hadn't
// activated before), then we start the language server, but we warn the user that they may be missing multi-root
// workspace configuration
if (
customBundleGemfile.length === 0 &&
!lockfileExists &&
!this.context.globalState.get("rubyLsp.disableMultirootLockfileWarning")
) {
const answer = await vscode.window.showWarningMessage(
`Activating the Ruby LSP in ${workspaceDir}, but no lockfile was found. Are you using a monorepo setup?`,
"See the multi-root workspace docs",
"Don't show again",
);
if (answer === "See the multi-root workspace docs") {
await vscode.env.openExternal(
vscode.Uri.parse(
"https://github.com/Shopify/ruby-lsp/blob/main/vscode/README.md?tab=readme-ov-file#multi-root-workspaces",
),
);
}
if (answer === "Don't show again") {
await this.context.globalState.update(
"rubyLsp.disableMultirootLockfileWarning",
true,
);
}
}
const workspace = new Workspace(
this.context,
workspaceFolder,
this.telemetry,
this.testController.createTestItems.bind(this.testController),
);
this.workspaces.set(workspaceFolder.uri.toString(), workspace);
await workspace.start();
this.context.subscriptions.push(workspace);
// If we successfully activated a workspace, then we can start showing the dependencies tree view. This is necessary
// so that we can avoid showing it on non Ruby projects
await vscode.commands.executeCommand(
"setContext",
"rubyLsp.activated",
true,
);
await this.showFormatOnSaveModeWarning(workspace);
}
// Registers all extension commands. Commands can only be registered once, so this happens in the constructor. For
// creating multiple instances in tests, the `RubyLsp` object should be disposed of after each test to prevent double
// command register errors
private registerCommands(context: vscode.ExtensionContext) {
context.subscriptions.push(
vscode.commands.registerCommand(Command.Update, async () => {
const workspace = await this.showWorkspacePick();
await workspace?.installOrUpdateServer();
}),
vscode.commands.registerCommand(Command.Start, async () => {
const workspace = await this.showWorkspacePick();
await workspace?.start();
}),
vscode.commands.registerCommand(Command.Restart, async () => {
const workspace = await this.showWorkspacePick();
await workspace?.restart();
}),
vscode.commands.registerCommand(Command.Stop, async () => {
const workspace = await this.showWorkspacePick();
await workspace?.stop();
}),
vscode.commands.registerCommand(
Command.ShowSyntaxTree,
this.showSyntaxTree.bind(this),
),
vscode.commands.registerCommand(Command.FormatterHelp, () => {
return vscode.env.openExternal(
vscode.Uri.parse(
"https://github.com/Shopify/ruby-lsp/blob/main/vscode/README.md#formatting",
),
);
}),
vscode.commands.registerCommand(Command.ToggleFeatures, async () => {
// Extract feature descriptions from our package.json
const enabledFeaturesProperties =
vscode.extensions.getExtension("Shopify.ruby-lsp")!.packageJSON
.contributes.configuration.properties["rubyLsp.enabledFeatures"]
.properties;
const descriptions: Record<string, string> = {};
Object.entries(enabledFeaturesProperties).forEach(
([key, value]: [string, any]) => {
descriptions[key] = value.description;
},
);
const configuration = vscode.workspace.getConfiguration("rubyLsp");
const features: Record<string, boolean> =
configuration.get("enabledFeatures")!;
const allFeatures = Object.keys(features);
const options: vscode.QuickPickItem[] = allFeatures.map((label) => {
return {
label,
picked: features[label],
description: descriptions[label],
};
});
const toggledFeatures = await vscode.window.showQuickPick(options, {
canPickMany: true,
placeHolder: "Select the features you would like to enable",
});
if (toggledFeatures !== undefined) {
// The `picked` property is only used to determine if the checkbox is checked initially. When we receive the
// response back from the QuickPick, we need to use inclusion to check if the feature was selected
allFeatures.forEach((feature) => {
features[feature] = toggledFeatures.some(
(selected) => selected.label === feature,
);
});
await vscode.workspace
.getConfiguration("rubyLsp")
.update("enabledFeatures", features, true, true);
}
}),
vscode.commands.registerCommand(
Command.ToggleExperimentalFeatures,
async () => {
const lspConfig = vscode.workspace.getConfiguration("rubyLsp");
const experimentalFeaturesEnabled = lspConfig.get(
"enableExperimentalFeatures",
);
await lspConfig.update(
"enableExperimentalFeatures",
!experimentalFeaturesEnabled,
true,
true,
);
STATUS_EMITTER.fire(this.currentActiveWorkspace());
},
),
vscode.commands.registerCommand(
Command.ServerOptions,
async (options: [{ label: string; description: string }]) => {
const result = await vscode.window.showQuickPick(options, {
placeHolder: "Select server action",
});
if (result !== undefined)
await vscode.commands.executeCommand(result.description);
},
),
vscode.commands.registerCommand(
Command.SelectVersionManager,
async () => {
const configuration = vscode.workspace.getConfiguration("rubyLsp");
const managerConfig =
configuration.get<ManagerConfiguration>("rubyVersionManager")!;
const options = Object.values(ManagerIdentifier);
const manager = (await vscode.window.showQuickPick(options, {
placeHolder: `Current: ${managerConfig.identifier}`,
})) as ManagerIdentifier | undefined;
if (manager !== undefined) {
managerConfig.identifier = manager;
await configuration.update(
"rubyVersionManager",
managerConfig,
true,
);
}
},
),
vscode.commands.registerCommand(
Command.RunTest,
(_path, name, _command) => {
return this.testController.runOnClick(name);
},
),
vscode.commands.registerCommand(
Command.RunTestInTerminal,
this.testController.runTestInTerminal.bind(this.testController),
),
vscode.commands.registerCommand(
Command.DebugTest,
this.testController.debugTest.bind(this.testController),
),
);
}
// Get the current active workspace based on which file is opened in the editor
private currentActiveWorkspace(
activeEditor = vscode.window.activeTextEditor,
): Workspace | undefined {
let workspaceFolder: vscode.WorkspaceFolder | undefined;
if (activeEditor) {
workspaceFolder = vscode.workspace.getWorkspaceFolder(
activeEditor.document.uri,
);
} else {
// If there's no active editor, we search based on the current workspace name
workspaceFolder = vscode.workspace.workspaceFolders?.find(
(folder) => folder.name === vscode.workspace.name,
);
}
if (!workspaceFolder) {
return;
}
return this.getWorkspace(workspaceFolder.uri);
}
private getWorkspace(uri: vscode.Uri): Workspace | undefined {
return this.workspaces.get(uri.toString());
}
private workspaceResolver(
uri: vscode.Uri | undefined,
): Workspace | undefined {
// If no URI is passed, we try to figured out what the active workspace is
if (!uri) {
return this.currentActiveWorkspace();
}
// If a workspace is found for that URI, then we return that one
const workspace = this.workspaces.get(uri.toString());
if (workspace) {
return workspace;
}
// Otherwise, if there's a URI, but we can't find a workspace for it, we fallback to trying to figure out what the
// active workspace is. This situation may happen if we receive a workspace folder URI that is not the actual
// workspace where the Ruby application exists. For example, if you have a monorepo with client and server
// directories and the `launch.json` file is in the top level directory, then we may receive the URI for the top
// level, but the actual workspace is the server directory
return this.currentActiveWorkspace();
}
// Displays a quick pick to select which workspace to perform an action on. For example, if multiple workspaces exist,
// then we need to know which workspace to restart the language server on
private async showWorkspacePick(): Promise<Workspace | undefined> {
if (this.workspaces.size === 1) {
return this.workspaces.values().next().value;
}
const workspaceFolder = await vscode.window.showWorkspaceFolderPick();
if (!workspaceFolder) {
return;
}
return this.getWorkspace(workspaceFolder.uri);
}
// Show syntax tree command
private async showSyntaxTree() {
const activeEditor = vscode.window.activeTextEditor;
if (activeEditor) {
const document = activeEditor.document;
if (document.languageId !== "ruby") {
await vscode.window.showErrorMessage(
"Show syntax tree: not a Ruby file",
);
return;
}
const workspaceFolder = vscode.workspace.getWorkspaceFolder(document.uri);
if (!workspaceFolder) {
return;
}
const workspace = this.getWorkspace(workspaceFolder.uri);
const selection = activeEditor.selection;
let range: Range | undefined;
// Anchor is the first point and active is the last point in the selection. If both are the same, nothing is
// selected
if (!selection.active.isEqual(selection.anchor)) {
// If you start selecting from below and go up, then the selection is reverted
if (selection.isReversed) {
range = Range.create(
selection.active.line,
selection.active.character,
selection.anchor.line,
selection.anchor.character,
);
} else {
range = Range.create(
selection.anchor.line,
selection.anchor.character,
selection.active.line,
selection.active.character,
);
}
}
const response: { ast: string } | null | undefined =
await workspace?.lspClient?.sendShowSyntaxTreeRequest(
document.uri,
range,
);
if (response) {
const document = await vscode.workspace.openTextDocument(
vscode.Uri.from({
scheme: "ruby-lsp",
path: "show-syntax-tree",
query: response.ast,
}),
);
await vscode.window.showTextDocument(document, {
viewColumn: vscode.ViewColumn.Beside,
preserveFocus: true,
});
}
}
}
private async showFormatOnSaveModeWarning(workspace: Workspace) {
const setting = vscode.workspace.getConfiguration("editor", {
languageId: "ruby",
});
const value: string = setting.get("formatOnSaveMode")!;
if (value === "file") {
return;
}
const answer = await vscode.window.showWarningMessage(
`The "editor.formatOnSaveMode" setting is set to ${value} in workspace ${workspace.workspaceFolder.name}, which
is currently unsupported by the Ruby LSP. If you'd like to have formatting enabled, please set it to 'file'`,
"Change setting to 'file'",
"Use without formatting",
);
if (answer === "Change setting to 'file'") {
await setting.update(
"formatOnSaveMode",
"file",
vscode.ConfigurationTarget.Global,
);
}
}
private async lockfileExists(workspaceUri: vscode.Uri) {
try {
await vscode.workspace.fs.stat(
vscode.Uri.joinPath(workspaceUri, "Gemfile.lock"),
);
return true;
} catch (error: any) {
// Gemfile.lock doesn't exist, try the next
}
try {
await vscode.workspace.fs.stat(
vscode.Uri.joinPath(workspaceUri, "gems.locked"),
);
return true;
} catch (error: any) {
// gems.locked doesn't exist
}
return false;
}
}