Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 5 additions & 56 deletions packages/lsp/src/server/csharp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'],
})
66 changes: 66 additions & 0 deletions packages/lsp/src/server/dotnet-tool.ts
Original file line number Diff line number Diff line change
@@ -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<string | undefined> {
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
}
Comment thread
amondnet marked this conversation as resolved.
Resolved

/** A server run from PATH, or installed with `dotnet tool install` into `~/.cache/dora/<id>-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 }
},
}
}
61 changes: 5 additions & 56 deletions packages/lsp/src/server/fsharp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'],
})
105 changes: 105 additions & 0 deletions packages/lsp/src/server/github-release.ts
Original file line number Diff line number Diff line change
@@ -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<GithubRelease['assets'][number] | undefined> {
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.
Comment thread
amondnet marked this conversation as resolved.
Resolved
*/
export async function downloadReleaseBinary(spec: ReleaseBinarySpec, destDir: string, bin: string): Promise<boolean> {
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
}
Comment thread
amondnet marked this conversation as resolved.
Resolved

async function extractArchive(archivePath: string, destDir: string): Promise<void> {
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' })
Comment thread
amondnet marked this conversation as resolved.
Resolved
const [exitCode, stderr] = await Promise.all([proc.exited, new Response(proc.stderr).text()])
if (exitCode !== 0) {
throw new Error(`tar exited ${exitCode}: ${stderr}`)
}
Comment thread
amondnet marked this conversation as resolved.
Resolved
}
Loading