3534: Feature: vscode impl nightlies download and installation r=Veetaha a=Veetaha

I need to test things more, but the core shape of the code is quite well-formed.
The main problem is that we save the release date only for nightlies and there are no means to get the release date of the stable extension (i.e. for this we would need to consult the github releases via a network request, or we would need to somehow save this info into package.json or any other file accessible from the extension code during the deployment step, but this will be very hard I guess).
So there is an invariant that the users can install nightly only from our extension and they can't do it manually, because when installing the nightly `.vsix` we actually save its release date to `globalState`

Closes: #3402

TODO:
- [x] More manual tests and documentation

cc @matklad @lnicola 

Co-authored-by: Veetaha <gerzoh1@gmail.com>
Co-authored-by: Veetaha <veetaha2@gmail.com>
This commit is contained in:
bors[bot] 2020-03-16 10:26:31 +00:00 committed by GitHub
commit 200c275c2e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
13 changed files with 454 additions and 147 deletions

View file

@ -65,6 +65,25 @@ Note that we only support the latest version of VS Code.
The extension will be updated automatically as new versions become available. It will ask your permission to download the matching language server version binary if needed.
===== Nightly
We ship nightly releases for VS Code. To help us out with testing the newest code and follow the bleeding edge of our `master`, please use the following config:
[source,json]
----
{ "rust-analyzer.updates.channel": "nightly" }
----
You will be prompted to install the `nightly` extension version. Just click `Download now` and from that moment you will get automatic updates each 24 hours.
If you don't want to be asked for `Download now` every day when the new nightly version is released add the following to your `settings.json`:
[source,json]
----
{ "rust-analyzer.updates.askBeforeDownload": false }
----
NOTE: Nightly extension should **only** be installed via the `Download now` action from VS Code.
==== Building From Source
Alternatively, both the server and the plugin can be installed from source:

View file

@ -1,6 +1,6 @@
{
"name": "rust-analyzer",
"version": "0.2.20200211-dev",
"version": "0.2.20200309-nightly",
"lockfileVersion": 1,
"requires": true,
"dependencies": {

View file

@ -6,7 +6,7 @@
"private": true,
"icon": "icon.png",
"//": "The real version is in release.yaml, this one just needs to be bigger",
"version": "0.2.20200211-dev",
"version": "0.2.20200309-nightly",
"publisher": "matklad",
"repository": {
"url": "https://github.com/rust-analyzer/rust-analyzer.git",
@ -219,6 +219,19 @@
}
}
},
"rust-analyzer.updates.channel": {
"type": "string",
"enum": [
"stable",
"nightly"
],
"default": "stable",
"markdownEnumDescriptions": [
"`\"stable\"` updates are shipped weekly, they don't contain cutting-edge features from VSCode proposed APIs but have less bugs in general",
"`\"nightly\"` updates are shipped daily, they contain cutting-edge features and latest bug fixes. These releases help us get your feedback very quickly and speed up rust-analyzer development **drastically**"
],
"markdownDescription": "Choose `\"nightly\"` updates to get the latest features and bug fixes every day. While `\"stable\"` releases occur weekly and don't contain cutting-edge features from VSCode proposed APIs"
},
"rust-analyzer.updates.askBeforeDownload": {
"type": "boolean",
"default": true,
@ -235,7 +248,7 @@
"string"
],
"default": null,
"description": "Path to rust-analyzer executable (points to bundled binary by default)"
"description": "Path to rust-analyzer executable (points to bundled binary by default). If this is set, then \"rust-analyzer.updates.channel\" setting is not used"
},
"rust-analyzer.excludeGlobs": {
"type": "array",

View file

@ -5,7 +5,7 @@ import { spawnSync } from 'child_process';
export function serverVersion(ctx: Ctx): Cmd {
return async () => {
const binaryPath = await ensureServerBinary(ctx.config.serverSource);
const binaryPath = await ensureServerBinary(ctx.config);
if (binaryPath == null) {
throw new Error(
@ -18,4 +18,3 @@ export function serverVersion(ctx: Ctx): Cmd {
vscode.window.showInformationMessage('rust-analyzer version : ' + version);
};
}

View file

@ -1,7 +1,7 @@
import * as os from "os";
import * as vscode from 'vscode';
import { ArtifactSource } from "./installation/interfaces";
import { log } from "./util";
import { log, vscodeReloadWindow } from "./util";
const RA_LSP_DEBUG = process.env.__RA_LSP_SERVER_DEBUG;
@ -23,25 +23,40 @@ export interface CargoFeatures {
allFeatures: boolean;
features: string[];
}
export const enum UpdatesChannel {
Stable = "stable",
Nightly = "nightly"
}
export const NIGHTLY_TAG = "nightly";
export class Config {
private static readonly rootSection = "rust-analyzer";
private static readonly requiresReloadOpts = [
readonly extensionId = "matklad.rust-analyzer";
private readonly rootSection = "rust-analyzer";
private readonly requiresReloadOpts = [
"serverPath",
"cargoFeatures",
"cargo-watch",
"highlighting.semanticTokens",
"inlayHints",
]
.map(opt => `${Config.rootSection}.${opt}`);
.map(opt => `${this.rootSection}.${opt}`);
private static readonly extensionVersion: string = (() => {
const packageJsonVersion = vscode
.extensions
.getExtension("matklad.rust-analyzer")!
.packageJSON
.version as string; // n.n.YYYYMMDD
readonly packageJsonVersion = vscode
.extensions
.getExtension(this.extensionId)!
.packageJSON
.version as string; // n.n.YYYYMMDD[-nightly]
/**
* Either `nightly` or `YYYY-MM-DD` (i.e. `stable` release)
*/
readonly extensionReleaseTag: string = (() => {
if (this.packageJsonVersion.endsWith(NIGHTLY_TAG)) return NIGHTLY_TAG;
const realVersionRegexp = /^\d+\.\d+\.(\d{4})(\d{2})(\d{2})/;
const [, yyyy, mm, dd] = packageJsonVersion.match(realVersionRegexp)!;
const [, yyyy, mm, dd] = this.packageJsonVersion.match(realVersionRegexp)!;
return `${yyyy}-${mm}-${dd}`;
})();
@ -54,16 +69,19 @@ export class Config {
}
private refreshConfig() {
this.cfg = vscode.workspace.getConfiguration(Config.rootSection);
this.cfg = vscode.workspace.getConfiguration(this.rootSection);
const enableLogging = this.cfg.get("trace.extension") as boolean;
log.setEnabled(enableLogging);
log.debug("Using configuration:", this.cfg);
log.debug(
"Extension version:", this.packageJsonVersion,
"using configuration:", this.cfg
);
}
private async onConfigChange(event: vscode.ConfigurationChangeEvent) {
this.refreshConfig();
const requiresReloadOpt = Config.requiresReloadOpts.find(
const requiresReloadOpt = this.requiresReloadOpts.find(
opt => event.affectsConfiguration(opt)
);
@ -75,7 +93,7 @@ export class Config {
);
if (userResponse === "Reload now") {
vscode.commands.executeCommand("workbench.action.reloadWindow");
await vscodeReloadWindow();
}
}
@ -121,8 +139,14 @@ export class Config {
}
}
get installedExtensionUpdateChannel(): UpdatesChannel {
return this.extensionReleaseTag === NIGHTLY_TAG
? UpdatesChannel.Nightly
: UpdatesChannel.Stable;
}
get serverSource(): null | ArtifactSource {
const serverPath = RA_LSP_DEBUG ?? this.cfg.get<null | string>("serverPath");
const serverPath = RA_LSP_DEBUG ?? this.serverPath;
if (serverPath) {
return {
@ -135,13 +159,18 @@ export class Config {
if (!prebuiltBinaryName) return null;
return this.createGithubReleaseSource(
prebuiltBinaryName,
this.extensionReleaseTag
);
}
private createGithubReleaseSource(file: string, tag: string): ArtifactSource.GithubRelease {
return {
type: ArtifactSource.Type.GithubRelease,
file,
tag,
dir: this.ctx.globalStoragePath,
file: prebuiltBinaryName,
storage: this.ctx.globalState,
tag: Config.extensionVersion,
askBeforeDownload: this.cfg.get("updates.askBeforeDownload") as boolean,
repo: {
name: "rust-analyzer",
owner: "rust-analyzer",
@ -149,9 +178,23 @@ export class Config {
};
}
get nightlyVsixSource(): ArtifactSource.GithubRelease {
return this.createGithubReleaseSource("rust-analyzer.vsix", NIGHTLY_TAG);
}
readonly installedNightlyExtensionReleaseDate = new DateStorage(
"installed-nightly-extension-release-date",
this.ctx.globalState
);
readonly serverReleaseDate = new DateStorage("server-release-date", this.ctx.globalState);
readonly serverReleaseTag = new Storage<null | string>("server-release-tag", this.ctx.globalState, null);
// We don't do runtime config validation here for simplicity. More on stackoverflow:
// https://stackoverflow.com/questions/60135780/what-is-the-best-way-to-type-check-the-configuration-for-vscode-extension
private get serverPath() { return this.cfg.get("serverPath") as null | string; }
get updatesChannel() { return this.cfg.get("updates.channel") as UpdatesChannel; }
get askBeforeDownload() { return this.cfg.get("updates.askBeforeDownload") as boolean; }
get highlightingSemanticTokens() { return this.cfg.get("highlighting.semanticTokens") as boolean; }
get highlightingOn() { return this.cfg.get("highlightingOn") as boolean; }
get rainbowHighlightingOn() { return this.cfg.get("rainbowHighlightingOn") as boolean; }
@ -189,3 +232,37 @@ export class Config {
// for internal use
get withSysroot() { return this.cfg.get("withSysroot", true) as boolean; }
}
export class Storage<T> {
constructor(
private readonly key: string,
private readonly storage: vscode.Memento,
private readonly defaultVal: T
) { }
get(): T {
const val = this.storage.get(this.key, this.defaultVal);
log.debug(this.key, "==", val);
return val;
}
async set(val: T) {
log.debug(this.key, "=", val);
await this.storage.update(this.key, val);
}
}
export class DateStorage {
inner: Storage<null | string>;
constructor(key: string, storage: vscode.Memento) {
this.inner = new Storage(key, storage, null);
}
get(): null | Date {
const dateStr = this.inner.get();
return dateStr ? new Date(dateStr) : null;
}
async set(date: null | Date) {
await this.inner.set(date ? date.toString() : null);
}
}

View file

@ -1,50 +0,0 @@
import * as vscode from "vscode";
import * as path from "path";
import { promises as fs } from "fs";
import { ArtifactReleaseInfo } from "./interfaces";
import { downloadFile } from "./download_file";
import { assert } from "../util";
/**
* Downloads artifact from given `downloadUrl`.
* Creates `installationDir` if it is not yet created and put the artifact under
* `artifactFileName`.
* Displays info about the download progress in an info message printing the name
* of the artifact as `displayName`.
*/
export async function downloadArtifact(
{ downloadUrl, releaseName }: ArtifactReleaseInfo,
artifactFileName: string,
installationDir: string,
displayName: string,
) {
await fs.mkdir(installationDir).catch(err => assert(
err?.code === "EEXIST",
`Couldn't create directory "${installationDir}" to download ` +
`${artifactFileName} artifact: ${err?.message}`
));
const installationPath = path.join(installationDir, artifactFileName);
await vscode.window.withProgress(
{
location: vscode.ProgressLocation.Notification,
cancellable: false, // FIXME: add support for canceling download?
title: `Downloading ${displayName} (${releaseName})`
},
async (progress, _cancellationToken) => {
let lastPrecentage = 0;
const filePermissions = 0o755; // (rwx, r_x, r_x)
await downloadFile(downloadUrl, installationPath, filePermissions, (readBytes, totalBytes) => {
const newPercentage = (readBytes / totalBytes) * 100;
progress.report({
message: newPercentage.toFixed(0) + "%",
increment: newPercentage - lastPrecentage
});
lastPrecentage = newPercentage;
});
}
);
}

View file

@ -1,8 +1,11 @@
import fetch from "node-fetch";
import * as vscode from "vscode";
import * as path from "path";
import * as fs from "fs";
import * as stream from "stream";
import * as util from "util";
import { log, assert } from "../util";
import { ArtifactReleaseInfo } from "./interfaces";
const pipeline = util.promisify(stream.pipeline);
@ -49,3 +52,46 @@ export async function downloadFile(
// Issue at nodejs repo: https://github.com/nodejs/node/issues/31776
});
}
/**
* Downloads artifact from given `downloadUrl`.
* Creates `installationDir` if it is not yet created and puts the artifact under
* `artifactFileName`.
* Displays info about the download progress in an info message printing the name
* of the artifact as `displayName`.
*/
export async function downloadArtifactWithProgressUi(
{ downloadUrl, releaseName }: ArtifactReleaseInfo,
artifactFileName: string,
installationDir: string,
displayName: string,
) {
await fs.promises.mkdir(installationDir).catch(err => assert(
err?.code === "EEXIST",
`Couldn't create directory "${installationDir}" to download ` +
`${artifactFileName} artifact: ${err?.message}`
));
const installationPath = path.join(installationDir, artifactFileName);
await vscode.window.withProgress(
{
location: vscode.ProgressLocation.Notification,
cancellable: false, // FIXME: add support for canceling download?
title: `Downloading rust-analyzer ${displayName} (${releaseName})`
},
async (progress, _cancellationToken) => {
let lastPrecentage = 0;
const filePermissions = 0o755; // (rwx, r_x, r_x)
await downloadFile(downloadUrl, installationPath, filePermissions, (readBytes, totalBytes) => {
const newPercentage = (readBytes / totalBytes) * 100;
progress.report({
message: newPercentage.toFixed(0) + "%",
increment: newPercentage - lastPrecentage
});
lastPrecentage = newPercentage;
});
}
);
}

View file

@ -0,0 +1,144 @@
import * as vscode from "vscode";
import * as path from "path";
import { promises as fs } from 'fs';
import { vscodeReinstallExtension, vscodeReloadWindow, log, vscodeInstallExtensionFromVsix, assert, notReentrant } from "../util";
import { Config, UpdatesChannel } from "../config";
import { ArtifactReleaseInfo, ArtifactSource } from "./interfaces";
import { downloadArtifactWithProgressUi } from "./downloads";
import { fetchArtifactReleaseInfo } from "./fetch_artifact_release_info";
const HEURISTIC_NIGHTLY_RELEASE_PERIOD_IN_HOURS = 25;
/**
* Installs `stable` or latest `nightly` version or does nothing if the current
* extension version is what's needed according to `desiredUpdateChannel`.
*/
export async function ensureProperExtensionVersion(config: Config): Promise<never | void> {
// User has built lsp server from sources, she should manage updates manually
if (config.serverSource?.type === ArtifactSource.Type.ExplicitPath) return;
const currentUpdChannel = config.installedExtensionUpdateChannel;
const desiredUpdChannel = config.updatesChannel;
if (currentUpdChannel === UpdatesChannel.Stable) {
// Release date is present only when we are on nightly
await config.installedNightlyExtensionReleaseDate.set(null);
}
if (desiredUpdChannel === UpdatesChannel.Stable) {
// VSCode should handle updates for stable channel
if (currentUpdChannel === UpdatesChannel.Stable) return;
if (!await askToDownloadProperExtensionVersion(config)) return;
await vscodeReinstallExtension(config.extensionId);
await vscodeReloadWindow(); // never returns
}
if (currentUpdChannel === UpdatesChannel.Stable) {
if (!await askToDownloadProperExtensionVersion(config)) return;
return await tryDownloadNightlyExtension(config);
}
const currentExtReleaseDate = config.installedNightlyExtensionReleaseDate.get();
if (currentExtReleaseDate === null) {
void vscode.window.showErrorMessage(
"Nightly release date must've been set during the installation. " +
"Did you download and install the nightly .vsix package manually?"
);
throw new Error("Nightly release date was not set in globalStorage");
}
const dateNow = new Date;
const hoursSinceLastUpdate = diffInHours(currentExtReleaseDate, dateNow);
log.debug(
"Current rust-analyzer nightly was downloaded", hoursSinceLastUpdate,
"hours ago, namely:", currentExtReleaseDate, "and now is", dateNow
);
if (hoursSinceLastUpdate < HEURISTIC_NIGHTLY_RELEASE_PERIOD_IN_HOURS) {
return;
}
if (!await askToDownloadProperExtensionVersion(config, "The installed nightly version is most likely outdated. ")) {
return;
}
await tryDownloadNightlyExtension(config, releaseInfo => {
assert(
currentExtReleaseDate.getTime() === config.installedNightlyExtensionReleaseDate.get()?.getTime(),
"Other active VSCode instance has reinstalled the extension"
);
if (releaseInfo.releaseDate.getTime() === currentExtReleaseDate.getTime()) {
vscode.window.showInformationMessage(
"Whoops, it appears that your nightly version is up-to-date. " +
"There might be some problems with the upcomming nightly release " +
"or you traveled too far into the future. Sorry for that 😅! "
);
return false;
}
return true;
});
}
async function askToDownloadProperExtensionVersion(config: Config, reason = "") {
if (!config.askBeforeDownload) return true;
const stableOrNightly = config.updatesChannel === UpdatesChannel.Stable ? "stable" : "latest nightly";
// In case of reentering this function and showing the same info message
// (e.g. after we had shown this message, the user changed the config)
// vscode will dismiss the already shown one (i.e. return undefined).
// This behaviour is what we want, but likely it is not documented
const userResponse = await vscode.window.showInformationMessage(
reason + `Do you want to download the ${stableOrNightly} rust-analyzer extension ` +
`version and reload the window now?`,
"Download now", "Cancel"
);
return userResponse === "Download now";
}
/**
* Shutdowns the process in case of success (i.e. reloads the window) or throws an error.
*
* ACHTUNG!: this function has a crazy amount of state transitions, handling errors during
* each of them would result in a ton of code (especially accounting for cross-process
* shared mutable `globalState` access). Enforcing no reentrancy for this is best-effort.
*/
const tryDownloadNightlyExtension = notReentrant(async (
config: Config,
shouldDownload: (releaseInfo: ArtifactReleaseInfo) => boolean = () => true
): Promise<never | void> => {
const vsixSource = config.nightlyVsixSource;
try {
const releaseInfo = await fetchArtifactReleaseInfo(vsixSource.repo, vsixSource.file, vsixSource.tag);
if (!shouldDownload(releaseInfo)) return;
await downloadArtifactWithProgressUi(releaseInfo, vsixSource.file, vsixSource.dir, "nightly extension");
const vsixPath = path.join(vsixSource.dir, vsixSource.file);
await vscodeInstallExtensionFromVsix(vsixPath);
await config.installedNightlyExtensionReleaseDate.set(releaseInfo.releaseDate);
await fs.unlink(vsixPath);
await vscodeReloadWindow(); // never returns
} catch (err) {
log.downloadError(err, "nightly extension", vsixSource.repo.name);
}
});
function diffInHours(a: Date, b: Date): number {
// Discard the time and time-zone information (to abstract from daylight saving time bugs)
// https://stackoverflow.com/a/15289883/9259330
const utcA = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
const utcB = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());
return (utcA - utcB) / (1000 * 60 * 60);
}

View file

@ -59,12 +59,15 @@ export async function fetchArtifactReleaseInfo(
return {
releaseName: release.name,
releaseDate: new Date(release.published_at),
downloadUrl: artifact.browser_download_url
};
// We omit declaration of tremendous amount of fields that we are not using here
interface GithubRelease {
name: string;
// eslint-disable-next-line camelcase
published_at: string;
assets: Array<{
name: string;
// eslint-disable-next-line camelcase

View file

@ -1,5 +1,3 @@
import * as vscode from "vscode";
export interface GithubRepo {
name: string;
owner: string;
@ -9,6 +7,7 @@ export interface GithubRepo {
* Metadata about particular artifact retrieved from GitHub releases.
*/
export interface ArtifactReleaseInfo {
releaseDate: Date;
releaseName: string;
downloadUrl: string;
}
@ -42,6 +41,9 @@ export namespace ArtifactSource {
*/
repo: GithubRepo;
// FIXME: add installationPath: string;
/**
* Directory on the filesystem where the bundled binary is stored.
*/
@ -57,17 +59,5 @@ export namespace ArtifactSource {
* Tag of github release that denotes a version required by this extension.
*/
tag: string;
/**
* Object that provides `get()/update()` operations to store metadata
* about the actual binary, e.g. its actual version.
*/
storage: vscode.Memento;
/**
* Ask for the user permission before downloading the artifact.
*/
askBeforeDownload: boolean;
}
}

View file

@ -1,14 +1,16 @@
import * as vscode from "vscode";
import * as path from "path";
import { promises as dns } from "dns";
import { spawnSync } from "child_process";
import { ArtifactSource } from "./interfaces";
import { fetchArtifactReleaseInfo } from "./fetch_artifact_release_info";
import { downloadArtifact } from "./download_artifact";
import { log, assert } from "../util";
import { downloadArtifactWithProgressUi } from "./downloads";
import { log, assert, notReentrant } from "../util";
import { Config, NIGHTLY_TAG } from "../config";
export async function ensureServerBinary(config: Config): Promise<null | string> {
const source = config.serverSource;
export async function ensureServerBinary(source: null | ArtifactSource): Promise<null | string> {
if (!source) {
vscode.window.showErrorMessage(
"Unfortunately we don't ship binaries for your platform yet. " +
@ -35,18 +37,11 @@ export async function ensureServerBinary(source: null | ArtifactSource): Promise
return null;
}
case ArtifactSource.Type.GithubRelease: {
const prebuiltBinaryPath = path.join(source.dir, source.file);
const installedVersion: null | string = getServerVersion(source.storage);
const requiredVersion: string = source.tag;
log.debug("Installed version:", installedVersion, "required:", requiredVersion);
if (isBinaryAvailable(prebuiltBinaryPath) && installedVersion === requiredVersion) {
return prebuiltBinaryPath;
if (!shouldDownloadServer(source, config)) {
return path.join(source.dir, source.file);
}
if (source.askBeforeDownload) {
if (config.askBeforeDownload) {
const userResponse = await vscode.window.showInformationMessage(
`Language server version ${source.tag} for rust-analyzer is not installed. ` +
"Do you want to download it now?",
@ -55,38 +50,56 @@ export async function ensureServerBinary(source: null | ArtifactSource): Promise
if (userResponse !== "Download now") return null;
}
if (!await downloadServer(source)) return null;
return prebuiltBinaryPath;
return await downloadServer(source, config);
}
}
}
async function downloadServer(source: ArtifactSource.GithubRelease): Promise<boolean> {
function shouldDownloadServer(
source: ArtifactSource.GithubRelease,
config: Config
): boolean {
if (!isBinaryAvailable(path.join(source.dir, source.file))) return true;
const installed = {
tag: config.serverReleaseTag.get(),
date: config.serverReleaseDate.get()
};
const required = {
tag: source.tag,
date: config.installedNightlyExtensionReleaseDate.get()
};
log.debug("Installed server:", installed, "required:", required);
if (required.tag !== NIGHTLY_TAG || installed.tag !== NIGHTLY_TAG) {
return required.tag !== installed.tag;
}
assert(required.date !== null, "Extension release date should have been saved during its installation");
assert(installed.date !== null, "Server release date should have been saved during its installation");
return installed.date.getTime() !== required.date.getTime();
}
/**
* Enforcing no reentrancy for this is best-effort.
*/
const downloadServer = notReentrant(async (
source: ArtifactSource.GithubRelease,
config: Config,
): Promise<null | string> => {
try {
const releaseInfo = await fetchArtifactReleaseInfo(source.repo, source.file, source.tag);
await downloadArtifact(releaseInfo, source.file, source.dir, "language server");
await setServerVersion(source.storage, releaseInfo.releaseName);
await downloadArtifactWithProgressUi(releaseInfo, source.file, source.dir, "language server");
await Promise.all([
config.serverReleaseTag.set(releaseInfo.releaseName),
config.serverReleaseDate.set(releaseInfo.releaseDate)
]);
} catch (err) {
vscode.window.showErrorMessage(
`Failed to download language server from ${source.repo.name} ` +
`GitHub repository: ${err.message}`
);
log.error(err);
dns.resolve('example.com').then(
addrs => log.debug("DNS resolution for example.com was successful", addrs),
err => {
log.error(
"DNS resolution for example.com failed, " +
"there might be an issue with Internet availability"
);
log.error(err);
}
);
return false;
log.downloadError(err, "language server", source.repo.name);
return null;
}
const binaryPath = path.join(source.dir, source.file);
@ -101,8 +114,8 @@ async function downloadServer(source: ArtifactSource.GithubRelease): Promise<boo
"Rust analyzer language server was successfully installed 🦀"
);
return true;
}
return binaryPath;
});
function isBinaryAvailable(binaryPath: string): boolean {
const res = spawnSync(binaryPath, ["--version"]);
@ -115,14 +128,3 @@ function isBinaryAvailable(binaryPath: string): boolean {
return res.status === 0;
}
function getServerVersion(storage: vscode.Memento): null | string {
const version = storage.get<null | string>("server-version", null);
log.debug("Get server-version:", version);
return version;
}
async function setServerVersion(storage: vscode.Memento, version: string): Promise<void> {
log.debug("Set server-version:", version);
await storage.update("server-version", version.toString());
}

View file

@ -8,6 +8,7 @@ import { activateHighlighting } from './highlighting';
import { ensureServerBinary } from './installation/server';
import { Config } from './config';
import { log } from './util';
import { ensureProperExtensionVersion } from './installation/extension';
let ctx: Ctx | undefined;
@ -34,7 +35,13 @@ export async function activate(context: vscode.ExtensionContext) {
const config = new Config(context);
const serverPath = await ensureServerBinary(config.serverSource);
vscode.workspace.onDidChangeConfiguration(() => ensureProperExtensionVersion(config).catch(log.error));
// Don't await the user response here, otherwise we will block the lsp server bootstrap
void ensureProperExtensionVersion(config).catch(log.error);
const serverPath = await ensureServerBinary(config);
if (serverPath == null) {
throw new Error(
"Rust Analyzer Language Server is not available. " +

View file

@ -1,5 +1,6 @@
import * as lc from "vscode-languageclient";
import * as vscode from "vscode";
import { promises as dns } from "dns";
import { strict as nativeAssert } from "assert";
export function assert(condition: boolean, explanation: string): asserts condition {
@ -11,21 +12,40 @@ export function assert(condition: boolean, explanation: string): asserts conditi
}
}
export const log = {
enabled: true,
export const log = new class {
private enabled = true;
setEnabled(yes: boolean): void {
log.enabled = yes;
}
debug(message?: any, ...optionalParams: any[]): void {
if (!log.enabled) return;
// eslint-disable-next-line no-console
console.log(message, ...optionalParams);
},
}
error(message?: any, ...optionalParams: any[]): void {
if (!log.enabled) return;
debugger;
// eslint-disable-next-line no-console
console.error(message, ...optionalParams);
},
setEnabled(yes: boolean): void {
log.enabled = yes;
}
downloadError(err: Error, artifactName: string, repoName: string) {
vscode.window.showErrorMessage(
`Failed to download the rust-analyzer ${artifactName} from ${repoName} ` +
`GitHub repository: ${err.message}`
);
log.error(err);
dns.resolve('example.com').then(
addrs => log.debug("DNS resolution for example.com was successful", addrs),
err => log.error(
"DNS resolution for example.com failed, " +
"there might be an issue with Internet availability",
err
)
);
}
};
@ -66,6 +86,17 @@ function sleep(ms: number) {
return new Promise(resolve => setTimeout(resolve, ms));
}
export function notReentrant<TThis, TParams extends any[], TRet>(
fn: (this: TThis, ...params: TParams) => Promise<TRet>
): typeof fn {
let entered = false;
return function(...params) {
assert(!entered, `Reentrancy invariant for ${fn.name} is violated`);
entered = true;
return fn.apply(this, params).finally(() => entered = false);
};
}
export type RustDocument = vscode.TextDocument & { languageId: "rust" };
export type RustEditor = vscode.TextEditor & { document: RustDocument; id: string };
@ -79,3 +110,29 @@ export function isRustDocument(document: vscode.TextDocument): document is RustD
export function isRustEditor(editor: vscode.TextEditor): editor is RustEditor {
return isRustDocument(editor.document);
}
/**
* @param extensionId The canonical extension identifier in the form of: `publisher.name`
*/
export async function vscodeReinstallExtension(extensionId: string) {
// Unfortunately there is no straightforward way as of now, these commands
// were found in vscode source code.
log.debug("Uninstalling extension", extensionId);
await vscode.commands.executeCommand("workbench.extensions.uninstallExtension", extensionId);
log.debug("Installing extension", extensionId);
await vscode.commands.executeCommand("workbench.extensions.installExtension", extensionId);
}
export async function vscodeReloadWindow(): Promise<never> {
await vscode.commands.executeCommand("workbench.action.reloadWindow");
assert(false, "unreachable");
}
export async function vscodeInstallExtensionFromVsix(vsixPath: string) {
await vscode.commands.executeCommand(
"workbench.extensions.installExtension",
vscode.Uri.file(vsixPath)
);
}