diff --git a/packages/lsp/src/server/csharp.ts b/packages/lsp/src/server/csharp.ts index bf45bcf..3865256 100644 --- a/packages/lsp/src/server/csharp.ts +++ b/packages/lsp/src/server/csharp.ts @@ -3,62 +3,11 @@ * Uses dotnet tool install */ -import type { LSPServerInfo } from './types' -import { spawn } from 'node:child_process' -import fs from 'node:fs/promises' -import os from 'node:os' -import path from 'node:path' -import process from 'node:process' -import { attachLSPProcessHandlers, autoInstallDisabled, log, nearestRoot } from './utils' +import { dotnetToolServer } from './dotnet-tool' -function getCsharpResourcesDir(): string { - return path.join(os.homedir(), '.cache', 'dora', 'csharp-lsp') -} - -export const CsharpServer: LSPServerInfo = { +export const CsharpServer = dotnetToolServer({ id: 'csharp', + tool: 'csharp-ls', extensions: ['.cs'], - root: nearestRoot(['.sln', '.csproj', 'global.json']), - async spawn(root) { - const isWindows = process.platform === 'win32' - const ext = isWindows ? '.exe' : '' - const resourcesDir = getCsharpResourcesDir() - - // Check PATH first - let bin = Bun.which('csharp-ls', { - PATH: `${process.env.PATH}${path.delimiter}${resourcesDir}`, - }) - - if (!bin) { - // Check prerequisite - const dotnet = Bun.which('dotnet') - if (!dotnet) { - log.warn('.NET SDK is required for csharp-ls. Install .NET SDK first.') - return undefined - } - - if (autoInstallDisabled('csharp')) { return undefined } - - log.info('Installing csharp-ls via dotnet tool') - await fs.mkdir(resourcesDir, { recursive: true }) - - const proc = Bun.spawn(['dotnet', 'tool', 'install', 'csharp-ls', '--tool-path', resourcesDir], { - stdout: 'pipe', - stderr: 'pipe', - }) - const exitCode = await proc.exited - if (exitCode !== 0) { - const stderr = await new Response(proc.stderr).text() - log.error({ exitCode, stderr }, 'Failed to install csharp-ls') - return undefined - } - - bin = path.join(resourcesDir, `csharp-ls${ext}`) - log.info({ bin }, 'csharp-ls installed') - } - - const proc = spawn(bin, [], { cwd: root }) - attachLSPProcessHandlers(proc, 'csharp') - return { process: proc } - }, -} + rootMarkers: ['.sln', '.csproj', 'global.json'], +}) diff --git a/packages/lsp/src/server/dotnet-tool.ts b/packages/lsp/src/server/dotnet-tool.ts new file mode 100644 index 0000000..131c2ac --- /dev/null +++ b/packages/lsp/src/server/dotnet-tool.ts @@ -0,0 +1,66 @@ +import type { LSPServerInfo } from './types' +import { spawn } from 'node:child_process' +import fs from 'node:fs/promises' +import path from 'node:path' +import process from 'node:process' +import { findCachedBinary, serverCacheDir } from './github-release' +import { attachLSPProcessHandlers, autoInstallDisabled, log, nearestRoot } from './utils' + +export interface DotnetToolServerSpec { + id: string + /** NuGet tool package, also the executable name. */ + tool: string + extensions: string[] + rootMarkers: string[] +} + +async function installDotnetTool(serverId: string, tool: string, toolPath: string): Promise { + if (!Bun.which('dotnet')) { + log.warn(`.NET SDK is required for ${tool}. Install .NET SDK first.`) + return undefined + } + if (autoInstallDisabled(serverId)) { + return undefined + } + + log.info({ tool }, 'Installing language server via dotnet tool') + try { + await fs.mkdir(toolPath, { recursive: true }) + const proc = Bun.spawn(['dotnet', 'tool', 'install', tool, '--tool-path', toolPath], { + stdout: 'ignore', + stderr: 'pipe', + }) + const [exitCode, stderr] = await Promise.all([proc.exited, new Response(proc.stderr).text()]) + if (exitCode !== 0) { + log.error({ tool, exitCode, stderr }, 'dotnet tool install failed') + return undefined + } + } + catch (err) { + log.error({ tool, err }, 'Failed to run dotnet tool install') + return undefined + } + + const bin = path.join(toolPath, `${tool}${process.platform === 'win32' ? '.exe' : ''}`) + log.info({ bin }, 'Language server installed via dotnet tool') + return bin +} + +/** A server run from PATH, or installed with `dotnet tool install` into `~/.cache/dora/-lsp`. */ +export function dotnetToolServer(spec: DotnetToolServerSpec): LSPServerInfo { + return { + id: spec.id, + extensions: spec.extensions, + root: nearestRoot(spec.rootMarkers), + async spawn(root) { + const toolPath = serverCacheDir(`${spec.id}-lsp`) + const bin = findCachedBinary(spec.tool, toolPath) ?? await installDotnetTool(spec.id, spec.tool, toolPath) + if (!bin) { + return undefined + } + const proc = spawn(bin, [], { cwd: root }) + attachLSPProcessHandlers(proc, spec.id) + return { process: proc } + }, + } +} diff --git a/packages/lsp/src/server/fsharp.ts b/packages/lsp/src/server/fsharp.ts index e779ed6..6514c99 100644 --- a/packages/lsp/src/server/fsharp.ts +++ b/packages/lsp/src/server/fsharp.ts @@ -3,62 +3,11 @@ * Uses dotnet tool install */ -import type { LSPServerInfo } from './types' -import { spawn } from 'node:child_process' -import fs from 'node:fs/promises' -import os from 'node:os' -import path from 'node:path' -import process from 'node:process' -import { attachLSPProcessHandlers, autoInstallDisabled, log, nearestRoot } from './utils' +import { dotnetToolServer } from './dotnet-tool' -function getFsharpResourcesDir(): string { - return path.join(os.homedir(), '.cache', 'dora', 'fsharp-lsp') -} - -export const FsharpServer: LSPServerInfo = { +export const FsharpServer = dotnetToolServer({ id: 'fsharp', + tool: 'fsautocomplete', extensions: ['.fs', '.fsi', '.fsx', '.fsscript'], - root: nearestRoot(['.sln', '.fsproj', 'global.json']), - async spawn(root) { - const isWindows = process.platform === 'win32' - const ext = isWindows ? '.exe' : '' - const resourcesDir = getFsharpResourcesDir() - - // Check PATH first - let bin = Bun.which('fsautocomplete', { - PATH: `${process.env.PATH}${path.delimiter}${resourcesDir}`, - }) - - if (!bin) { - // Check prerequisite - const dotnet = Bun.which('dotnet') - if (!dotnet) { - log.warn('.NET SDK is required for fsautocomplete. Install .NET SDK first.') - return undefined - } - - if (autoInstallDisabled('fsharp')) { return undefined } - - log.info('Installing fsautocomplete via dotnet tool') - await fs.mkdir(resourcesDir, { recursive: true }) - - const proc = Bun.spawn(['dotnet', 'tool', 'install', 'fsautocomplete', '--tool-path', resourcesDir], { - stdout: 'pipe', - stderr: 'pipe', - }) - const exitCode = await proc.exited - if (exitCode !== 0) { - const stderr = await new Response(proc.stderr).text() - log.error({ exitCode, stderr }, 'Failed to install fsautocomplete') - return undefined - } - - bin = path.join(resourcesDir, `fsautocomplete${ext}`) - log.info({ bin }, 'fsautocomplete installed') - } - - const proc = spawn(bin, [], { cwd: root }) - attachLSPProcessHandlers(proc, 'fsharp') - return { process: proc } - }, -} + rootMarkers: ['.sln', '.fsproj', 'global.json'], +}) diff --git a/packages/lsp/src/server/github-release.ts b/packages/lsp/src/server/github-release.ts new file mode 100644 index 0000000..309c3c7 --- /dev/null +++ b/packages/lsp/src/server/github-release.ts @@ -0,0 +1,105 @@ +import fs from 'node:fs/promises' +import os from 'node:os' +import path from 'node:path' +import process from 'node:process' +import { downloadFile, extractZip, log } from './utils' + +const RELEASE_INFO_TIMEOUT_MS = 30_000 + +export interface GithubRelease { + tag_name: string + assets: Array<{ name: string, browser_download_url: string }> +} + +export interface ReleaseBinarySpec { + serverId: string + /** GitHub `owner/name` whose latest release ships the server. */ + repo: string + /** Name of this platform's asset; `.zip` assets are unzipped, all others untarred. */ + assetName: (release: GithubRelease) => string +} + +export function serverCacheDir(name: string): string { + return path.join(os.homedir(), '.cache', 'dora', name) +} + +/** Looks up `name` on PATH, then in `dirs`. */ +export function findCachedBinary(name: string, ...dirs: string[]): string | null { + return Bun.which(name, { + PATH: [process.env.PATH, ...dirs].filter(Boolean).join(path.delimiter), + }) +} + +async function findReleaseAsset(spec: ReleaseBinarySpec): Promise { + const { serverId, repo } = spec + try { + const response = await fetch(`https://api.github.com/repos/${repo}/releases/latest`, { + signal: AbortSignal.timeout(RELEASE_INFO_TIMEOUT_MS), + }) + if (!response.ok) { + log.error({ serverId, repo, status: response.status, statusText: response.statusText }, 'Failed to fetch release info from GitHub') + return undefined + } + const release = await response.json() as GithubRelease + const assetName = spec.assetName(release) + const asset = release.assets.find(a => a.name === assetName) + if (!asset) { + log.error({ serverId, assetName, availableAssets: release.assets.map(a => a.name).slice(0, 10) }, 'Release asset not found for this platform') + } + return asset + } + catch (err) { + log.error({ serverId, repo, err }, 'Failed to fetch release info from GitHub') + return undefined + } +} + +/** + * Extracts this platform's asset from the latest release of `spec.repo` into `destDir` + * and makes `bin` executable. Returns false, after logging, when any step fails. + */ +export async function downloadReleaseBinary(spec: ReleaseBinarySpec, destDir: string, bin: string): Promise { + const { serverId } = spec + const asset = await findReleaseAsset(spec) + if (!asset) { + return false + } + const assetName = asset.name + + let downloadDir: string | undefined + try { + downloadDir = await fs.mkdtemp(path.join(os.tmpdir(), `dora-${serverId}-`)) + const archivePath = path.join(downloadDir, assetName) + await downloadFile(asset.browser_download_url, archivePath) + await extractArchive(archivePath, destDir) + await fs.access(bin) + if (process.platform !== 'win32') { + await fs.chmod(bin, 0o700) + } + } + catch (err) { + log.error({ serverId, assetName, bin, err }, 'Failed to install language server from GitHub release') + return false + } + finally { + if (downloadDir) { + await fs.rm(downloadDir, { force: true, recursive: true }).catch((err) => { + log.warn({ serverId, downloadDir, err }, 'Failed to clean up release download') + }) + } + } + return true +} + +async function extractArchive(archivePath: string, destDir: string): Promise { + if (archivePath.endsWith('.zip')) { + await extractZip(archivePath, destDir) + return + } + await fs.mkdir(destDir, { recursive: true }) + const proc = Bun.spawn(['tar', '-xzf', archivePath, '-C', destDir], { stdout: 'ignore', stderr: 'pipe' }) + const [exitCode, stderr] = await Promise.all([proc.exited, new Response(proc.stderr).text()]) + if (exitCode !== 0) { + throw new Error(`tar exited ${exitCode}: ${stderr}`) + } +} diff --git a/packages/lsp/src/server/lua.ts b/packages/lsp/src/server/lua.ts index ccb1f1b..3b65479 100644 --- a/packages/lsp/src/server/lua.ts +++ b/packages/lsp/src/server/lua.ts @@ -3,22 +3,22 @@ * Auto-downloads from GitHub releases */ +import type { ReleaseBinarySpec } from './github-release' import type { LSPServerInfo } from './types' import { spawn } from 'node:child_process' import fs from 'node:fs/promises' -import os from 'node:os' import path from 'node:path' import process from 'node:process' -import { attachLSPProcessHandlers, autoInstallDisabled, downloadFile, extractZip, log, nearestRoot } from './utils' - -function getLuaLsResourcesDir(): string { - return path.join(os.homedir(), '.cache', 'dora', 'lua-lsp') +import { downloadReleaseBinary, findCachedBinary, serverCacheDir } from './github-release' +import { attachLSPProcessHandlers, autoInstallDisabled, log, nearestRoot } from './utils' + +const LUA_RELEASE: ReleaseBinarySpec = { + serverId: 'lua-ls', + repo: 'LuaLS/lua-language-server', + // Assets use Node's platform/arch names and drop the tag's `v`, e.g. 3.13.5-darwin-arm64 + assetName: release => `lua-language-server-${release.tag_name.replace(/^v/, '')}-${process.platform}-${process.arch}.${process.platform === 'win32' ? 'zip' : 'tar.gz'}`, } -/** - * Moves a complete staged install to `installDir`. A working install already there - * (another start published first) is kept; only a leftover without the binary is replaced. - */ async function publishInstall(stagingDir: string, installDir: string, bin: string): Promise { for (let attempt = 0; attempt < 2; attempt++) { try { @@ -57,101 +57,42 @@ export const LuaLsServer: LSPServerInfo = { 'selene.yml', ]), async spawn(root) { - const isWindows = process.platform === 'win32' - const ext = isWindows ? '.exe' : '' - const resourcesDir = getLuaLsResourcesDir() + const ext = process.platform === 'win32' ? '.exe' : '' + const resourcesDir = serverCacheDir('lua-lsp') const installDir = path.join(resourcesDir, `lua-language-server-${process.arch}-${process.platform}`) - // Check PATH first, then a previous download - let bin = Bun.which('lua-language-server', { - PATH: [process.env.PATH, resourcesDir, path.join(installDir, 'bin')].filter(Boolean).join(path.delimiter), - }) + let bin = findCachedBinary('lua-language-server', resourcesDir, path.join(installDir, 'bin')) if (!bin) { if (autoInstallDisabled('lua-ls')) { return undefined } log.info('Downloading lua-language-server from GitHub releases') await fs.mkdir(resourcesDir, { recursive: true }) - const releaseResponse = await fetch('https://api.github.com/repos/LuaLS/lua-language-server/releases/latest') - if (!releaseResponse.ok) { - log.error({ status: releaseResponse.status, statusText: releaseResponse.statusText }, 'Failed to fetch lua-language-server release info from GitHub') - return undefined - } - - const release = await releaseResponse.json() as { - tag_name: string - assets: Array<{ name: string, browser_download_url: string }> - } - - // LuaLS uses platform/arch naming that matches Node.js convention - // darwin-arm64, darwin-x64, linux-arm64, linux-x64, win32-x64 - const platform = process.platform - const arch = process.arch - const archiveExt = isWindows ? 'zip' : 'tar.gz' - - // Remove 'v' prefix from tag if present (tag is v3.13.5, asset uses 3.13.5) - const version = release.tag_name.replace(/^v/, '') - - const assetName = `lua-language-server-${version}-${platform}-${arch}.${archiveExt}` - const asset = release.assets.find(a => a.name === assetName) - if (!asset) { - log.error({ assetName, availableAssets: release.assets.map(a => a.name).slice(0, 10) }, 'lua-language-server asset not found for this platform') - return undefined - } - - // Extract into a per-attempt staging dir and move it into place only once it is - // complete, so an interrupted download or a concurrent start never leaves a - // half-extracted install that the lookup above would reuse. const stagingDir = await fs.mkdtemp(`${installDir}.partial-`) - const archivePath = `${stagingDir}-${assetName}` bin = path.join(installDir, 'bin', `lua-language-server${ext}`) try { - await downloadFile(asset.browser_download_url, archivePath) - - if (archiveExt === 'zip') { - await extractZip(archivePath, stagingDir) - } - else { - const tarProc = Bun.spawn(['tar', '-xzf', archivePath, '-C', stagingDir], { - stdout: 'pipe', - stderr: 'pipe', - }) - const tarExitCode = await tarProc.exited - if (tarExitCode !== 0) { - const stderr = await new Response(tarProc.stderr).text() - log.error({ tarExitCode, stderr }, 'Failed to extract lua-language-server archive') - return undefined - } - } - const stagedBin = path.join(stagingDir, 'bin', `lua-language-server${ext}`) - try { - await fs.access(stagedBin) - } - catch { - log.error({ bin: stagedBin }, 'lua-language-server binary not found after extraction') + if (!await downloadReleaseBinary(LUA_RELEASE, stagingDir, stagedBin)) { return undefined } - if (!await publishInstall(stagingDir, installDir, bin)) { log.error({ bin }, 'lua-language-server install could not be moved into place') return undefined } - } - finally { - const cleanup = await Promise.allSettled([ - fs.rm(archivePath, { force: true }), - fs.rm(stagingDir, { force: true, recursive: true }), - ]) - for (const result of cleanup) { - if (result.status === 'rejected') { - log.warn({ err: result.reason, archivePath, stagingDir }, 'Failed to clean up lua-language-server download files') + if (process.platform !== 'win32') { + try { + await fs.chmod(bin, 0o700) + } + catch (err) { + log.error({ bin, err }, 'Failed to make lua-language-server executable') + return undefined } } } - - if (!isWindows) { - await fs.chmod(bin, 0o755) + finally { + await fs.rm(stagingDir, { force: true, recursive: true }).catch((err) => { + log.warn({ err, stagingDir }, 'Failed to clean up lua-language-server staging dir') + }) } log.info({ bin }, 'lua-language-server installed') diff --git a/packages/lsp/src/server/terraform.ts b/packages/lsp/src/server/terraform.ts index 258ab71..0bfb4e9 100644 --- a/packages/lsp/src/server/terraform.ts +++ b/packages/lsp/src/server/terraform.ts @@ -3,16 +3,23 @@ * Auto-downloads from GitHub releases */ +import type { ReleaseBinarySpec } from './github-release' import type { LSPServerInfo } from './types' import { spawn } from 'node:child_process' -import fs from 'node:fs/promises' -import os from 'node:os' import path from 'node:path' import process from 'node:process' -import { attachLSPProcessHandlers, autoInstallDisabled, downloadFile, extractZip, log, nearestRoot } from './utils' - -function getTerraformResourcesDir(): string { - return path.join(os.homedir(), '.cache', 'dora', 'terraform-lsp') +import { downloadReleaseBinary, findCachedBinary, serverCacheDir } from './github-release' +import { attachLSPProcessHandlers, autoInstallDisabled, log, nearestRoot } from './utils' + +const TERRAFORM_RELEASE: ReleaseBinarySpec = { + serverId: 'terraform', + repo: 'hashicorp/terraform-ls', + assetName: (release) => { + const version = release.tag_name.replace('v', '') + const tfArch = process.arch === 'arm64' ? 'arm64' : 'amd64' + const tfPlatform = process.platform === 'win32' ? 'windows' : process.platform + return `terraform-ls_${version}_${tfPlatform}_${tfArch}.zip` + }, } export const TerraformServer: LSPServerInfo = { @@ -20,60 +27,14 @@ export const TerraformServer: LSPServerInfo = { extensions: ['.tf', '.tfvars'], root: nearestRoot(['.terraform.lock.hcl', 'terraform.tfstate']), async spawn(root) { - const isWindows = process.platform === 'win32' - const ext = isWindows ? '.exe' : '' - const resourcesDir = getTerraformResourcesDir() - - // Check PATH first - let bin = Bun.which('terraform-ls', { - PATH: `${process.env.PATH}${path.delimiter}${resourcesDir}`, - }) + const resourcesDir = serverCacheDir('terraform-lsp') + let bin = findCachedBinary('terraform-ls', resourcesDir) if (!bin) { if (autoInstallDisabled('terraform')) { return undefined } log.info('Downloading terraform-ls from GitHub releases') - await fs.mkdir(resourcesDir, { recursive: true }) - - const releaseResponse = await fetch('https://api.github.com/repos/hashicorp/terraform-ls/releases/latest') - if (!releaseResponse.ok) { - log.error({ status: releaseResponse.status, statusText: releaseResponse.statusText }, 'Failed to fetch terraform-ls release info from GitHub') - return undefined - } - - const release = await releaseResponse.json() as { - tag_name: string - assets: Array<{ name: string, browser_download_url: string }> - } - - const version = release.tag_name.replace('v', '') - const tfArch = process.arch === 'arm64' ? 'arm64' : 'amd64' - const tfPlatform = isWindows ? 'windows' : process.platform - - const assetName = `terraform-ls_${version}_${tfPlatform}_${tfArch}.zip` - const asset = release.assets.find(a => a.name === assetName) - if (!asset) { - log.error({ assetName }, 'terraform-ls asset not found') - return undefined - } - - const archivePath = path.join(resourcesDir, assetName) - await downloadFile(asset.browser_download_url, archivePath) - await extractZip(archivePath, resourcesDir) - await fs.rm(archivePath, { force: true }) - - bin = path.join(resourcesDir, `terraform-ls${ext}`) - try { - await fs.access(bin) - } - catch { - log.error({ bin }, 'terraform-ls binary not found after extraction') - return undefined - } - - if (!isWindows) { - await fs.chmod(bin, 0o755) - } - + bin = path.join(resourcesDir, `terraform-ls${process.platform === 'win32' ? '.exe' : ''}`) + if (!await downloadReleaseBinary(TERRAFORM_RELEASE, resourcesDir, bin)) { return undefined } log.info({ bin }, 'terraform-ls installed') } diff --git a/packages/lsp/src/server/texlab.ts b/packages/lsp/src/server/texlab.ts index 9d9f5ed..8356e37 100644 --- a/packages/lsp/src/server/texlab.ts +++ b/packages/lsp/src/server/texlab.ts @@ -3,16 +3,23 @@ * Auto-downloads from GitHub releases */ +import type { ReleaseBinarySpec } from './github-release' import type { LSPServerInfo } from './types' import { spawn } from 'node:child_process' -import fs from 'node:fs/promises' -import os from 'node:os' import path from 'node:path' import process from 'node:process' -import { attachLSPProcessHandlers, autoInstallDisabled, downloadFile, extractZip, log, nearestRoot } from './utils' +import { downloadReleaseBinary, findCachedBinary, serverCacheDir } from './github-release' +import { attachLSPProcessHandlers, autoInstallDisabled, log, nearestRoot } from './utils' -function getTexlabResourcesDir(): string { - return path.join(os.homedir(), '.cache', 'dora', 'texlab-lsp') +const TEXLAB_RELEASE: ReleaseBinarySpec = { + serverId: 'texlab', + repo: 'latex-lsp/texlab', + assetName: () => { + const isWindows = process.platform === 'win32' + const texArch = process.arch === 'arm64' ? 'aarch64' : 'x86_64' + const texPlatform = process.platform === 'darwin' ? 'macos' : isWindows ? 'windows' : 'linux' + return `texlab-${texArch}-${texPlatform}.${isWindows ? 'zip' : 'tar.gz'}` + }, } export const TexlabServer: LSPServerInfo = { @@ -20,78 +27,14 @@ export const TexlabServer: LSPServerInfo = { extensions: ['.tex', '.bib'], root: nearestRoot(['.latexmkrc', 'latexmkrc', '.texlabroot', 'texlabroot']), async spawn(root) { - const isWindows = process.platform === 'win32' - const ext = isWindows ? '.exe' : '' - const resourcesDir = getTexlabResourcesDir() - - // Check PATH first - let bin = Bun.which('texlab', { - PATH: `${process.env.PATH}${path.delimiter}${resourcesDir}`, - }) + const resourcesDir = serverCacheDir('texlab-lsp') + let bin = findCachedBinary('texlab', resourcesDir) if (!bin) { if (autoInstallDisabled('texlab')) { return undefined } log.info('Downloading texlab from GitHub releases') - await fs.mkdir(resourcesDir, { recursive: true }) - - const releaseResponse = await fetch('https://api.github.com/repos/latex-lsp/texlab/releases/latest') - if (!releaseResponse.ok) { - log.error({ status: releaseResponse.status, statusText: releaseResponse.statusText }, 'Failed to fetch texlab release info from GitHub') - return undefined - } - - const release = await releaseResponse.json() as { - tag_name: string - assets: Array<{ name: string, browser_download_url: string }> - } - - const texArch = process.arch === 'arm64' ? 'aarch64' : 'x86_64' - const texPlatform = process.platform === 'darwin' ? 'macos' : isWindows ? 'windows' : 'linux' - const archiveExt = isWindows ? 'zip' : 'tar.gz' - - const assetName = `texlab-${texArch}-${texPlatform}.${archiveExt}` - const asset = release.assets.find(a => a.name === assetName) - if (!asset) { - log.error({ assetName }, 'texlab asset not found') - return undefined - } - - const archivePath = path.join(resourcesDir, assetName) - await downloadFile(asset.browser_download_url, archivePath) - - if (archiveExt === 'zip') { - await extractZip(archivePath, resourcesDir) - } - else { - const tarProc = Bun.spawn(['tar', '-xzf', archivePath], { - cwd: resourcesDir, - stdout: 'pipe', - stderr: 'pipe', - }) - const tarExitCode = await tarProc.exited - if (tarExitCode !== 0) { - const stderr = await new Response(tarProc.stderr).text() - log.error({ tarExitCode, stderr }, 'Failed to extract texlab archive') - await fs.rm(archivePath, { force: true }) - return undefined - } - } - - await fs.rm(archivePath, { force: true }) - - bin = path.join(resourcesDir, `texlab${ext}`) - try { - await fs.access(bin) - } - catch { - log.error({ bin }, 'texlab binary not found after extraction') - return undefined - } - - if (!isWindows) { - await fs.chmod(bin, 0o755) - } - + bin = path.join(resourcesDir, `texlab${process.platform === 'win32' ? '.exe' : ''}`) + if (!await downloadReleaseBinary(TEXLAB_RELEASE, resourcesDir, bin)) { return undefined } log.info({ bin }, 'texlab installed') } diff --git a/packages/lsp/test/unit/auto-install.test.ts b/packages/lsp/test/unit/auto-install.test.ts index 5dd9b0b..8e93563 100644 --- a/packages/lsp/test/unit/auto-install.test.ts +++ b/packages/lsp/test/unit/auto-install.test.ts @@ -3,6 +3,7 @@ import os from 'node:os' import path from 'node:path' import process from 'node:process' import { afterEach, beforeEach, describe, expect, spyOn, test } from 'bun:test' +import { CsharpServer } from '../../src/server/csharp' import { LuaLsServer } from '../../src/server/lua' import { TerraformServer } from '../../src/server/terraform' import { TexlabServer } from '../../src/server/texlab' @@ -69,6 +70,13 @@ describe('spawn with a stubbed network (auto-install off unless a test turns it expect(fetchCalls).toEqual([]) }) + test('terraform returns undefined when the release lookup fails with auto-install on', async () => { + process.env[AUTO_INSTALL_ENV] = 'true' + + expect(await TerraformServer.spawn(tmp)).toBeUndefined() + expect(fetchCalls).toHaveLength(1) + }) + test.skipIf(process.platform === 'win32')('texlab still runs a binary already in the cache', async () => { const cacheDir = path.join(tmp, '.cache', 'dora', 'texlab-lsp') await fs.mkdir(cacheDir, { recursive: true }) @@ -123,4 +131,42 @@ describe('spawn with a stubbed network (auto-install off unless a test turns it expect((await fs.readdir(resourcesDir)).filter(name => name.includes('.partial-'))).toEqual([]) handle?.process.kill() }) + + test.skipIf(process.platform === 'win32')('csharp-ls runs a tool already installed in the cache', async () => { + const toolPath = path.join(tmp, '.cache', 'dora', 'csharp-lsp') + await fs.mkdir(toolPath, { recursive: true }) + await fs.writeFile(path.join(toolPath, 'csharp-ls'), '#!/bin/sh\nexit 0\n', { mode: 0o755 }) + + const handle = await CsharpServer.spawn(tmp) + + expect(handle).toBeDefined() + handle?.process.kill() + }) + + test.skipIf(process.platform === 'win32')('texlab downloads the release binary when auto-install is on', async () => { + process.env[AUTO_INSTALL_ENV] = 'true' + const src = path.join(tmp, 'archive-src') + await fs.mkdir(src) + await fs.writeFile(path.join(src, 'texlab'), '#!/bin/sh\nexit 0\n') + const archive = path.join(tmp, 'texlab.tar.gz') + expect(Bun.spawnSync(['tar', '-czf', archive, '-C', src, '.']).exitCode).toBe(0) + const texArch = process.arch === 'arm64' ? 'aarch64' : 'x86_64' + const texPlatform = process.platform === 'darwin' ? 'macos' : 'linux' + globalThis.fetch = (async (input: unknown) => { + const url = String(input) + fetchCalls.push(url) + if (url.includes('/releases/latest')) { + return Response.json({ tag_name: 'v9.9.9', assets: [{ name: `texlab-${texArch}-${texPlatform}.tar.gz`, browser_download_url: 'https://example.test/texlab.tar.gz' }] }) + } + return new Response(await fs.readFile(archive)) + }) as unknown as typeof fetch + + const handle = await TexlabServer.spawn(tmp) + + expect(handle).toBeDefined() + expect(fetchCalls).toHaveLength(2) + const stat = await fs.stat(path.join(tmp, '.cache', 'dora', 'texlab-lsp', 'texlab')) + expect(stat.mode & 0o111).not.toBe(0) + handle?.process.kill() + }) })