-
Notifications
You must be signed in to change notification settings - Fork 2
/
setup.js
441 lines (410 loc) · 15.1 KB
/
setup.js
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
// A build script that downloads the latest ink! Language Server (ink-lsp-server) binary for the target platform (if none exists yet at ./server/ink-lsp-server[.exe]).
const fs = require('node:fs');
const path = require('node:path');
const https = require('node:https');
const fetch = require('node-fetch');
const zlib = require('node:zlib');
const { pipeline } = require('node:stream');
const { execSync } = require('node:child_process');
const { promisify } = require('node:util');
const chalk = require('chalk');
const admZip = require('adm-zip');
const pipe = promisify(pipeline);
const BINARY_INSTALL_INSTRUCTIONS =
"You'll need to:\n" +
'- Clone the ink! Analyzer repository\n' +
'- Manually build an ink-lsp-server binary\n' +
'- Copy the binary into the `./server` directory in the project root\n' +
'- Make the binary executable\n\n' +
'Please find further instructions at: ' +
chalk.blue.underline('https://github.com/ink-analyzer/ink-analyzer/tree/master/crates/lsp-server#installation');
(async () => {
if (process.env.INK_ANALYZER_SKIP_SETUP) {
// Allows skipping of language server setting when publishing pre-packaged extensions.
console.log(
chalk.yellow('⚠️ Warning:') +
' Skipping ink-lsp-server binary setup and verification because the ' +
chalk.yellow('`INK_ANALYZER_SKIP_SETUP`') +
' environment variable is set.',
);
process.exit(0);
}
let version = process.env.INK_ANALYZER_LSP_SERVER_VERSION;
if (!version) {
console.log('⌛ Reading package metadata ...');
const packageMetadata = getPackageMetadata();
version = packageMetadata && packageMetadata.lspServerVersion;
}
if (!version) {
console.log(
chalk.yellow('⚠️ Warning:') +
' Failed to determine a target ink-lsp-server version. Make sure the ' +
chalk.yellow('`lspServerVersion`') +
' key is set in `package.json` or set the ' +
chalk.yellow('`INK_ANALYZER_LSP_SERVER_VERSION`') +
' environment variable.',
);
}
console.log('🔎 Searching for ink-lsp-server binary ...');
const serverPath = path.resolve(`./server/ink-lsp-server${process.platform === 'win32' ? '.exe' : ''}`);
const stat = fs.statSync(serverPath, { throwIfNoEntry: false });
const binaryExists = stat && stat.isFile();
if (binaryExists) {
if (verifyBinary(serverPath, version)) {
// Exits successfully if a binary exists at the expected location.
exitWithSuccess(serverPath);
}
// Tries to fix binaries permissions for the existing binary.
if (fixBinaryPermissions(serverPath, version)) {
// Exits successfully if the executable permissions were added successfully to the existing binary.
exitWithSuccess(serverPath);
}
}
// Exits with an error if ink! Analyzer doesn't ship ink-lsp-server binaries for this platform.
const target = getBinaryTarget();
if (!target) {
exitWithError(
chalk.red("ink! Analyzer doesn't currently ship ink-lsp-server binaries for your platform: ") +
target +
'\n' +
BINARY_INSTALL_INSTRUCTIONS,
);
}
// Tries to download, decompress and configure the target binary otherwise exits with an error.
const newServerPath = await setupBinaryForTarget(target, version).catch(() => {
exitWithError(
chalk.red('Failed to setup a binary for your platform: ') + target + '\n' + BINARY_INSTALL_INSTRUCTIONS,
);
});
// Exits successfully if an executable was downloaded and configured for this target.
exitWithSuccess(newServerPath);
})();
// Returns a supported Rust binary target for ink-lsp-server or undefined otherwise.
// Ref: https://github.com/ink-analyzer/ink-analyzer/blob/lsp-server-v0.2.1/.github/workflows/release.yaml#L28-L44
// Ref: https://doc.rust-lang.org/nightly/rustc/platform-support.html
function getBinaryTarget() {
// Ref: https://nodejs.org/api/process.html#processplatform
let os;
switch (process.platform) {
case 'win32': {
os = 'pc-windows-msvc';
break;
}
case 'linux': {
os = 'unknown-linux-gnu';
break;
}
case 'darwin': {
os = 'apple-darwin';
break;
}
default: {
return;
}
}
// Ref: https://nodejs.org/api/process.html#processarch
let arch;
// Allows cross compilation by setting the `INK_ANALYZER_ARCH` environment variable to the target architecture.
const processArch = process.env.INK_ANALYZER_ARCH || process.arch;
if (process.env.INK_ANALYZER_ARCH) {
console.log(
chalk.yellow('⚠️ Warning:') +
' Manually setting the architecture to ' +
chalk.yellow(`"${processArch}"`) +
' because the ' +
chalk.yellow('`INK_ANALYZER_ARCH`') +
' environment variable is set.',
);
}
switch (processArch) {
case 'x64': {
arch = 'x86_64';
break;
}
case 'ia32': {
if (process.platform === 'win32') {
arch = 'i686';
break;
}
// ink-lsp-server only releases 32 bit x86 binaries for windows.
return;
}
case 'arm64': {
arch = 'aarch64';
break;
}
default: {
return;
}
}
return `${arch}-${os}`;
}
// Exits with a success message and exit code.
function exitWithSuccess(serverPath) {
console.log(chalk.green('✅ An executable ink-lsp-server binary is available at:'), serverPath);
process.exit(0);
}
// Exits with an error message.
function exitWithError(message) {
console.log(`❌ ${message}`);
process.exit(1);
}
// Parses package.json as JSON.
function getPackageMetadata() {
try {
return JSON.parse(fs.readFileSync(path.resolve('./package.json'), 'utf-8'));
} catch (e) {
console.log(chalk.red('Error:') + ' Failed read package metadata:\n', e.message || e);
}
}
// Verifies that the binary is executable on this platform.
function verifyBinary(serverPath, version) {
console.log('⌛ Verifying binary/executable at: ', serverPath);
// Skips verification during cross-compilation.
if (process.env.INK_ANALYZER_ARCH || process.env.INK_ANALYZER_SKIP_VERIFY) {
console.log(
chalk.yellow('⚠️ Warning:') +
' Skipping ink-lsp-server binary verification because the ' +
chalk.yellow(process.env.INK_ANALYZER_ARCH ? '`INK_ANALYZER_ARCH`' : '`INK_ANALYZER_SKIP_VERIFY`') +
' environment variable is set.',
);
return true;
}
try {
const result = execSync(`${path.resolve(serverPath)} -V`, { timeout: 500 });
// `ink-lsp-server -v` returns something like `ink-lsp-server x.y.z` when it works.
const output = result.toString();
return output.includes('ink-lsp-server') && (!version || output.includes(version));
} catch (e) {
console.log(chalk.red('Error:') + ' Binary verification failed:\n', (e.stderr && e.stderr.toString()) || e);
}
return false;
}
// Attempts to add executable permissions to the binary.
function fixBinaryPermissions(serverPath, version) {
// Assume permissions are always fine on works on Windows.
if (process.platform === 'win32') {
return true;
}
console.log('⚒️ Attempting to add executable permissions to the binary at: ', serverPath);
// Fix permissions on Linux and macOS (may work for others but these are the primary targets).
try {
execSync(`chmod +x ${path.resolve(serverPath)}`, { timeout: 100 });
// The binary should be able to pass verification after the above command.
return verifyBinary(serverPath, version);
} catch (e) {
console.log(chalk.red('Error:') + ' Failed to fix binary permissions:\n', (e.stderr && e.stderr.toString()) || e);
}
return false;
}
// Downloads, decompresses and configures an ink-lsp-server for the target platform.
async function setupBinaryForTarget(target, version, retryCount = 0) {
if (retryCount) {
console.log(`📡 Download retry #${retryCount}: ink-lsp-server binary for ${target} ...`);
} else {
console.log(
`📦 Downloading ink-lsp-server binary (${version ? `version ${version}` : 'latest'}) for ${target} ...`,
);
}
// Cleans server directory.
fs.rmSync(path.resolve('./server'), { force: true, recursive: true });
try {
fs.mkdirSync(path.resolve('./server'));
} catch (e) {}
// Downloads the latest release of ink-lsp-server binary for the target platform.
let asset;
let archivePath;
const serverPath = path.resolve(`./server/ink-lsp-server${process.platform === 'win32' ? '.exe' : ''}`);
try {
asset = await getBinaryDownloadUrl(target, version);
archivePath = path.resolve(`./server/${asset.name}`);
await downloadAsset(asset.browser_download_url, archivePath);
} catch (e) {
console.log(chalk.red('Error:') + ' Binary download failed:\n', e);
// Retries download binary setup process at least 10 times before giving up.
const numTries = (retryCount || 0) + 1;
if (numTries > 10) {
throw e;
} else {
return setupBinaryForTarget(target, version, numTries);
}
}
// Unpack and rename assets.
switch (asset.content_type) {
case 'application/gzip': {
await decompressGzipAsset(archivePath, serverPath).catch(() => {
// Exits with an error message alerting the user that we failed to decompress the binary.
exitWithError(
chalk.red('Failed to decompress the binary for your platform: ') +
archivePath +
'\n' +
BINARY_INSTALL_INSTRUCTIONS,
);
});
if (fixBinaryPermissions(serverPath)) {
// Deletes the archive.
fs.rmSync(archivePath);
// Returns the new server path.
return serverPath;
}
break;
}
case 'application/zip': {
if (
decompressZipAsset(
archivePath,
path.resolve('./server'),
`ink-lsp-server${process.platform === 'win32' ? '.exe' : ''}`,
)
) {
if (fixBinaryPermissions(serverPath)) {
// Deletes the archive.
fs.rmSync(archivePath);
// Returns the new server path.
return serverPath;
}
} else {
// Exits with an error message alerting the user that we failed to decompress the binary.
exitWithError(
chalk.red('Failed to decompress the binary for your platform: ') +
archivePath +
'\n' +
BINARY_INSTALL_INSTRUCTIONS,
);
}
break;
}
default: {
throw new Error(`Unsupported file type: ${archivePath}`);
}
}
throw new Error('Failed to setup binary');
}
// Returns (if any) the download URL for the ink-lsp-server binary version for
// the specified platform/target and version (defaults to latest).
async function getBinaryDownloadUrl(target, version) {
try {
// Ref: https://docs.github.com/en/rest/releases/releases?apiVersion=2022-11-28#get-the-latest-release
// Ref: https://docs.github.com/en/rest/releases/releases?apiVersion=2022-11-28#get-a-release-by-tag-name
let headers = { Accept: 'application/vnd.github+json', 'User-Agent': 'ink! Analyzer' };
// CLI runners sometimes hit rate limits due to shared IPs, so we use the GitHub token when available in that context.
if (process.env.GITHUB_TOKEN) {
headers['Authorization'] = `Bearer ${process.env.GITHUB_TOKEN}`;
}
const res = await fetch(
`https://api.github.com/repos/ink-analyzer/ink-analyzer/releases/${
version ? `tags/lsp-server-v${version}` : 'latest'
}`,
{
headers,
},
);
if (res) {
const data = await res.json();
if (data.assets) {
return data.assets.find((item) => item.name.toLowerCase().includes(target.toLowerCase()));
} else {
return Promise.reject(
new Error(
`Bad response for ink-lsp-binary assets: ${JSON.stringify(data)} | header keys: ${JSON.stringify(
Object.keys(headers),
)}`,
),
);
}
}
} catch (e) {
throw e;
}
throw new Error(`Failed to get ${version || 'latest'} binary download url`);
}
// Downloads an asset to a destination path.
function downloadAsset(url, path) {
return new Promise((resolve, reject) => {
const start = performance.now();
https
.get(
url,
{
headers: {
Accept: 'application/octet-stream',
'User-Agent': 'ink! Analyzer',
},
},
(res) => {
if ([301, 302].includes(res.statusCode) && res.headers['location']) {
// Follows redirects.
downloadAsset(res.headers['location'], path).then(resolve).catch(reject);
} else if (res.statusCode === 200) {
// Downloads the file.
const file = fs.createWriteStream(path);
const size = parseInt(res.headers['content-length']);
let received = 0;
res
.on('data', (data) => {
received += data.length;
const percentage = ((received * 100) / size).toFixed(2);
const ratio = Math.floor(percentage / 10);
const duration = ((performance.now() - start) / 1000).toFixed(2); // in seconds.
const bar = Array.from(Array(10).keys())
.map((i) => (i <= ratio ? '===' : ' '))
.join('');
let displaySize = size;
let displayUnits = 'bytes';
if (size >= 1024 ** 2) {
displaySize = (displaySize / 1024 ** 2).toFixed(2);
displayUnits = 'MB';
} else if (size >= 1024) {
displaySize = (displaySize / 1024).toFixed(2);
displayUnits = 'kB';
}
process.stdout.write(
`Downloading ${displaySize} ${displayUnits} [${bar}] ${percentage}% ${duration}s\r`,
);
})
.pipe(file)
.on('finish', () => {
process.stdout.write('\n');
})
.on('error', () => {
fs.unlink(path, () => {
reject(new Error('Failed to write to file.'));
});
});
file.on('finish', () => {
file.close();
resolve({ path, size });
});
file.on('error', () => {
fs.unlink(path, () => {
reject(new Error('Failed to write to file.'));
});
});
} else {
// Handles failures.
reject(new Error(`Failed to download file: status: ${res.statusCode}`));
}
},
)
.on('error', (e) => {
reject(e);
});
});
}
// Decompresses an asset to a destination path.
function decompressGzipAsset(src, dest) {
// Handles .gzip files with node:zlib.
const input = fs.createReadStream(src);
const output = fs.createWriteStream(dest);
return pipe(input, zlib.createGunzip(), output);
}
function decompressZipAsset(src, destDir, destFilename) {
// Handles .zip files with adm-zip.
const zip = new admZip(src);
const zipEntries = zip.getEntries();
const executable = zipEntries.find((entry) => entry.entryName.endsWith('.exe'));
if (executable && executable.name) {
return zip.extractEntryTo(executable.name, destDir, false, true, false, destFilename);
}
return false;
}