-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
extension.ts
293 lines (255 loc) · 7.26 KB
/
extension.ts
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
import * as vscode from "vscode";
import * as os from "os";
import * as path from "path";
import * as fs from "fs";
import * as fsp from "fs/promises";
import fetch from "node-fetch";
import {
LanguageClient,
LanguageClientOptions,
ServerOptions,
StreamInfo,
} from "vscode-languageclient/node";
let credoClient: LanguageClient;
let nextLSClient: LanguageClient;
async function latestRelease(project: string): Promise<string> {
return fetch(
`https://api.github.com/repos/elixir-tools/${project}/releases/latest`,
{
headers: {
["X-GitHub-Api-Version"]: "2022-11-28",
["Accept"]: "application/vnd.github+json",
},
}
)
.then((x) => x.json())
.then((x: any): string => x.tag_name.replace(/^v/, ""));
}
async function activateCredo(
context: vscode.ExtensionContext,
mixfile: vscode.Uri
) {
let config = vscode.workspace.getConfiguration("elixir-tools.credo");
let text = await vscode.workspace.fs.readFile(mixfile);
if (text.toString().includes("{:credo")) {
if (config.get("enable")) {
let serverOptions: ServerOptions;
switch (config.get("adapter")) {
case "stdio":
let version = config.get("version");
if (version === "latest") {
version = await latestRelease("credo-language-server");
}
serverOptions = {
options: {
env: Object.assign({}, process.env, {
["CREDO_LSP_VERSION"]: version,
}),
},
command: context.asAbsolutePath("./bin/credo-language-server"),
args: ["--stdio"],
};
break;
case "tcp":
serverOptions = () => {
// Connect to language server via socket
let socket = require("net").connect({
host: "127.0.0.1",
port: config.get("port"),
});
let result: StreamInfo = {
writer: socket,
reader: socket,
};
return Promise.resolve(result);
};
break;
default:
throw new Error("boom");
}
const clientOptions: LanguageClientOptions = {
documentSelector: [{ scheme: "file", language: "elixir" }],
};
credoClient = new LanguageClient(
"elixir-tools.credo",
"Credo",
serverOptions,
clientOptions
);
// Start the credoClient. This will also launch the server
credoClient.start();
}
}
}
async function activateNextLS(
context: vscode.ExtensionContext,
_mixfile: vscode.Uri
) {
let config = vscode.workspace.getConfiguration("elixir-tools.nextls");
const command = "elixir-tools.uninstall-nextls";
const uninstallNextLS = async () => {
let cacheDir: string = config.get("installationDirectory")!;
if (cacheDir[0] === "~") {
cacheDir = path.join(os.homedir(), cacheDir.slice(1));
}
const bin = path.join(cacheDir, "nextls");
await fsp
.rm(bin)
.then(
async () =>
await vscode.window.showInformationMessage(
`Uninstalled Next LS from ${bin}`
)
)
.catch(
async () =>
await vscode.window.showErrorMessage(
`Failed to uninstall Next LS from ${bin}`
)
);
};
context.subscriptions.push(
vscode.commands.registerCommand(command, uninstallNextLS)
);
if (config.get("enable")) {
let serverOptions: ServerOptions;
switch (config.get("adapter")) {
case "stdio":
let cacheDir: string = config.get("installationDirectory")!;
if (cacheDir[0] === "~") {
cacheDir = path.join(os.homedir(), cacheDir.slice(1));
}
const command = await ensureNextLSDownloaded(cacheDir, {
force: false,
});
serverOptions = {
options: {
env: Object.assign({}, process.env, {
["NEXTLS_AUTO_UPDATE"]: true,
}),
},
command,
args: ["--stdio"],
};
break;
case "tcp":
serverOptions = () => {
// Connect to language server via socket
let socket = require("net").connect({
host: "127.0.0.1",
port: config.get("port"),
});
let result: StreamInfo = {
writer: socket,
reader: socket,
};
return Promise.resolve(result);
};
break;
default:
throw new Error("boom");
}
const clientOptions: LanguageClientOptions = {
documentSelector: [
{ scheme: "file", language: "elixir" },
{ scheme: "file", language: "surface" },
{ scheme: "file", language: "phoenix-heex" },
],
};
nextLSClient = new LanguageClient(
"elixir-tools.nextls",
"NextLS",
serverOptions,
clientOptions
);
// Start the nextLSClient. This will also launch the server
nextLSClient.start();
}
}
export async function activate(context: vscode.ExtensionContext) {
let files = await vscode.workspace.findFiles("mix.exs");
if (files[0]) {
await activateCredo(context, files[0]);
await activateNextLS(context, files[0]);
}
}
export function deactivate() {
if (!credoClient && !nextLSClient) {
return undefined;
}
if (credoClient) {
credoClient.stop();
}
if (nextLSClient) {
nextLSClient.stop();
}
return true;
}
async function ensureNextLSDownloaded(
cacheDir: string,
opts: { force?: boolean } = {}
): Promise<string> {
const bin = path.join(cacheDir, "nextls");
const shouldDownload = opts.force || (await isBinaryMissing(bin));
if (shouldDownload) {
await fsp.mkdir(cacheDir, { recursive: true });
const arch = getArch();
const platform = getPlatform();
const url = `https://github.com/elixir-tools/next-ls/releases/latest/download/next_ls_${platform}_${arch}`;
const shouldInstall = await vscode.window.showInformationMessage(
"Install Next LS?",
{ modal: true, detail: `Downloading to '${cacheDir}'` },
"Yes"
);
if (shouldInstall !== "Yes") {
throw new Error("Could not activate Next LS");
}
await fetch(url).then((res) => {
if (res.ok) {
return new Promise((resolve, reject) => {
const file = fs.createWriteStream(bin);
res.body?.pipe(file);
file.on("close", resolve);
file.on("error", reject);
})
.then(() => console.log("Downloaded NextLS!!"))
.catch(() => console.log("Failed to download NextLS!!"));
} else {
throw new Error(`Download failed (${url}, status=${res.status})`);
}
});
await fsp.chmod(bin, "755");
}
return bin;
}
async function isBinaryMissing(bin: string) {
try {
await fsp.access(bin, fs.constants.X_OK);
return false;
} catch {
return true;
}
}
function getArch() {
const arch = os.arch();
switch (arch) {
case "x64":
return "amd64";
case "arm64":
return "arm64";
default:
throw new Error(`Unsupported architecture: ${arch}`);
}
}
function getPlatform() {
switch (os.platform()) {
case "darwin":
return "darwin";
case "linux":
return "linux";
case "win32":
return "windows";
default:
throw new Error(`Unsupported platform: ${os.platform()}`);
}
}