]> git.lizzy.rs Git - rust.git/blob - editors/code/src/main.ts
8b0a9d8706e9d903fee897bbeb29f48b0bba60b1
[rust.git] / editors / code / src / main.ts
1 import * as vscode from 'vscode';
2 import * as path from "path";
3 import * as os from "os";
4 import { promises as fs } from "fs";
5
6 import * as commands from './commands';
7 import { activateInlayHints } from './inlay_hints';
8 import { activateStatusDisplay } from './status_display';
9 import { Ctx } from './ctx';
10 import { Config, NIGHTLY_TAG } from './config';
11 import { log, assert, isValidExecutable } from './util';
12 import { PersistentState } from './persistent_state';
13 import { fetchRelease, download } from './net';
14 import { activateTaskProvider } from './tasks';
15
16 let ctx: Ctx | undefined;
17
18 export async function activate(context: vscode.ExtensionContext) {
19     // Register a "dumb" onEnter command for the case where server fails to
20     // start.
21     //
22     // FIXME: refactor command registration code such that commands are
23     // **always** registered, even if the server does not start. Use API like
24     // this perhaps?
25     //
26     // ```TypeScript
27     // registerCommand(
28     //    factory: (Ctx) => ((Ctx) => any),
29     //    fallback: () => any = () => vscode.window.showErrorMessage(
30     //        "rust-analyzer is not available"
31     //    ),
32     // )
33     const defaultOnEnter = vscode.commands.registerCommand(
34         'rust-analyzer.onEnter',
35         () => vscode.commands.executeCommand('default:type', { text: '\n' }),
36     );
37     context.subscriptions.push(defaultOnEnter);
38
39     const config = new Config(context);
40     const state = new PersistentState(context.globalState);
41     const serverPath = await bootstrap(config, state);
42
43     const workspaceFolder = vscode.workspace.workspaceFolders?.[0];
44     if (workspaceFolder === undefined) {
45         const err = "Cannot activate rust-analyzer when no folder is opened";
46         void vscode.window.showErrorMessage(err);
47         throw new Error(err);
48     }
49
50     // Note: we try to start the server before we activate type hints so that it
51     // registers its `onDidChangeDocument` handler before us.
52     //
53     // This a horribly, horribly wrong way to deal with this problem.
54     ctx = await Ctx.create(config, context, serverPath, workspaceFolder.uri.fsPath);
55
56     // Commands which invokes manually via command palette, shortcut, etc.
57
58     // Reloading is inspired by @DanTup maneuver: https://github.com/microsoft/vscode/issues/45774#issuecomment-373423895
59     ctx.registerCommand('reload', _ => async () => {
60         void vscode.window.showInformationMessage('Reloading rust-analyzer...');
61         await deactivate();
62         while (context.subscriptions.length > 0) {
63             try {
64                 context.subscriptions.pop()!.dispose();
65             } catch (err) {
66                 log.error("Dispose error:", err);
67             }
68         }
69         await activate(context).catch(log.error);
70     });
71
72     ctx.registerCommand('analyzerStatus', commands.analyzerStatus);
73     ctx.registerCommand('collectGarbage', commands.collectGarbage);
74     ctx.registerCommand('matchingBrace', commands.matchingBrace);
75     ctx.registerCommand('joinLines', commands.joinLines);
76     ctx.registerCommand('parentModule', commands.parentModule);
77     ctx.registerCommand('syntaxTree', commands.syntaxTree);
78     ctx.registerCommand('expandMacro', commands.expandMacro);
79     ctx.registerCommand('run', commands.run);
80     ctx.registerCommand('debug', commands.debug);
81     ctx.registerCommand('newDebugConfig', commands.newDebugConfig);
82
83     defaultOnEnter.dispose();
84     ctx.registerCommand('onEnter', commands.onEnter);
85
86     ctx.registerCommand('ssr', commands.ssr);
87     ctx.registerCommand('serverVersion', commands.serverVersion);
88
89     // Internal commands which are invoked by the server.
90     ctx.registerCommand('runSingle', commands.runSingle);
91     ctx.registerCommand('debugSingle', commands.debugSingle);
92     ctx.registerCommand('showReferences', commands.showReferences);
93     ctx.registerCommand('applySourceChange', commands.applySourceChange);
94     ctx.registerCommand('applySnippetWorkspaceEdit', commands.applySnippetWorkspaceEditCommand);
95     ctx.registerCommand('selectAndApplySourceChange', commands.selectAndApplySourceChange);
96
97     ctx.pushCleanup(activateTaskProvider(workspaceFolder));
98
99     activateStatusDisplay(ctx);
100
101     activateInlayHints(ctx);
102
103     vscode.workspace.onDidChangeConfiguration(
104         _ => ctx?.client?.sendNotification('workspace/didChangeConfiguration', { settings: "" }),
105         null,
106         ctx.subscriptions,
107     );
108 }
109
110 export async function deactivate() {
111     await ctx?.client.stop();
112     ctx = undefined;
113 }
114
115 async function bootstrap(config: Config, state: PersistentState): Promise<string> {
116     await fs.mkdir(config.globalStoragePath, { recursive: true });
117
118     await bootstrapExtension(config, state);
119     const path = await bootstrapServer(config, state);
120
121     return path;
122 }
123
124 async function bootstrapExtension(config: Config, state: PersistentState): Promise<void> {
125     if (config.package.releaseTag === null) return;
126     if (config.channel === "stable") {
127         if (config.package.releaseTag === NIGHTLY_TAG) {
128             void vscode.window.showWarningMessage(
129                 `You are running a nightly version of rust-analyzer extension. ` +
130                 `To switch to stable, uninstall the extension and re-install it from the marketplace`
131             );
132         }
133         return;
134     };
135
136     const lastCheck = state.lastCheck;
137     const now = Date.now();
138
139     const anHour = 60 * 60 * 1000;
140     const shouldDownloadNightly = state.releaseId === undefined || (now - (lastCheck ?? 0)) > anHour;
141
142     if (!shouldDownloadNightly) return;
143
144     const release = await fetchRelease("nightly").catch((e) => {
145         log.error(e);
146         if (state.releaseId === undefined) { // Show error only for the initial download
147             vscode.window.showErrorMessage(`Failed to download rust-analyzer nightly ${e}`);
148         }
149         return undefined;
150     });
151     if (release === undefined || release.id === state.releaseId) return;
152
153     const userResponse = await vscode.window.showInformationMessage(
154         "New version of rust-analyzer (nightly) is available (requires reload).",
155         "Update"
156     );
157     if (userResponse !== "Update") return;
158
159     const artifact = release.assets.find(artifact => artifact.name === "rust-analyzer.vsix");
160     assert(!!artifact, `Bad release: ${JSON.stringify(release)}`);
161
162     const dest = path.join(config.globalStoragePath, "rust-analyzer.vsix");
163     await download(artifact.browser_download_url, dest, "Downloading rust-analyzer extension");
164
165     await vscode.commands.executeCommand("workbench.extensions.installExtension", vscode.Uri.file(dest));
166     await fs.unlink(dest);
167
168     await state.updateReleaseId(release.id);
169     await state.updateLastCheck(now);
170     await vscode.commands.executeCommand("workbench.action.reloadWindow");
171 }
172
173 async function bootstrapServer(config: Config, state: PersistentState): Promise<string> {
174     const path = await getServer(config, state);
175     if (!path) {
176         throw new Error(
177             "Rust Analyzer Language Server is not available. " +
178             "Please, ensure its [proper installation](https://rust-analyzer.github.io/manual.html#installation)."
179         );
180     }
181
182     log.debug("Using server binary at", path);
183
184     if (!isValidExecutable(path)) {
185         throw new Error(`Failed to execute ${path} --version`);
186     }
187
188     return path;
189 }
190
191 async function getServer(config: Config, state: PersistentState): Promise<string | undefined> {
192     const explicitPath = process.env.__RA_LSP_SERVER_DEBUG ?? config.serverPath;
193     if (explicitPath) {
194         if (explicitPath.startsWith("~/")) {
195             return os.homedir() + explicitPath.slice("~".length);
196         }
197         return explicitPath;
198     };
199     if (config.package.releaseTag === null) return "rust-analyzer";
200
201     let binaryName: string | undefined = undefined;
202     if (process.arch === "x64" || process.arch === "ia32") {
203         if (process.platform === "linux") binaryName = "rust-analyzer-linux";
204         if (process.platform === "darwin") binaryName = "rust-analyzer-mac";
205         if (process.platform === "win32") binaryName = "rust-analyzer-windows.exe";
206     }
207     if (binaryName === undefined) {
208         vscode.window.showErrorMessage(
209             "Unfortunately we don't ship binaries for your platform yet. " +
210             "You need to manually clone rust-analyzer repository and " +
211             "run `cargo xtask install --server` to build the language server from sources. " +
212             "If you feel that your platform should be supported, please create an issue " +
213             "about that [here](https://github.com/rust-analyzer/rust-analyzer/issues) and we " +
214             "will consider it."
215         );
216         return undefined;
217     }
218
219     const dest = path.join(config.globalStoragePath, binaryName);
220     const exists = await fs.stat(dest).then(() => true, () => false);
221     if (!exists) {
222         await state.updateServerVersion(undefined);
223     }
224
225     if (state.serverVersion === config.package.version) return dest;
226
227     if (config.askBeforeDownload) {
228         const userResponse = await vscode.window.showInformationMessage(
229             `Language server version ${config.package.version} for rust-analyzer is not installed.`,
230             "Download now"
231         );
232         if (userResponse !== "Download now") return dest;
233     }
234
235     const release = await fetchRelease(config.package.releaseTag);
236     const artifact = release.assets.find(artifact => artifact.name === binaryName);
237     assert(!!artifact, `Bad release: ${JSON.stringify(release)}`);
238
239     await download(artifact.browser_download_url, dest, "Downloading rust-analyzer server", { mode: 0o755 });
240     await state.updateServerVersion(config.package.version);
241     return dest;
242 }