aboutsummaryrefslogtreecommitdiff
path: root/editors/vscode/src/extension.ts
blob: 5d288bb6a5153de9b4b31ec83d07267a9a88ded6 (plain)
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
/*
    HIGHLY inspired by the wonderful rust-analyzer, and contains modification of code from rust-analyzer vscode extension.
*/

import * as vscode from 'vscode';
import * as path from "path";
import * as os from "os";
import { promises as fs, PathLike, constants, writeFileSync } from "fs";

var AdmZip = require('adm-zip');

import {
    LanguageClient,
    LanguageClientOptions,
    ServerOptions
} from 'vscode-languageclient/node';

import { log, assert, isValidExecutable } from './util';
import { RunnableCodeLensProvider } from "./run";
import { PersistentState } from './persistent_state';
import { Config } from './config';
import { fetchRelease, download } from './net';
import { getPathForExecutable, isOdinInstalled } from './toolchain';
import { Ctx } from './ctx';
import { runDebugTest, runTest } from './commands';
import { watchOlsConfigFile } from './watch';

const onDidChange: vscode.EventEmitter<void> = new vscode.EventEmitter<void>();

let ctx: Ctx;

export async function activate(context: vscode.ExtensionContext) {

    const config = new Config(context);
    const state = new PersistentState(context.globalState);

    log.setEnabled(true);

    const serverPath = await bootstrap(config, state).catch(err => {
        let message = "bootstrap error. ";

        if (err.code === "EBUSY" || err.code === "ETXTBSY" || err.code === "EPERM") {
            message += "Other vscode windows might be using ols, ";
            message += "you should close them and reload this window to retry. ";
        }

        log.error("Bootstrap error", err);
        throw new Error(message);
    });


    const workspaceFolder = vscode.workspace.workspaceFolders?.[0];

    if (workspaceFolder === undefined) {
        throw new Error("no folder is opened");
    }

    const codeLensProvider = new RunnableCodeLensProvider(
        onDidChange,
    );

    const disposable = vscode.languages.registerCodeLensProvider(
        { scheme: "file", language: "odin" },
        codeLensProvider
    );

    context.subscriptions.push(
        vscode.workspace.onDidChangeConfiguration(e => {
            codeLensProvider.updateArgs();
        })
    );

    context.subscriptions.push(disposable);
 
    if (!serverPath) {
        vscode.window.showErrorMessage("Failed to find ols executable!");
        return;
    }

    let serverOptions: ServerOptions = {
        command: serverPath,
        args: [],
        options: {
            cwd: path.dirname(serverPath),
        },
    };

    let clientOptions: LanguageClientOptions = {
        documentSelector: [{ scheme: 'file', language: 'odin' }],
        outputChannel: vscode.window.createOutputChannel("Odin Language Server")
    };

    var client = new LanguageClient(
        'ols',
        'Odin Language Server Client',
        serverOptions,
        clientOptions
    );

    ctx = await Ctx.create(config, client, context, serverPath, workspaceFolder.uri.fsPath);

    ctx.registerCommand("runDebugTest", runDebugTest);
    ctx.registerCommand("runTest", runTest);

    const olsFile = path.join(workspaceFolder.uri.fsPath, "ols.json");
    
    fs.access(olsFile, constants.F_OK).catch(async err => {
        if (err) {

            const userResponse = await vscode.window.showInformationMessage(
                "No ols config file in the workspace root folder. Do you wish to create one?",
                "Yes",
                "No"
            );

            if (userResponse === "Yes") {
                createOlsConfig(ctx);
            }

        }

        parseOlsFile(config, olsFile);
    });

    if(!isOdinInstalled()) {
        vscode.window.showErrorMessage("Odin cannot be found in your path environment. Please install Odin or add it into your path environment before going any further: [Install](https://odin-lang.org/docs/install/).");
    }

    vscode.commands.registerCommand("ols.start", () => {
        client.start();
    });

    vscode.commands.registerCommand("ols.stop", async () => {
        await client.stop();
    });

    vscode.commands.registerCommand("ols.restart", async () => {
        await client.stop();
        client.start();
    });

    vscode.commands.registerCommand("ols.createOls", async() => {
        createOlsConfig(ctx);
    });

    client.start();

    parseOlsFile(config, olsFile);
    watchOlsConfigFile(ctx, olsFile);
}

async function bootstrap(config: Config, state: PersistentState): Promise<string> {
    await fs.mkdir(config.globalStorageUri.fsPath, { recursive: true });

    const path = await bootstrapServer(config, state);

    return path;
}

async function bootstrapServer(config: Config, state: PersistentState): Promise<string> {
    const path = await getServer(config, state);
    if (!path) {
        throw new Error(
            "ols is not available. " +
            "Please, ensure its [installed](https://github.com/DanielGavin/ols/#installation)."
        );
    }

    log.info("Using server binary at", path);

    /*
        TODO(add version)
    if (!isValidExecutable(path)) {
        throw new Error(`Failed to execute ${path} --version`);
    }
    */

    return path;
}

export function createOlsConfig(ctx: Ctx) {
    const odinPath = getPathForExecutable("odin");

    const corePath = path.resolve(path.join(path.dirname(odinPath), "core"));

    const config = {
        collections: [{ name: "core", path: corePath }],
        enable_document_symbols: true,
        enable_semantic_tokens: false,
        enable_hover: true,
        enable_snippets: true
    };

    const olsPath = vscode.workspace.workspaceFolders![0].uri.fsPath;

    const edit = new vscode.WorkspaceEdit();

    const content = JSON.stringify(config, null, 4);

    writeFileSync(path.join(olsPath, "ols.json"), content);
}

export async function parseOlsFile(config: Config, file: string) {
    /*
        We have to parse the collections that they have specificed through the json(This will be changed when odin gets it's own builder files)
    */
    fs.readFile(file).then((data) => {
        const conf = JSON.parse(data.toString());
        config.collections = conf.collections;
    });
} 

function serverPath(config: Config): string | null {
    return config.serverPath;
}

async function getServer(config: Config, state: PersistentState): Promise<string | undefined> {
    const explicitPath = serverPath(config);
    if (explicitPath) {
        if (explicitPath.startsWith("~/")) {
            return os.homedir() + explicitPath.slice("~".length);
        }
        return explicitPath;
    };

    const platforms: { [key: string]: string } = {
        "x64 win32": "x86_64-pc-windows-msvc",
        "x64 linux": "x86_64-unknown-linux-gnu",
        "x64 darwin": "x86_64-darwin",
    };

    let platform = platforms[`${process.arch} ${process.platform}`];

    if (platform === undefined) {
        await vscode.window.showErrorMessage(
            "Unfortunately we don't ship binaries for your platform yet. " +
            "You need to manually clone ols, build it, set the ols.server.path to the executable"
        );
        return undefined;
    }

    /*
    if (platform === "x86_64-unknown-linux-gnu" && isMusl()) {
        platform = "x86_64-unknown-linux-musl";
    }
    */

    const ext = platform.indexOf("-windows-") !== -1 ? ".exe" : "";
    const destFolder = config.globalStorageUri.fsPath;
    const destExecutable = path.join(destFolder, `ols-${platform}${ext}`);
    
    const exists = await fs.stat(destExecutable).then(() => true, () => false);

    if (!exists) {
        await state.updateReleaseId(0);
    }

    /*
        Temp: right now it doesn't check for versions, since ols has no versioning right now
    */
    
    if (exists && state.lastCheck !== undefined && state.lastCheck + (3 * 60 * 60 * 1000)  > Date.now()) {
        return destExecutable;
    }

    const release = await downloadWithRetryDialog(state, async () => {
        return await fetchRelease("nightly", state.githubToken, config.httpProxy);
    });

    if (release === undefined || release.id === state.releaseId) {
        await state.updateLastCheck(Date.now());
        return destExecutable;
    }

    const userResponse = await vscode.window.showInformationMessage(
        "New version of ols (nightly) is available (requires reload).",
        "Update"
    );

    if (userResponse !== "Update") {
        return destExecutable;
    }

    const artifact = release.assets.find(artifact => artifact.name === `ols-${platform}.zip`);
    assert(!!artifact, `Bad release: ${JSON.stringify(release)}`);
    
    const destZip = path.join(destFolder, `ols-${platform}.zip`);

    await downloadWithRetryDialog(state, async () => {
        await download({
            url: artifact.browser_download_url,
            dest: destZip,
            progressTitle: "Downloading ols",
            httpProxy: config.httpProxy,
        });
    });

    var zip = new AdmZip(destZip);

    zip.extractAllTo(destFolder, true);

    if (ext !== ".exe") {
        fs.chmod(destExecutable, 0o755);
    }

    await state.updateServerVersion(config.package.version);
    await state.updateReleaseId(release.id);
    await state.updateLastCheck(Date.now());
    await vscode.commands.executeCommand("workbench.action.reloadWindow");

    return destExecutable;
}

async function downloadWithRetryDialog<T>(state: PersistentState, downloadFunc: () => Promise<T>): Promise<T> {
    while (true) {
        try {
            return await downloadFunc();
        } catch (e) {
            const selected = await vscode.window.showErrorMessage("Failed to download: " + e.message, {}, {
                title: "Update Github Auth Token",
                updateToken: true,
            }, {
                title: "Retry download",
                retry: true,
            }, {
                title: "Dismiss",
            });

            if (selected?.updateToken) {
                await queryForGithubToken(state);
                continue;
            } else if (selected?.retry) {
                continue;
            }
            throw e;
        };
    }
}

async function queryForGithubToken(state: PersistentState): Promise<void> {
    const githubTokenOptions: vscode.InputBoxOptions = {
        value: state.githubToken,
        password: true,
        prompt: `
            This dialog allows to store a Github authorization token.
            The usage of an authorization token will increase the rate
            limit on the use of Github APIs and can thereby prevent getting
            throttled.
            Auth tokens can be created at https://github.com/settings/tokens`,
    };

    const newToken = await vscode.window.showInputBox(githubTokenOptions);
    if (newToken === undefined) {
        // The user aborted the dialog => Do not update the stored token
        return;
    }

    if (newToken === "") {
        log.info("Clearing github token");
        await state.updateGithubToken(undefined);
    } else {
        log.info("Storing new github token");
        await state.updateGithubToken(newToken);
    }
}

export function deactivate(): Thenable<void> {
    return ctx!.client.stop();
}