]> git.lizzy.rs Git - rust.git/blob - editors/code/src/main.ts
Add basic task support
[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 { activateHighlighting } from './highlighting';
11 import { Config, NIGHTLY_TAG } from './config';
12 import { log, assert } from './util';
13 import { PersistentState } from './persistent_state';
14 import { fetchRelease, download } from './net';
15 import { spawnSync } from 'child_process';
16 import { activateTaskProvider } from './tasks';
17
18 let ctx: Ctx | undefined;
19
20 export async function activate(context: vscode.ExtensionContext) {
21     // Register a "dumb" onEnter command for the case where server fails to
22     // start.
23     //
24     // FIXME: refactor command registration code such that commands are
25     // **always** registered, even if the server does not start. Use API like
26     // this perhaps?
27     //
28     // ```TypeScript
29     // registerCommand(
30     //    factory: (Ctx) => ((Ctx) => any),
31     //    fallback: () => any = () => vscode.window.showErrorMessage(
32     //        "rust-analyzer is not available"
33     //    ),
34     // )
35     const defaultOnEnter = vscode.commands.registerCommand(
36         'rust-analyzer.onEnter',
37         () => vscode.commands.executeCommand('default:type', { text: '\n' }),
38     );
39     context.subscriptions.push(defaultOnEnter);
40
41     const config = new Config(context);
42     const state = new PersistentState(context.globalState);
43     const serverPath = await bootstrap(config, state);
44
45     const workspaceFolder = vscode.workspace.workspaceFolders?.[0] ?? null;
46
47     // Note: we try to start the server before we activate type hints so that it
48     // registers its `onDidChangeDocument` handler before us.
49     //
50     // This a horribly, horribly wrong way to deal with this problem.
51     ctx = await Ctx.create(config, context, serverPath, workspaceFolder);
52
53     // Commands which invokes manually via command palette, shortcut, etc.
54
55     // Reloading is inspired by @DanTup maneuver: https://github.com/microsoft/vscode/issues/45774#issuecomment-373423895
56     ctx.registerCommand('reload', _ => async () => {
57         void vscode.window.showInformationMessage('Reloading rust-analyzer...');
58         await deactivate();
59         while (context.subscriptions.length > 0) {
60             try {
61                 context.subscriptions.pop()!.dispose();
62             } catch (err) {
63                 log.error("Dispose error:", err);
64             }
65         }
66         await activate(context).catch(log.error);
67     });
68
69     ctx.registerCommand('analyzerStatus', commands.analyzerStatus);
70     ctx.registerCommand('collectGarbage', commands.collectGarbage);
71     ctx.registerCommand('matchingBrace', commands.matchingBrace);
72     ctx.registerCommand('joinLines', commands.joinLines);
73     ctx.registerCommand('parentModule', commands.parentModule);
74     ctx.registerCommand('syntaxTree', commands.syntaxTree);
75     ctx.registerCommand('expandMacro', commands.expandMacro);
76     ctx.registerCommand('run', commands.run);
77
78     defaultOnEnter.dispose();
79     ctx.registerCommand('onEnter', commands.onEnter);
80
81     ctx.registerCommand('ssr', commands.ssr);
82     ctx.registerCommand('serverVersion', commands.serverVersion);
83
84     // Internal commands which are invoked by the server.
85     ctx.registerCommand('runSingle', commands.runSingle);
86     ctx.registerCommand('debugSingle', commands.debugSingle);
87     ctx.registerCommand('showReferences', commands.showReferences);
88     ctx.registerCommand('applySourceChange', commands.applySourceChange);
89     ctx.registerCommand('selectAndApplySourceChange', commands.selectAndApplySourceChange);
90
91     if (workspaceFolder !== null) {
92         ctx.pushCleanup(activateTaskProvider(workspaceFolder));
93     }
94
95     activateStatusDisplay(ctx);
96
97     if (!ctx.config.highlightingSemanticTokens) {
98         activateHighlighting(ctx);
99     }
100     activateInlayHints(ctx);
101
102     vscode.workspace.onDidChangeConfiguration(
103         _ => ctx?.client?.sendNotification('workspace/didChangeConfiguration', { settings: "" }),
104         null,
105         ctx.subscriptions,
106     );
107 }
108
109 export async function deactivate() {
110     await ctx?.client.stop();
111     ctx = undefined;
112 }
113
114 async function bootstrap(config: Config, state: PersistentState): Promise<string> {
115     await fs.mkdir(config.globalStoragePath, { recursive: true });
116
117     await bootstrapExtension(config, state);
118     const path = await bootstrapServer(config, state);
119
120     return path;
121 }
122
123 async function bootstrapExtension(config: Config, state: PersistentState): Promise<void> {
124     if (config.package.releaseTag === null) return;
125     if (config.channel === "stable") {
126         if (config.package.releaseTag === NIGHTLY_TAG) {
127             void vscode.window.showWarningMessage(
128                 `You are running a nightly version of rust-analyzer extension. ` +
129                 `To switch to stable, uninstall the extension and re-install it from the marketplace`
130             );
131         }
132         return;
133     };
134
135     const lastCheck = state.lastCheck;
136     const now = Date.now();
137
138     const anHour = 60 * 60 * 1000;
139     const shouldDownloadNightly = state.releaseId === undefined || (now - (lastCheck ?? 0)) > anHour;
140
141     if (!shouldDownloadNightly) return;
142
143     const release = await fetchRelease("nightly").catch((e) => {
144         log.error(e);
145         if (state.releaseId === undefined) { // Show error only for the initial download
146             vscode.window.showErrorMessage(`Failed to download rust-analyzer nightly ${e}`);
147         }
148         return undefined;
149     });
150     if (release === undefined || release.id === state.releaseId) return;
151
152     const userResponse = await vscode.window.showInformationMessage(
153         "New version of rust-analyzer (nightly) is available (requires reload).",
154         "Update"
155     );
156     if (userResponse !== "Update") return;
157
158     const artifact = release.assets.find(artifact => artifact.name === "rust-analyzer.vsix");
159     assert(!!artifact, `Bad release: ${JSON.stringify(release)}`);
160
161     const dest = path.join(config.globalStoragePath, "rust-analyzer.vsix");
162     await download(artifact.browser_download_url, dest, "Downloading rust-analyzer extension");
163
164     await vscode.commands.executeCommand("workbench.extensions.installExtension", vscode.Uri.file(dest));
165     await fs.unlink(dest);
166
167     await state.updateReleaseId(release.id);
168     await state.updateLastCheck(now);
169     await vscode.commands.executeCommand("workbench.action.reloadWindow");
170 }
171
172 async function bootstrapServer(config: Config, state: PersistentState): Promise<string> {
173     const path = await getServer(config, state);
174     if (!path) {
175         throw new Error(
176             "Rust Analyzer Language Server is not available. " +
177             "Please, ensure its [proper installation](https://rust-analyzer.github.io/manual.html#installation)."
178         );
179     }
180
181     const res = spawnSync(path, ["--version"], { encoding: 'utf8' });
182     log.debug("Checked binary availability via --version", res);
183     log.debug(res, "--version output:", res.output);
184     if (res.status !== 0) {
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 }