tree-sitter/cli/npm/install.js

75 lines
1.9 KiB
JavaScript
Raw Normal View History

2019-01-16 11:42:50 -08:00
#!/usr/bin/env node
const fs = require('fs');
const zlib = require('zlib');
2019-01-16 11:42:50 -08:00
const https = require('https');
const packageJSON = require('./package.json');
// Determine the URL of the file.
const platformName = {
'darwin': 'macos',
2019-01-16 11:42:50 -08:00
'linux': 'linux',
'win32': 'windows'
}[process.platform];
let archName = {
'x64': 'x64',
'x86': 'x86',
'ia32': 'x86'
}[process.arch];
// ARM macs can run x64 binaries via Rosetta. Rely on that for now.
if (platformName === 'macos' && process.arch === 'arm64') {
archName = 'x64';
}
if (!platformName || !archName) {
console.error(
`Cannot install tree-sitter-cli for platform ${process.platform}, architecture ${process.arch}`
);
process.exit(1);
}
const releaseURL = `https://github.com/tree-sitter/tree-sitter/releases/download/v${packageJSON.version}`;
const assetName = `tree-sitter-${platformName}-${archName}.gz`;
2019-01-16 11:42:50 -08:00
const assetURL = `${releaseURL}/${assetName}`;
// Remove previously-downloaded files.
const executableName = process.platform === 'win32' ? 'tree-sitter.exe' : 'tree-sitter';
2019-01-16 11:42:50 -08:00
if (fs.existsSync(executableName)) {
fs.unlinkSync(executableName);
}
// Download the compressed file.
console.log(`Downloading ${assetURL}`);
const file = fs.createWriteStream(executableName);
2019-01-16 11:42:50 -08:00
get(assetURL, response => {
if (response.statusCode > 299) {
console.error([
2019-01-16 11:42:50 -08:00
'Download failed',
'',
`url: ${assetURL}`,
2019-01-16 11:42:50 -08:00
`status: ${response.statusCode}`,
`headers: ${JSON.stringify(response.headers, null, 2)}`,
'',
].join('\n'));
process.exit(1);
2019-01-16 11:42:50 -08:00
}
response.pipe(zlib.createGunzip()).pipe(file);
2019-01-16 11:42:50 -08:00
});
file.on('finish', () => {
fs.chmodSync(executableName, '755');
});
2019-01-16 11:42:50 -08:00
// Follow redirects.
function get(url, callback) {
https.get(url, response => {
if (response.statusCode === 301 || response.statusCode === 302) {
get(response.headers.location, callback);
} else {
callback(response);
}
});
}