aboutsummaryrefslogtreecommitdiff
path: root/editors/code/src/config.ts
blob: fbb7a556a86e8abfd2e16e274a5cbc68016e8ee7 (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
import * as vscode from 'vscode';
import { Env } from './client';
import { log } from "./util";

export type UpdatesChannel = "stable" | "nightly";

const NIGHTLY_TAG = "nightly";

export type RunnableEnvCfg = undefined | Record<string, string> | { mask?: string; env: Record<string, string> }[];

export class Config {
    readonly extensionId = "matklad.rust-analyzer";

    readonly rootSection = "rust-analyzer";
    private readonly requiresReloadOpts = [
        "serverPath",
        "server",
        "cargo",
        "procMacro",
        "files",
        "highlighting",
        "updates.channel",
        "lens", // works as lens.*
        "hoverActions", // works as hoverActions.*
    ]
        .map(opt => `${this.rootSection}.${opt}`);

    readonly package: {
        version: string;
        releaseTag: string | null;
        enableProposedApi: boolean | undefined;
    } = vscode.extensions.getExtension(this.extensionId)!.packageJSON;

    readonly globalStoragePath: string;

    constructor(ctx: vscode.ExtensionContext) {
        this.globalStoragePath = ctx.globalStorageUri.path;
        vscode.workspace.onDidChangeConfiguration(this.onDidChangeConfiguration, this, ctx.subscriptions);
        this.refreshLogging();
    }

    private refreshLogging() {
        log.setEnabled(this.traceExtension);
        log.info("Extension version:", this.package.version);

        const cfg = Object.entries(this.cfg).filter(([_, val]) => !(val instanceof Function));
        log.info("Using configuration", Object.fromEntries(cfg));
    }

    private async onDidChangeConfiguration(event: vscode.ConfigurationChangeEvent) {
        this.refreshLogging();

        const requiresReloadOpt = this.requiresReloadOpts.find(
            opt => event.affectsConfiguration(opt)
        );

        if (!requiresReloadOpt) return;

        const userResponse = await vscode.window.showInformationMessage(
            `Changing "${requiresReloadOpt}" requires a reload`,
            "Reload now"
        );

        if (userResponse === "Reload now") {
            await vscode.commands.executeCommand("workbench.action.reloadWindow");
        }
    }

    // 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 cfg(): vscode.WorkspaceConfiguration {
        return vscode.workspace.getConfiguration(this.rootSection);
    }

    /**
     * Beware that postfix `!` operator erases both `null` and `undefined`.
     * This is why the following doesn't work as expected:
     *
     * ```ts
     * const nullableNum = vscode
     *  .workspace
     *  .getConfiguration
     *  .getConfiguration("rust-analyer")
     *  .get<number | null>(path)!;
     *
     * // What happens is that type of `nullableNum` is `number` but not `null | number`:
     * const fullFledgedNum: number = nullableNum;
     * ```
     * So this getter handles this quirk by not requiring the caller to use postfix `!`
     */
    private get<T>(path: string): T {
        return this.cfg.get<T>(path)!;
    }

    get serverPath() {
        return this.get<null | string>("server.path") ?? this.get<null | string>("serverPath");
    }
    get serverExtraEnv() { return this.get<Env | null>("server.extraEnv") ?? {}; }
    get channel() { return this.get<UpdatesChannel>("updates.channel"); }
    get askBeforeDownload() { return this.get<boolean>("updates.askBeforeDownload"); }
    get traceExtension() { return this.get<boolean>("trace.extension"); }
    get httpProxy() {
        const httpProxy = vscode
            .workspace
            .getConfiguration('http')
            .get<null | string>("proxy")!;

        return httpProxy || process.env["https_proxy"] || process.env["HTTPS_PROXY"];
    }

    get inlayHints() {
        return {
            enable: this.get<boolean>("inlayHints.enable"),
            typeHints: this.get<boolean>("inlayHints.typeHints"),
            parameterHints: this.get<boolean>("inlayHints.parameterHints"),
            chainingHints: this.get<boolean>("inlayHints.chainingHints"),
            smallerHints: this.get<boolean>("inlayHints.smallerHints"),
            maxLength: this.get<null | number>("inlayHints.maxLength"),
        };
    }

    get checkOnSave() {
        return {
            command: this.get<string>("checkOnSave.command"),
        };
    }

    get cargoRunner() {
        return this.get<string | undefined>("cargoRunner");
    }

    get runnableEnv() {
        return this.get<RunnableEnvCfg>("runnableEnv");
    }

    get debug() {
        let sourceFileMap = this.get<Record<string, string> | "auto">("debug.sourceFileMap");
        if (sourceFileMap !== "auto") {
            // "/rustc/<id>" used by suggestions only.
            const { ["/rustc/<id>"]: _, ...trimmed } = this.get<Record<string, string>>("debug.sourceFileMap");
            sourceFileMap = trimmed;
        }

        return {
            engine: this.get<string>("debug.engine"),
            engineSettings: this.get<object>("debug.engineSettings"),
            openDebugPane: this.get<boolean>("debug.openDebugPane"),
            sourceFileMap: sourceFileMap
        };
    }

    get lens() {
        return {
            enable: this.get<boolean>("lens.enable"),
            run: this.get<boolean>("lens.run"),
            debug: this.get<boolean>("lens.debug"),
            implementations: this.get<boolean>("lens.implementations"),
            methodReferences: this.get<boolean>("lens.methodReferences"),
            references: this.get<boolean>("lens.references"),
        };
    }

    get hoverActions() {
        return {
            enable: this.get<boolean>("hoverActions.enable"),
            implementations: this.get<boolean>("hoverActions.implementations"),
            run: this.get<boolean>("hoverActions.run"),
            debug: this.get<boolean>("hoverActions.debug"),
            gotoTypeDef: this.get<boolean>("hoverActions.gotoTypeDef"),
        };
    }

    get currentExtensionIsNightly() {
        return this.package.releaseTag === NIGHTLY_TAG;
    }
}