diff options
author | Dmitry <[email protected]> | 2020-02-16 17:36:48 +0000 |
---|---|---|
committer | Dmitry <[email protected]> | 2020-02-16 17:36:48 +0000 |
commit | 58e15d12e4211306273b0128cb4a80b552889543 (patch) | |
tree | 70e129b7cd76c55d5cb86f9b084db001f73a2003 /editors/code/src | |
parent | b446384956243ce6bdcef2a869123a2605e597ed (diff) | |
parent | 742b3b5744fbca1a5587e2898cd5b74d55853a47 (diff) |
Merge remote-tracking branch 'origin/master'
Diffstat (limited to 'editors/code/src')
-rw-r--r-- | editors/code/src/client.ts | 31 | ||||
-rw-r--r-- | editors/code/src/config.ts | 294 | ||||
-rw-r--r-- | editors/code/src/ctx.ts | 4 | ||||
-rw-r--r-- | editors/code/src/installation/download_artifact.ts | 58 | ||||
-rw-r--r-- | editors/code/src/installation/fetch_artifact_release_info.ts (renamed from editors/code/src/installation/fetch_latest_artifact_metadata.ts) | 20 | ||||
-rw-r--r-- | editors/code/src/installation/interfaces.ts | 15 | ||||
-rw-r--r-- | editors/code/src/installation/language_server.ts | 148 | ||||
-rw-r--r-- | editors/code/src/installation/server.ts | 124 | ||||
-rw-r--r-- | editors/code/src/status_display.ts | 4 |
9 files changed, 325 insertions, 373 deletions
diff --git a/editors/code/src/client.ts b/editors/code/src/client.ts index 2e3d4aba2..efef820ab 100644 --- a/editors/code/src/client.ts +++ b/editors/code/src/client.ts | |||
@@ -1,39 +1,42 @@ | |||
1 | import * as lc from 'vscode-languageclient'; | 1 | import * as lc from 'vscode-languageclient'; |
2 | import * as vscode from 'vscode'; | ||
2 | 3 | ||
3 | import { window, workspace } from 'vscode'; | ||
4 | import { Config } from './config'; | 4 | import { Config } from './config'; |
5 | import { ensureLanguageServerBinary } from './installation/language_server'; | 5 | import { ensureServerBinary } from './installation/server'; |
6 | import { CallHierarchyFeature } from 'vscode-languageclient/lib/callHierarchy.proposed'; | ||
6 | 7 | ||
7 | export async function createClient(config: Config): Promise<null | lc.LanguageClient> { | 8 | export async function createClient(config: Config): Promise<null | lc.LanguageClient> { |
8 | // '.' Is the fallback if no folder is open | 9 | // '.' Is the fallback if no folder is open |
9 | // TODO?: Workspace folders support Uri's (eg: file://test.txt). | 10 | // TODO?: Workspace folders support Uri's (eg: file://test.txt). |
10 | // It might be a good idea to test if the uri points to a file. | 11 | // It might be a good idea to test if the uri points to a file. |
11 | const workspaceFolderPath = workspace.workspaceFolders?.[0]?.uri.fsPath ?? '.'; | 12 | const workspaceFolderPath = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath ?? '.'; |
12 | 13 | ||
13 | const raLspServerPath = await ensureLanguageServerBinary(config.langServerSource); | 14 | const serverPath = await ensureServerBinary(config.serverSource); |
14 | if (!raLspServerPath) return null; | 15 | if (!serverPath) return null; |
15 | 16 | ||
16 | const run: lc.Executable = { | 17 | const run: lc.Executable = { |
17 | command: raLspServerPath, | 18 | command: serverPath, |
18 | options: { cwd: workspaceFolderPath }, | 19 | options: { cwd: workspaceFolderPath }, |
19 | }; | 20 | }; |
20 | const serverOptions: lc.ServerOptions = { | 21 | const serverOptions: lc.ServerOptions = { |
21 | run, | 22 | run, |
22 | debug: run, | 23 | debug: run, |
23 | }; | 24 | }; |
24 | const traceOutputChannel = window.createOutputChannel( | 25 | const traceOutputChannel = vscode.window.createOutputChannel( |
25 | 'Rust Analyzer Language Server Trace', | 26 | 'Rust Analyzer Language Server Trace', |
26 | ); | 27 | ); |
28 | const cargoWatchOpts = config.cargoWatchOptions; | ||
29 | |||
27 | const clientOptions: lc.LanguageClientOptions = { | 30 | const clientOptions: lc.LanguageClientOptions = { |
28 | documentSelector: [{ scheme: 'file', language: 'rust' }], | 31 | documentSelector: [{ scheme: 'file', language: 'rust' }], |
29 | initializationOptions: { | 32 | initializationOptions: { |
30 | publishDecorations: true, | 33 | publishDecorations: true, |
31 | lruCapacity: config.lruCapacity, | 34 | lruCapacity: config.lruCapacity, |
32 | maxInlayHintLength: config.maxInlayHintLength, | 35 | maxInlayHintLength: config.maxInlayHintLength, |
33 | cargoWatchEnable: config.cargoWatchOptions.enable, | 36 | cargoWatchEnable: cargoWatchOpts.enable, |
34 | cargoWatchArgs: config.cargoWatchOptions.arguments, | 37 | cargoWatchArgs: cargoWatchOpts.arguments, |
35 | cargoWatchCommand: config.cargoWatchOptions.command, | 38 | cargoWatchCommand: cargoWatchOpts.command, |
36 | cargoWatchAllTargets: config.cargoWatchOptions.allTargets, | 39 | cargoWatchAllTargets: cargoWatchOpts.allTargets, |
37 | excludeGlobs: config.excludeGlobs, | 40 | excludeGlobs: config.excludeGlobs, |
38 | useClientWatching: config.useClientWatching, | 41 | useClientWatching: config.useClientWatching, |
39 | featureFlags: config.featureFlags, | 42 | featureFlags: config.featureFlags, |
@@ -78,6 +81,10 @@ export async function createClient(config: Config): Promise<null | lc.LanguageCl | |||
78 | } | 81 | } |
79 | }, | 82 | }, |
80 | }; | 83 | }; |
81 | res.registerProposedFeatures(); | 84 | |
85 | // To turn on all proposed features use: res.registerProposedFeatures(); | ||
86 | // Here we want to just enable CallHierarchyFeature since it is available on stable. | ||
87 | // Note that while the CallHierarchyFeature is stable the LSP protocol is not. | ||
88 | res.registerFeature(new CallHierarchyFeature(res)); | ||
82 | return res; | 89 | return res; |
83 | } | 90 | } |
diff --git a/editors/code/src/config.ts b/editors/code/src/config.ts index 418845436..70cb0a612 100644 --- a/editors/code/src/config.ts +++ b/editors/code/src/config.ts | |||
@@ -16,45 +16,62 @@ export interface CargoFeatures { | |||
16 | allFeatures: boolean; | 16 | allFeatures: boolean; |
17 | features: string[]; | 17 | features: string[]; |
18 | } | 18 | } |
19 | |||
20 | export class Config { | 19 | export class Config { |
21 | langServerSource!: null | BinarySource; | 20 | private static readonly rootSection = "rust-analyzer"; |
22 | 21 | private static readonly requiresReloadOpts = [ | |
23 | highlightingOn = true; | 22 | "cargoFeatures", |
24 | rainbowHighlightingOn = false; | 23 | "cargo-watch", |
25 | enableEnhancedTyping = true; | 24 | ] |
26 | lruCapacity: null | number = null; | 25 | .map(opt => `${Config.rootSection}.${opt}`); |
27 | displayInlayHints = true; | 26 | |
28 | maxInlayHintLength: null | number = null; | 27 | private static readonly extensionVersion: string = (() => { |
29 | excludeGlobs: string[] = []; | 28 | const packageJsonVersion = vscode |
30 | useClientWatching = true; | 29 | .extensions |
31 | featureFlags: Record<string, boolean> = {}; | 30 | .getExtension("matklad.rust-analyzer")! |
32 | // for internal use | 31 | .packageJSON |
33 | withSysroot: null | boolean = null; | 32 | .version as string; // n.n.YYYYMMDD |
34 | cargoWatchOptions: CargoWatchOptions = { | 33 | |
35 | enable: true, | 34 | const realVersionRegexp = /^\d+\.\d+\.(\d{4})(\d{2})(\d{2})/; |
36 | arguments: [], | 35 | const [, yyyy, mm, dd] = packageJsonVersion.match(realVersionRegexp)!; |
37 | command: '', | 36 | |
38 | allTargets: true, | 37 | return `${yyyy}-${mm}-${dd}`; |
39 | }; | 38 | })(); |
40 | cargoFeatures: CargoFeatures = { | 39 | |
41 | noDefaultFeatures: false, | 40 | private cfg!: vscode.WorkspaceConfiguration; |
42 | allFeatures: true, | 41 | |
43 | features: [], | 42 | constructor(private readonly ctx: vscode.ExtensionContext) { |
44 | }; | 43 | vscode.workspace.onDidChangeConfiguration(this.onConfigChange, this, ctx.subscriptions); |
45 | 44 | this.refreshConfig(); | |
46 | private prevEnhancedTyping: null | boolean = null; | 45 | } |
47 | private prevCargoFeatures: null | CargoFeatures = null; | 46 | |
48 | private prevCargoWatchOptions: null | CargoWatchOptions = null; | 47 | |
49 | 48 | private refreshConfig() { | |
50 | constructor(ctx: vscode.ExtensionContext) { | 49 | this.cfg = vscode.workspace.getConfiguration(Config.rootSection); |
51 | vscode.workspace.onDidChangeConfiguration(_ => this.refresh(ctx), null, ctx.subscriptions); | 50 | console.log("Using configuration:", this.cfg); |
52 | this.refresh(ctx); | ||
53 | } | 51 | } |
54 | 52 | ||
55 | private static expandPathResolving(path: string) { | 53 | private async onConfigChange(event: vscode.ConfigurationChangeEvent) { |
56 | if (path.startsWith('~/')) { | 54 | this.refreshConfig(); |
57 | return path.replace('~', os.homedir()); | 55 | |
56 | const requiresReloadOpt = Config.requiresReloadOpts.find( | ||
57 | opt => event.affectsConfiguration(opt) | ||
58 | ); | ||
59 | |||
60 | if (!requiresReloadOpt) return; | ||
61 | |||
62 | const userResponse = await vscode.window.showInformationMessage( | ||
63 | `Changing "${requiresReloadOpt}" requires a reload`, | ||
64 | "Reload now" | ||
65 | ); | ||
66 | |||
67 | if (userResponse === "Reload now") { | ||
68 | vscode.commands.executeCommand("workbench.action.reloadWindow"); | ||
69 | } | ||
70 | } | ||
71 | |||
72 | private static replaceTildeWithHomeDir(path: string) { | ||
73 | if (path.startsWith("~/")) { | ||
74 | return os.homedir() + path.slice("~".length); | ||
58 | } | 75 | } |
59 | return path; | 76 | return path; |
60 | } | 77 | } |
@@ -64,17 +81,14 @@ export class Config { | |||
64 | * `platform` on GitHub releases. (It is also stored under the same name when | 81 | * `platform` on GitHub releases. (It is also stored under the same name when |
65 | * downloaded by the extension). | 82 | * downloaded by the extension). |
66 | */ | 83 | */ |
67 | private static prebuiltLangServerFileName( | 84 | get prebuiltServerFileName(): null | string { |
68 | platform: NodeJS.Platform, | ||
69 | arch: string | ||
70 | ): null | string { | ||
71 | // See possible `arch` values here: | 85 | // See possible `arch` values here: |
72 | // https://nodejs.org/api/process.html#process_process_arch | 86 | // https://nodejs.org/api/process.html#process_process_arch |
73 | 87 | ||
74 | switch (platform) { | 88 | switch (process.platform) { |
75 | 89 | ||
76 | case "linux": { | 90 | case "linux": { |
77 | switch (arch) { | 91 | switch (process.arch) { |
78 | case "arm": | 92 | case "arm": |
79 | case "arm64": return null; | 93 | case "arm64": return null; |
80 | 94 | ||
@@ -97,29 +111,26 @@ export class Config { | |||
97 | } | 111 | } |
98 | } | 112 | } |
99 | 113 | ||
100 | private static langServerBinarySource( | 114 | get serverSource(): null | BinarySource { |
101 | ctx: vscode.ExtensionContext, | 115 | const serverPath = RA_LSP_DEBUG ?? this.cfg.get<null | string>("raLspServerPath"); |
102 | config: vscode.WorkspaceConfiguration | ||
103 | ): null | BinarySource { | ||
104 | const langServerPath = RA_LSP_DEBUG ?? config.get<null | string>("raLspServerPath"); | ||
105 | 116 | ||
106 | if (langServerPath) { | 117 | if (serverPath) { |
107 | return { | 118 | return { |
108 | type: BinarySource.Type.ExplicitPath, | 119 | type: BinarySource.Type.ExplicitPath, |
109 | path: Config.expandPathResolving(langServerPath) | 120 | path: Config.replaceTildeWithHomeDir(serverPath) |
110 | }; | 121 | }; |
111 | } | 122 | } |
112 | 123 | ||
113 | const prebuiltBinaryName = Config.prebuiltLangServerFileName( | 124 | const prebuiltBinaryName = this.prebuiltServerFileName; |
114 | process.platform, process.arch | ||
115 | ); | ||
116 | 125 | ||
117 | if (!prebuiltBinaryName) return null; | 126 | if (!prebuiltBinaryName) return null; |
118 | 127 | ||
119 | return { | 128 | return { |
120 | type: BinarySource.Type.GithubRelease, | 129 | type: BinarySource.Type.GithubRelease, |
121 | dir: ctx.globalStoragePath, | 130 | dir: this.ctx.globalStoragePath, |
122 | file: prebuiltBinaryName, | 131 | file: prebuiltBinaryName, |
132 | storage: this.ctx.globalState, | ||
133 | version: Config.extensionVersion, | ||
123 | repo: { | 134 | repo: { |
124 | name: "rust-analyzer", | 135 | name: "rust-analyzer", |
125 | owner: "rust-analyzer", | 136 | owner: "rust-analyzer", |
@@ -127,158 +138,35 @@ export class Config { | |||
127 | }; | 138 | }; |
128 | } | 139 | } |
129 | 140 | ||
141 | // We don't do runtime config validation here for simplicity. More on stackoverflow: | ||
142 | // https://stackoverflow.com/questions/60135780/what-is-the-best-way-to-type-check-the-configuration-for-vscode-extension | ||
130 | 143 | ||
131 | // FIXME: revisit the logic for `if (.has(...)) config.get(...)` set default | 144 | get highlightingOn() { return this.cfg.get("highlightingOn") as boolean; } |
132 | // values only in one place (i.e. remove default values from non-readonly members declarations) | 145 | get rainbowHighlightingOn() { return this.cfg.get("rainbowHighlightingOn") as boolean; } |
133 | private refresh(ctx: vscode.ExtensionContext) { | 146 | get lruCapacity() { return this.cfg.get("lruCapacity") as null | number; } |
134 | const config = vscode.workspace.getConfiguration('rust-analyzer'); | 147 | get displayInlayHints() { return this.cfg.get("displayInlayHints") as boolean; } |
135 | 148 | get maxInlayHintLength() { return this.cfg.get("maxInlayHintLength") as number; } | |
136 | let requireReloadMessage = null; | 149 | get excludeGlobs() { return this.cfg.get("excludeGlobs") as string[]; } |
137 | 150 | get useClientWatching() { return this.cfg.get("useClientWatching") as boolean; } | |
138 | if (config.has('highlightingOn')) { | 151 | get featureFlags() { return this.cfg.get("featureFlags") as Record<string, boolean>; } |
139 | this.highlightingOn = config.get('highlightingOn') as boolean; | ||
140 | } | ||
141 | |||
142 | if (config.has('rainbowHighlightingOn')) { | ||
143 | this.rainbowHighlightingOn = config.get( | ||
144 | 'rainbowHighlightingOn', | ||
145 | ) as boolean; | ||
146 | } | ||
147 | |||
148 | if (config.has('enableEnhancedTyping')) { | ||
149 | this.enableEnhancedTyping = config.get( | ||
150 | 'enableEnhancedTyping', | ||
151 | ) as boolean; | ||
152 | |||
153 | if (this.prevEnhancedTyping === null) { | ||
154 | this.prevEnhancedTyping = this.enableEnhancedTyping; | ||
155 | } | ||
156 | } else if (this.prevEnhancedTyping === null) { | ||
157 | this.prevEnhancedTyping = this.enableEnhancedTyping; | ||
158 | } | ||
159 | |||
160 | if (this.prevEnhancedTyping !== this.enableEnhancedTyping) { | ||
161 | requireReloadMessage = | ||
162 | 'Changing enhanced typing setting requires a reload'; | ||
163 | this.prevEnhancedTyping = this.enableEnhancedTyping; | ||
164 | } | ||
165 | |||
166 | this.langServerSource = Config.langServerBinarySource(ctx, config); | ||
167 | |||
168 | if (config.has('cargo-watch.enable')) { | ||
169 | this.cargoWatchOptions.enable = config.get<boolean>( | ||
170 | 'cargo-watch.enable', | ||
171 | true, | ||
172 | ); | ||
173 | } | ||
174 | |||
175 | if (config.has('cargo-watch.arguments')) { | ||
176 | this.cargoWatchOptions.arguments = config.get<string[]>( | ||
177 | 'cargo-watch.arguments', | ||
178 | [], | ||
179 | ); | ||
180 | } | ||
181 | |||
182 | if (config.has('cargo-watch.command')) { | ||
183 | this.cargoWatchOptions.command = config.get<string>( | ||
184 | 'cargo-watch.command', | ||
185 | '', | ||
186 | ); | ||
187 | } | ||
188 | |||
189 | if (config.has('cargo-watch.allTargets')) { | ||
190 | this.cargoWatchOptions.allTargets = config.get<boolean>( | ||
191 | 'cargo-watch.allTargets', | ||
192 | true, | ||
193 | ); | ||
194 | } | ||
195 | |||
196 | if (config.has('lruCapacity')) { | ||
197 | this.lruCapacity = config.get('lruCapacity') as number; | ||
198 | } | ||
199 | |||
200 | if (config.has('displayInlayHints')) { | ||
201 | this.displayInlayHints = config.get('displayInlayHints') as boolean; | ||
202 | } | ||
203 | if (config.has('maxInlayHintLength')) { | ||
204 | this.maxInlayHintLength = config.get( | ||
205 | 'maxInlayHintLength', | ||
206 | ) as number; | ||
207 | } | ||
208 | if (config.has('excludeGlobs')) { | ||
209 | this.excludeGlobs = config.get('excludeGlobs') || []; | ||
210 | } | ||
211 | if (config.has('useClientWatching')) { | ||
212 | this.useClientWatching = config.get('useClientWatching') || true; | ||
213 | } | ||
214 | if (config.has('featureFlags')) { | ||
215 | this.featureFlags = config.get('featureFlags') || {}; | ||
216 | } | ||
217 | if (config.has('withSysroot')) { | ||
218 | this.withSysroot = config.get('withSysroot') || false; | ||
219 | } | ||
220 | 152 | ||
221 | if (config.has('cargoFeatures.noDefaultFeatures')) { | 153 | get cargoWatchOptions(): CargoWatchOptions { |
222 | this.cargoFeatures.noDefaultFeatures = config.get( | 154 | return { |
223 | 'cargoFeatures.noDefaultFeatures', | 155 | enable: this.cfg.get("cargo-watch.enable") as boolean, |
224 | false, | 156 | arguments: this.cfg.get("cargo-watch.arguments") as string[], |
225 | ); | 157 | allTargets: this.cfg.get("cargo-watch.allTargets") as boolean, |
226 | } | 158 | command: this.cfg.get("cargo-watch.command") as string, |
227 | if (config.has('cargoFeatures.allFeatures')) { | 159 | }; |
228 | this.cargoFeatures.allFeatures = config.get( | 160 | } |
229 | 'cargoFeatures.allFeatures', | ||
230 | true, | ||
231 | ); | ||
232 | } | ||
233 | if (config.has('cargoFeatures.features')) { | ||
234 | this.cargoFeatures.features = config.get( | ||
235 | 'cargoFeatures.features', | ||
236 | [], | ||
237 | ); | ||
238 | } | ||
239 | 161 | ||
240 | if ( | 162 | get cargoFeatures(): CargoFeatures { |
241 | this.prevCargoFeatures !== null && | 163 | return { |
242 | (this.cargoFeatures.allFeatures !== | 164 | noDefaultFeatures: this.cfg.get("cargoFeatures.noDefaultFeatures") as boolean, |
243 | this.prevCargoFeatures.allFeatures || | 165 | allFeatures: this.cfg.get("cargoFeatures.allFeatures") as boolean, |
244 | this.cargoFeatures.noDefaultFeatures !== | 166 | features: this.cfg.get("cargoFeatures.features") as string[], |
245 | this.prevCargoFeatures.noDefaultFeatures || | 167 | }; |
246 | this.cargoFeatures.features.length !== | ||
247 | this.prevCargoFeatures.features.length || | ||
248 | this.cargoFeatures.features.some( | ||
249 | (v, i) => v !== this.prevCargoFeatures!.features[i], | ||
250 | )) | ||
251 | ) { | ||
252 | requireReloadMessage = 'Changing cargo features requires a reload'; | ||
253 | } | ||
254 | this.prevCargoFeatures = { ...this.cargoFeatures }; | ||
255 | |||
256 | if (this.prevCargoWatchOptions !== null) { | ||
257 | const changed = | ||
258 | this.cargoWatchOptions.enable !== this.prevCargoWatchOptions.enable || | ||
259 | this.cargoWatchOptions.command !== this.prevCargoWatchOptions.command || | ||
260 | this.cargoWatchOptions.allTargets !== this.prevCargoWatchOptions.allTargets || | ||
261 | this.cargoWatchOptions.arguments.length !== this.prevCargoWatchOptions.arguments.length || | ||
262 | this.cargoWatchOptions.arguments.some( | ||
263 | (v, i) => v !== this.prevCargoWatchOptions!.arguments[i], | ||
264 | ); | ||
265 | if (changed) { | ||
266 | requireReloadMessage = 'Changing cargo-watch options requires a reload'; | ||
267 | } | ||
268 | } | ||
269 | this.prevCargoWatchOptions = { ...this.cargoWatchOptions }; | ||
270 | |||
271 | if (requireReloadMessage !== null) { | ||
272 | const reloadAction = 'Reload now'; | ||
273 | vscode.window | ||
274 | .showInformationMessage(requireReloadMessage, reloadAction) | ||
275 | .then(selectedAction => { | ||
276 | if (selectedAction === reloadAction) { | ||
277 | vscode.commands.executeCommand( | ||
278 | 'workbench.action.reloadWindow', | ||
279 | ); | ||
280 | } | ||
281 | }); | ||
282 | } | ||
283 | } | 168 | } |
169 | |||
170 | // for internal use | ||
171 | get withSysroot() { return this.cfg.get("withSysroot", true) as boolean; } | ||
284 | } | 172 | } |
diff --git a/editors/code/src/ctx.ts b/editors/code/src/ctx.ts index 70042a479..9fcf2ec38 100644 --- a/editors/code/src/ctx.ts +++ b/editors/code/src/ctx.ts | |||
@@ -60,6 +60,10 @@ export class Ctx { | |||
60 | this.pushCleanup(d); | 60 | this.pushCleanup(d); |
61 | } | 61 | } |
62 | 62 | ||
63 | get globalState(): vscode.Memento { | ||
64 | return this.extCtx.globalState; | ||
65 | } | ||
66 | |||
63 | get subscriptions(): Disposable[] { | 67 | get subscriptions(): Disposable[] { |
64 | return this.extCtx.subscriptions; | 68 | return this.extCtx.subscriptions; |
65 | } | 69 | } |
diff --git a/editors/code/src/installation/download_artifact.ts b/editors/code/src/installation/download_artifact.ts new file mode 100644 index 000000000..de655f8f4 --- /dev/null +++ b/editors/code/src/installation/download_artifact.ts | |||
@@ -0,0 +1,58 @@ | |||
1 | import * as vscode from "vscode"; | ||
2 | import * as path from "path"; | ||
3 | import { promises as fs } from "fs"; | ||
4 | import { strict as assert } from "assert"; | ||
5 | |||
6 | import { ArtifactReleaseInfo } from "./interfaces"; | ||
7 | import { downloadFile } from "./download_file"; | ||
8 | import { throttle } from "throttle-debounce"; | ||
9 | |||
10 | /** | ||
11 | * Downloads artifact from given `downloadUrl`. | ||
12 | * Creates `installationDir` if it is not yet created and put the artifact under | ||
13 | * `artifactFileName`. | ||
14 | * Displays info about the download progress in an info message printing the name | ||
15 | * of the artifact as `displayName`. | ||
16 | */ | ||
17 | export async function downloadArtifact( | ||
18 | {downloadUrl, releaseName}: ArtifactReleaseInfo, | ||
19 | artifactFileName: string, | ||
20 | installationDir: string, | ||
21 | displayName: string, | ||
22 | ) { | ||
23 | await fs.mkdir(installationDir).catch(err => assert.strictEqual( | ||
24 | err?.code, | ||
25 | "EEXIST", | ||
26 | `Couldn't create directory "${installationDir}" to download `+ | ||
27 | `${artifactFileName} artifact: ${err.message}` | ||
28 | )); | ||
29 | |||
30 | const installationPath = path.join(installationDir, artifactFileName); | ||
31 | |||
32 | console.time(`Downloading ${artifactFileName}`); | ||
33 | await vscode.window.withProgress( | ||
34 | { | ||
35 | location: vscode.ProgressLocation.Notification, | ||
36 | cancellable: false, // FIXME: add support for canceling download? | ||
37 | title: `Downloading ${displayName} (${releaseName})` | ||
38 | }, | ||
39 | async (progress, _cancellationToken) => { | ||
40 | let lastPrecentage = 0; | ||
41 | const filePermissions = 0o755; // (rwx, r_x, r_x) | ||
42 | await downloadFile(downloadUrl, installationPath, filePermissions, throttle( | ||
43 | 200, | ||
44 | /* noTrailing: */ true, | ||
45 | (readBytes, totalBytes) => { | ||
46 | const newPercentage = (readBytes / totalBytes) * 100; | ||
47 | progress.report({ | ||
48 | message: newPercentage.toFixed(0) + "%", | ||
49 | increment: newPercentage - lastPrecentage | ||
50 | }); | ||
51 | |||
52 | lastPrecentage = newPercentage; | ||
53 | }) | ||
54 | ); | ||
55 | } | ||
56 | ); | ||
57 | console.timeEnd(`Downloading ${artifactFileName}`); | ||
58 | } | ||
diff --git a/editors/code/src/installation/fetch_latest_artifact_metadata.ts b/editors/code/src/installation/fetch_artifact_release_info.ts index 7e3700603..7d497057a 100644 --- a/editors/code/src/installation/fetch_latest_artifact_metadata.ts +++ b/editors/code/src/installation/fetch_artifact_release_info.ts | |||
@@ -1,26 +1,32 @@ | |||
1 | import fetch from "node-fetch"; | 1 | import fetch from "node-fetch"; |
2 | import { GithubRepo, ArtifactMetadata } from "./interfaces"; | 2 | import { GithubRepo, ArtifactReleaseInfo } from "./interfaces"; |
3 | 3 | ||
4 | const GITHUB_API_ENDPOINT_URL = "https://api.github.com"; | 4 | const GITHUB_API_ENDPOINT_URL = "https://api.github.com"; |
5 | 5 | ||
6 | |||
6 | /** | 7 | /** |
7 | * Fetches the latest release from GitHub `repo` and returns metadata about | 8 | * Fetches the release with `releaseTag` (or just latest release when not specified) |
8 | * `artifactFileName` shipped with this release or `null` if no such artifact was published. | 9 | * from GitHub `repo` and returns metadata about `artifactFileName` shipped with |
10 | * this release or `null` if no such artifact was published. | ||
9 | */ | 11 | */ |
10 | export async function fetchLatestArtifactMetadata( | 12 | export async function fetchArtifactReleaseInfo( |
11 | repo: GithubRepo, artifactFileName: string | 13 | repo: GithubRepo, artifactFileName: string, releaseTag?: string |
12 | ): Promise<null | ArtifactMetadata> { | 14 | ): Promise<null | ArtifactReleaseInfo> { |
13 | 15 | ||
14 | const repoOwner = encodeURIComponent(repo.owner); | 16 | const repoOwner = encodeURIComponent(repo.owner); |
15 | const repoName = encodeURIComponent(repo.name); | 17 | const repoName = encodeURIComponent(repo.name); |
16 | 18 | ||
17 | const apiEndpointPath = `/repos/${repoOwner}/${repoName}/releases/latest`; | 19 | const apiEndpointPath = releaseTag |
20 | ? `/repos/${repoOwner}/${repoName}/releases/tags/${releaseTag}` | ||
21 | : `/repos/${repoOwner}/${repoName}/releases/latest`; | ||
22 | |||
18 | const requestUrl = GITHUB_API_ENDPOINT_URL + apiEndpointPath; | 23 | const requestUrl = GITHUB_API_ENDPOINT_URL + apiEndpointPath; |
19 | 24 | ||
20 | // We skip runtime type checks for simplicity (here we cast from `any` to `GithubRelease`) | 25 | // We skip runtime type checks for simplicity (here we cast from `any` to `GithubRelease`) |
21 | 26 | ||
22 | console.log("Issuing request for released artifacts metadata to", requestUrl); | 27 | console.log("Issuing request for released artifacts metadata to", requestUrl); |
23 | 28 | ||
29 | // FIXME: handle non-ok response | ||
24 | const response: GithubRelease = await fetch(requestUrl, { | 30 | const response: GithubRelease = await fetch(requestUrl, { |
25 | headers: { Accept: "application/vnd.github.v3+json" } | 31 | headers: { Accept: "application/vnd.github.v3+json" } |
26 | }) | 32 | }) |
diff --git a/editors/code/src/installation/interfaces.ts b/editors/code/src/installation/interfaces.ts index 8039d0b90..e40839e4b 100644 --- a/editors/code/src/installation/interfaces.ts +++ b/editors/code/src/installation/interfaces.ts | |||
@@ -1,3 +1,5 @@ | |||
1 | import * as vscode from "vscode"; | ||
2 | |||
1 | export interface GithubRepo { | 3 | export interface GithubRepo { |
2 | name: string; | 4 | name: string; |
3 | owner: string; | 5 | owner: string; |
@@ -6,7 +8,7 @@ export interface GithubRepo { | |||
6 | /** | 8 | /** |
7 | * Metadata about particular artifact retrieved from GitHub releases. | 9 | * Metadata about particular artifact retrieved from GitHub releases. |
8 | */ | 10 | */ |
9 | export interface ArtifactMetadata { | 11 | export interface ArtifactReleaseInfo { |
10 | releaseName: string; | 12 | releaseName: string; |
11 | downloadUrl: string; | 13 | downloadUrl: string; |
12 | } | 14 | } |
@@ -50,6 +52,17 @@ export namespace BinarySource { | |||
50 | * and in local `.dir`. | 52 | * and in local `.dir`. |
51 | */ | 53 | */ |
52 | file: string; | 54 | file: string; |
55 | |||
56 | /** | ||
57 | * Tag of github release that denotes a version required by this extension. | ||
58 | */ | ||
59 | version: string; | ||
60 | |||
61 | /** | ||
62 | * Object that provides `get()/update()` operations to store metadata | ||
63 | * about the actual binary, e.g. its actual version. | ||
64 | */ | ||
65 | storage: vscode.Memento; | ||
53 | } | 66 | } |
54 | 67 | ||
55 | } | 68 | } |
diff --git a/editors/code/src/installation/language_server.ts b/editors/code/src/installation/language_server.ts deleted file mode 100644 index 4797c3f01..000000000 --- a/editors/code/src/installation/language_server.ts +++ /dev/null | |||
@@ -1,148 +0,0 @@ | |||
1 | import * as vscode from "vscode"; | ||
2 | import * as path from "path"; | ||
3 | import { strict as assert } from "assert"; | ||
4 | import { promises as fs } from "fs"; | ||
5 | import { promises as dns } from "dns"; | ||
6 | import { spawnSync } from "child_process"; | ||
7 | import { throttle } from "throttle-debounce"; | ||
8 | |||
9 | import { BinarySource } from "./interfaces"; | ||
10 | import { fetchLatestArtifactMetadata } from "./fetch_latest_artifact_metadata"; | ||
11 | import { downloadFile } from "./download_file"; | ||
12 | |||
13 | export async function downloadLatestLanguageServer( | ||
14 | {file: artifactFileName, dir: installationDir, repo}: BinarySource.GithubRelease | ||
15 | ) { | ||
16 | const { releaseName, downloadUrl } = (await fetchLatestArtifactMetadata( | ||
17 | repo, artifactFileName | ||
18 | ))!; | ||
19 | |||
20 | await fs.mkdir(installationDir).catch(err => assert.strictEqual( | ||
21 | err?.code, | ||
22 | "EEXIST", | ||
23 | `Couldn't create directory "${installationDir}" to download `+ | ||
24 | `language server binary: ${err.message}` | ||
25 | )); | ||
26 | |||
27 | const installationPath = path.join(installationDir, artifactFileName); | ||
28 | |||
29 | console.time("Downloading ra_lsp_server"); | ||
30 | await vscode.window.withProgress( | ||
31 | { | ||
32 | location: vscode.ProgressLocation.Notification, | ||
33 | cancellable: false, // FIXME: add support for canceling download? | ||
34 | title: `Downloading language server (${releaseName})` | ||
35 | }, | ||
36 | async (progress, _cancellationToken) => { | ||
37 | let lastPrecentage = 0; | ||
38 | const filePermissions = 0o755; // (rwx, r_x, r_x) | ||
39 | await downloadFile(downloadUrl, installationPath, filePermissions, throttle( | ||
40 | 200, | ||
41 | /* noTrailing: */ true, | ||
42 | (readBytes, totalBytes) => { | ||
43 | const newPercentage = (readBytes / totalBytes) * 100; | ||
44 | progress.report({ | ||
45 | message: newPercentage.toFixed(0) + "%", | ||
46 | increment: newPercentage - lastPrecentage | ||
47 | }); | ||
48 | |||
49 | lastPrecentage = newPercentage; | ||
50 | }) | ||
51 | ); | ||
52 | } | ||
53 | ); | ||
54 | console.timeEnd("Downloading ra_lsp_server"); | ||
55 | } | ||
56 | export async function ensureLanguageServerBinary( | ||
57 | langServerSource: null | BinarySource | ||
58 | ): Promise<null | string> { | ||
59 | |||
60 | if (!langServerSource) { | ||
61 | vscode.window.showErrorMessage( | ||
62 | "Unfortunately we don't ship binaries for your platform yet. " + | ||
63 | "You need to manually clone rust-analyzer repository and " + | ||
64 | "run `cargo xtask install --server` to build the language server from sources. " + | ||
65 | "If you feel that your platform should be supported, please create an issue " + | ||
66 | "about that [here](https://github.com/rust-analyzer/rust-analyzer/issues) and we " + | ||
67 | "will consider it." | ||
68 | ); | ||
69 | return null; | ||
70 | } | ||
71 | |||
72 | switch (langServerSource.type) { | ||
73 | case BinarySource.Type.ExplicitPath: { | ||
74 | if (isBinaryAvailable(langServerSource.path)) { | ||
75 | return langServerSource.path; | ||
76 | } | ||
77 | |||
78 | vscode.window.showErrorMessage( | ||
79 | `Unable to run ${langServerSource.path} binary. ` + | ||
80 | `To use the pre-built language server, set "rust-analyzer.raLspServerPath" ` + | ||
81 | "value to `null` or remove it from the settings to use it by default." | ||
82 | ); | ||
83 | return null; | ||
84 | } | ||
85 | case BinarySource.Type.GithubRelease: { | ||
86 | const prebuiltBinaryPath = path.join(langServerSource.dir, langServerSource.file); | ||
87 | |||
88 | if (isBinaryAvailable(prebuiltBinaryPath)) { | ||
89 | return prebuiltBinaryPath; | ||
90 | } | ||
91 | |||
92 | const userResponse = await vscode.window.showInformationMessage( | ||
93 | "Language server binary for rust-analyzer was not found. " + | ||
94 | "Do you want to download it now?", | ||
95 | "Download now", "Cancel" | ||
96 | ); | ||
97 | if (userResponse !== "Download now") return null; | ||
98 | |||
99 | try { | ||
100 | await downloadLatestLanguageServer(langServerSource); | ||
101 | } catch (err) { | ||
102 | vscode.window.showErrorMessage( | ||
103 | `Failed to download language server from ${langServerSource.repo.name} ` + | ||
104 | `GitHub repository: ${err.message}` | ||
105 | ); | ||
106 | |||
107 | console.error(err); | ||
108 | |||
109 | dns.resolve('example.com').then( | ||
110 | addrs => console.log("DNS resolution for example.com was successful", addrs), | ||
111 | err => { | ||
112 | console.error( | ||
113 | "DNS resolution for example.com failed, " + | ||
114 | "there might be an issue with Internet availability" | ||
115 | ); | ||
116 | console.error(err); | ||
117 | } | ||
118 | ); | ||
119 | |||
120 | return null; | ||
121 | } | ||
122 | |||
123 | if (!isBinaryAvailable(prebuiltBinaryPath)) assert(false, | ||
124 | `Downloaded language server binary is not functional.` + | ||
125 | `Downloaded from: ${JSON.stringify(langServerSource)}` | ||
126 | ); | ||
127 | |||
128 | |||
129 | vscode.window.showInformationMessage( | ||
130 | "Rust analyzer language server was successfully installed 🦀" | ||
131 | ); | ||
132 | |||
133 | return prebuiltBinaryPath; | ||
134 | } | ||
135 | } | ||
136 | |||
137 | function isBinaryAvailable(binaryPath: string) { | ||
138 | const res = spawnSync(binaryPath, ["--version"]); | ||
139 | |||
140 | // ACHTUNG! `res` type declaration is inherently wrong, see | ||
141 | // https://github.com/DefinitelyTyped/DefinitelyTyped/issues/42221 | ||
142 | |||
143 | console.log("Checked binary availablity via --version", res); | ||
144 | console.log(binaryPath, "--version output:", res.output?.map(String)); | ||
145 | |||
146 | return res.status === 0; | ||
147 | } | ||
148 | } | ||
diff --git a/editors/code/src/installation/server.ts b/editors/code/src/installation/server.ts new file mode 100644 index 000000000..80cb719e3 --- /dev/null +++ b/editors/code/src/installation/server.ts | |||
@@ -0,0 +1,124 @@ | |||
1 | import * as vscode from "vscode"; | ||
2 | import * as path from "path"; | ||
3 | import { strict as assert } from "assert"; | ||
4 | import { promises as dns } from "dns"; | ||
5 | import { spawnSync } from "child_process"; | ||
6 | |||
7 | import { BinarySource } from "./interfaces"; | ||
8 | import { fetchArtifactReleaseInfo } from "./fetch_artifact_release_info"; | ||
9 | import { downloadArtifact } from "./download_artifact"; | ||
10 | |||
11 | export async function ensureServerBinary(source: null | BinarySource): Promise<null | string> { | ||
12 | if (!source) { | ||
13 | vscode.window.showErrorMessage( | ||
14 | "Unfortunately we don't ship binaries for your platform yet. " + | ||
15 | "You need to manually clone rust-analyzer repository and " + | ||
16 | "run `cargo xtask install --server` to build the language server from sources. " + | ||
17 | "If you feel that your platform should be supported, please create an issue " + | ||
18 | "about that [here](https://github.com/rust-analyzer/rust-analyzer/issues) and we " + | ||
19 | "will consider it." | ||
20 | ); | ||
21 | return null; | ||
22 | } | ||
23 | |||
24 | switch (source.type) { | ||
25 | case BinarySource.Type.ExplicitPath: { | ||
26 | if (isBinaryAvailable(source.path)) { | ||
27 | return source.path; | ||
28 | } | ||
29 | |||
30 | vscode.window.showErrorMessage( | ||
31 | `Unable to run ${source.path} binary. ` + | ||
32 | `To use the pre-built language server, set "rust-analyzer.raLspServerPath" ` + | ||
33 | "value to `null` or remove it from the settings to use it by default." | ||
34 | ); | ||
35 | return null; | ||
36 | } | ||
37 | case BinarySource.Type.GithubRelease: { | ||
38 | const prebuiltBinaryPath = path.join(source.dir, source.file); | ||
39 | |||
40 | const installedVersion: null | string = getServerVersion(source.storage); | ||
41 | const requiredVersion: string = source.version; | ||
42 | |||
43 | console.log("Installed version:", installedVersion, "required:", requiredVersion); | ||
44 | |||
45 | if (isBinaryAvailable(prebuiltBinaryPath) && installedVersion == requiredVersion) { | ||
46 | // FIXME: check for new releases and notify the user to update if possible | ||
47 | return prebuiltBinaryPath; | ||
48 | } | ||
49 | |||
50 | const userResponse = await vscode.window.showInformationMessage( | ||
51 | `Language server version ${source.version} for rust-analyzer is not installed. ` + | ||
52 | "Do you want to download it now?", | ||
53 | "Download now", "Cancel" | ||
54 | ); | ||
55 | if (userResponse !== "Download now") return null; | ||
56 | |||
57 | if (!await downloadServer(source)) return null; | ||
58 | |||
59 | return prebuiltBinaryPath; | ||
60 | } | ||
61 | } | ||
62 | } | ||
63 | |||
64 | async function downloadServer(source: BinarySource.GithubRelease): Promise<boolean> { | ||
65 | try { | ||
66 | const releaseInfo = (await fetchArtifactReleaseInfo(source.repo, source.file, source.version))!; | ||
67 | |||
68 | await downloadArtifact(releaseInfo, source.file, source.dir, "language server"); | ||
69 | await setServerVersion(source.storage, releaseInfo.releaseName); | ||
70 | } catch (err) { | ||
71 | vscode.window.showErrorMessage( | ||
72 | `Failed to download language server from ${source.repo.name} ` + | ||
73 | `GitHub repository: ${err.message}` | ||
74 | ); | ||
75 | |||
76 | console.error(err); | ||
77 | |||
78 | dns.resolve('example.com').then( | ||
79 | addrs => console.log("DNS resolution for example.com was successful", addrs), | ||
80 | err => { | ||
81 | console.error( | ||
82 | "DNS resolution for example.com failed, " + | ||
83 | "there might be an issue with Internet availability" | ||
84 | ); | ||
85 | console.error(err); | ||
86 | } | ||
87 | ); | ||
88 | return false; | ||
89 | } | ||
90 | |||
91 | if (!isBinaryAvailable(path.join(source.dir, source.file))) assert(false, | ||
92 | `Downloaded language server binary is not functional.` + | ||
93 | `Downloaded from: ${JSON.stringify(source, null, 4)}` | ||
94 | ); | ||
95 | |||
96 | vscode.window.showInformationMessage( | ||
97 | "Rust analyzer language server was successfully installed 🦀" | ||
98 | ); | ||
99 | |||
100 | return true; | ||
101 | } | ||
102 | |||
103 | function isBinaryAvailable(binaryPath: string): boolean { | ||
104 | const res = spawnSync(binaryPath, ["--version"]); | ||
105 | |||
106 | // ACHTUNG! `res` type declaration is inherently wrong, see | ||
107 | // https://github.com/DefinitelyTyped/DefinitelyTyped/issues/42221 | ||
108 | |||
109 | console.log("Checked binary availablity via --version", res); | ||
110 | console.log(binaryPath, "--version output:", res.output?.map(String)); | ||
111 | |||
112 | return res.status === 0; | ||
113 | } | ||
114 | |||
115 | function getServerVersion(storage: vscode.Memento): null | string { | ||
116 | const version = storage.get<null | string>("server-version", null); | ||
117 | console.log("Get server-version:", version); | ||
118 | return version; | ||
119 | } | ||
120 | |||
121 | async function setServerVersion(storage: vscode.Memento, version: string): Promise<void> { | ||
122 | console.log("Set server-version:", version); | ||
123 | await storage.update("server-version", version.toString()); | ||
124 | } | ||
diff --git a/editors/code/src/status_display.ts b/editors/code/src/status_display.ts index 51dbf388b..993e79d70 100644 --- a/editors/code/src/status_display.ts +++ b/editors/code/src/status_display.ts | |||
@@ -66,9 +66,9 @@ class StatusDisplay implements Disposable { | |||
66 | 66 | ||
67 | refreshLabel() { | 67 | refreshLabel() { |
68 | if (this.packageName) { | 68 | if (this.packageName) { |
69 | this.statusBarItem!.text = `${spinnerFrames[this.i]} cargo ${this.command} [${this.packageName}]`; | 69 | this.statusBarItem.text = `${spinnerFrames[this.i]} cargo ${this.command} [${this.packageName}]`; |
70 | } else { | 70 | } else { |
71 | this.statusBarItem!.text = `${spinnerFrames[this.i]} cargo ${this.command}`; | 71 | this.statusBarItem.text = `${spinnerFrames[this.i]} cargo ${this.command}`; |
72 | } | 72 | } |
73 | } | 73 | } |
74 | 74 | ||