// Builtin CLI runners: ruff, biome, shellcheck. // // Each runner follows the same shell (distilled from pi-lens's // dispatch/runners): resolve an available command, spawn once with all // matching files, parse structured stdout into unified Diagnostics, and // classify the outcome honestly — a run that completed with findings is a // succeeded check, not a failed runner. A missing CLI can be auto-installed // through the user's package managers when ctx.autoInstall is set. import path from "node:path"; import { resetExtraToolDirectories } from "../command.js"; import { type BuiltinRunnerId, type ConfiguredRunner, DEFAULT_RUNNER_CONFIGS, } from "../config.js"; import type { Diagnostic, RunnerContext, RunnerDefinition, RunnerResult, Severity, } from "../types.js"; import { ensureUv } from "../uv-installer.js"; import { type InstallCandidate, installKey, invalidateRunnerAvailability, resolveRunnerCommand, safeSpawnAsync, shareInstall, tryInstallCandidates, } from "./helpers.js"; export const DEFAULT_BIOME_EXTENSIONS = [ ".astro", ".css", ".cts", ".cjs", ".graphql", ".gql", ".html", ".js", ".json", ".jsonc", ".jsx", ".mjs", ".mts", ".svelte", ".ts", ".tsx", ".vue", ]; export const RUNNER_PRIORITIES: Record = { ruff: 10, biome: 10, shellcheck: 20, }; // Best-effort install recipes: each candidate is tried in order; the first // successful one wins. They install into the user's normal environment, so // the tool lands on the user's regular PATH (unlike pi-lens's managed dir). const INSTALL_RECIPES: Record = { ruff: [ { label: "uv tool install ruff", command: "uv", args: ["tool", "install", "ruff"], }, ], biome: [ { label: "npm install -g @biomejs/biome", command: "npm", args: ["install", "-g", "@biomejs/biome"], }, ], shellcheck: [ { label: "winget install koalaman.shellcheck", command: "winget", args: [ "install", "--id", "koalaman.shellcheck", "--silent", "--accept-source-agreements", "--accept-package-agreements", ], }, { label: "scoop install shellcheck", command: "scoop", args: ["install", "shellcheck"], }, ], }; interface ParsedOutput { diagnostics: Diagnostic[]; parseFailed?: { message: string }; } // --- Parsers --- export function parseRuff(stdout: string, root: string): ParsedOutput { if (!stdout.trim()) return { diagnostics: [] }; let parsed: unknown; try { parsed = JSON.parse(stdout); } catch (error) { return { diagnostics: [], parseFailed: { message: `ruff JSON parse failed: ${describeError(error)}`, }, }; } if (!Array.isArray(parsed)) { return { diagnostics: [], parseFailed: { message: "ruff JSON output was not an array." }, }; } const diagnostics: Diagnostic[] = []; for (const item of parsed as Array>) { const location = item.location as | { row?: number; column?: number } | undefined; const endLocation = item.end_location as | { row?: number; column?: number } | undefined; const filename = typeof item.filename === "string" ? item.filename : undefined; if (!filename || !location) continue; diagnostics.push({ filePath: toDisplayPath(filename, root), line: location.row ?? 1, column: location.column ?? 1, endLine: endLocation?.row ?? location.row ?? 1, endColumn: endLocation?.column ?? location.column ?? 1, severity: "warning", message: typeof item.message === "string" ? item.message : "ruff finding", tool: "ruff", rule: typeof item.code === "string" ? item.code : undefined, fixable: Boolean(item.fix), }); } return { diagnostics }; } interface BiomeJsonDiagnostic { category?: string; severity?: string; message?: string; description?: string; // Biome v2: path is a string, positions are line/column objects. location?: { path?: string | { file?: string }; span?: [number, number]; start?: { line?: number; column?: number }; end?: { line?: number; column?: number }; }; } export function parseBiome(stdout: string, root: string): ParsedOutput { if (!stdout.trim()) return { diagnostics: [] }; let parsed: unknown; try { parsed = JSON.parse(stdout); } catch (error) { return { diagnostics: [], parseFailed: { message: `biome JSON parse failed: ${describeError(error)}`, }, }; } if (!isRecord(parsed) || !Array.isArray(parsed.diagnostics)) { return { diagnostics: [], parseFailed: { message: "biome JSON output had no diagnostics array." }, }; } const diagnostics: Diagnostic[] = []; for (const item of parsed.diagnostics as BiomeJsonDiagnostic[]) { const rawPath = item.location?.path; const relativeFile = typeof rawPath === "string" ? rawPath : rawPath?.file; if (!relativeFile) continue; const filePath = path.isAbsolute(relativeFile) ? relativeFile : path.resolve(root, relativeFile); const start = { line: item.location?.start?.line ?? 1, column: item.location?.start?.column ?? 1, }; const end = { line: item.location?.end?.line ?? start.line, column: item.location?.end?.column ?? start.column, }; diagnostics.push({ filePath: toDisplayPath(filePath, root), line: start.line, column: start.column, endLine: end.line, endColumn: end.column, severity: biomeSeverity(item.severity), message: item.message ?? item.description ?? item.category ?? "biome finding", tool: "biome", rule: item.category, fixable: false, }); } return { diagnostics }; } interface ShellcheckJsonFinding { file?: string; line?: number; endLine?: number; column?: number; endColumn?: number; level?: string; message?: string; code?: number; fix?: unknown; } export function parseShellcheck(stdout: string, root: string): ParsedOutput { if (!stdout.trim()) return { diagnostics: [] }; let parsed: unknown; try { parsed = JSON.parse(stdout); } catch (error) { return { diagnostics: [], parseFailed: { message: `shellcheck JSON parse failed: ${describeError(error)}`, }, }; } if (!Array.isArray(parsed)) { return { diagnostics: [], parseFailed: { message: "shellcheck JSON output was not an array." }, }; } const diagnostics: Diagnostic[] = []; for (const item of parsed as ShellcheckJsonFinding[]) { if (!item.file) continue; diagnostics.push({ filePath: toDisplayPath(item.file, root), line: item.line ?? 1, column: item.column ?? 1, endLine: item.endLine ?? item.line ?? 1, endColumn: item.endColumn ?? item.column ?? 1, severity: shellcheckSeverity(item.level), message: item.message ?? "shellcheck finding", tool: "shellcheck", rule: item.code === undefined ? undefined : `SC${item.code}`, fixable: Boolean(item.fix), }); } return { diagnostics }; } function biomeSeverity(level: string | undefined): Severity { if (level === "error") return "error"; if (level === "warning") return "warning"; if (level === "information" || level === "info") return "info"; return "hint"; } function shellcheckSeverity(level: string | undefined): Severity { if (level === "error") return "error"; if (level === "warning") return "warning"; if (level === "info") return "info"; return "hint"; // style } function toDisplayPath(filePath: string, root: string) { const relative = path.relative(root, filePath).replace(/\\/g, "/"); return relative && !relative.startsWith("..") ? relative : filePath; } function describeError(error: unknown) { return error instanceof Error ? error.message : String(error); } function isRecord(value: unknown): value is Record { return typeof value === "object" && value !== null; } // --- Runner shell --- const PARSERS: Record< BuiltinRunnerId, (stdout: string, root: string, files: string[]) => ParsedOutput > = { ruff: (stdout, root) => parseRuff(stdout, root), biome: parseBiome, shellcheck: (stdout, root) => parseShellcheck(stdout, root), }; export function createCliRunner( id: BuiltinRunnerId, entry: ConfiguredRunner, priority: number, ): RunnerDefinition { const commandArgs = entry.command ?? DEFAULT_RUNNER_CONFIGS[id].command ?? []; const extensions = entry.extensions ?? DEFAULT_RUNNER_CONFIGS[id].extensions ?? []; const [command, ...baseArgs] = commandArgs; const parser = PARSERS[id]; return { id, extensions, priority, command, timeoutMs: entry.timeoutMs, autoInstall: entry.autoInstall, async run(ctx: RunnerContext): Promise { const startedAt = Date.now(); const files = ctx.files.filter((file) => extensions.includes(path.extname(file)), ); if (files.length === 0) { return skipped(id, ctx.files, "no-files-matched"); } const runWithCommand = async ( resolvedPath: string, autoInstalled: boolean, ): Promise => { ctx.reportStatus?.(`${id} check`); let outcome: Awaited>; try { outcome = await safeSpawnAsync( resolvedPath, [...baseArgs, ...files], { cwd: ctx.root, timeoutMs: ctx.timeoutMs, signal: ctx.signal, }, ); } catch (error) { return { tool: id, status: "failed" as const, diagnostics: [], files: ctx.files, durationMs: Date.now() - startedAt, failureKind: "exception" as const, failureMessage: describeError(error), }; } if (outcome.timedOut) { return { tool: id, status: "failed" as const, diagnostics: [], files: ctx.files, durationMs: Date.now() - startedAt, failureKind: "timeout" as const, failureMessage: `${id} timed out after ${ctx.timeoutMs}ms.`, }; } // A caller cancel is not a timeout; report it honestly instead of // blaming the tool's wall-clock budget. if (outcome.aborted) { return { tool: id, status: "failed" as const, diagnostics: [], files: ctx.files, durationMs: Date.now() - startedAt, failureKind: "exception" as const, failureMessage: `${id} aborted before completion.`, }; } const parsed = parser(outcome.stdout, ctx.root, files); if (parsed.parseFailed) { const detail = `${parsed.parseFailed.message}${outcome.stderr.trim() ? ` stderr: ${outcome.stderr.trim()}` : ""}`; return { tool: id, status: "failed" as const, diagnostics: [], files: ctx.files, durationMs: Date.now() - startedAt, failureKind: "parser_error" as const, failureMessage: detail, }; } return { tool: id, status: "succeeded", diagnostics: parsed.diagnostics, files: ctx.files, durationMs: Date.now() - startedAt, autoInstalled: autoInstalled || undefined, }; }; const commandPath = resolveRunnerCommand(id, command, ctx.root); if (!commandPath) { if (!ctx.autoInstall) { return { tool: id, status: "skipped", diagnostics: [], files: ctx.files, durationMs: Date.now() - startedAt, skipReason: "unavailable", }; } // 安装要跑包管理器(winget / npm / uv),有时几十秒;这段界面 // 以前完全沉默,跟 LSP 通道一样看不出在下载还是卡住了。 ctx.reportStatus?.(`${id} installing`); // Shared by install command (see installKey) so concurrent tool // calls — including an LSP lane installing the same package — // never spawn duplicate installs of the same missing CLI. const install = await shareInstall( installKey(INSTALL_RECIPES[id]), async () => { // Recipes going through uv need the uv binary itself; make it // available first (best-effort — remaining recipes still run). if (INSTALL_RECIPES[id].some((c) => c.command === "uv")) { await ensureUv(ctx.root, ctx.signal); } return tryInstallCandidates( INSTALL_RECIPES[id], ctx.root, ctx.signal, { // The installed tool itself must run, not just "pip // reported success". Probe with the runner's command. command, args: ["--version"], }, ); }, ); if (install.installed) { invalidateRunnerAvailability(id); resetExtraToolDirectories(); const reResolved = resolveRunnerCommand(id, command, ctx.root); if (reResolved) { return await runWithCommand(reResolved, true); } } return { tool: id, status: "skipped", diagnostics: [], files: ctx.files, durationMs: Date.now() - startedAt, skipReason: "unavailable", installDetail: install.detail, }; } return await runWithCommand(commandPath, false); }, }; } function skipped( tool: string, files: string[], reason: "no-files-matched" | "unavailable", ): RunnerResult { return { tool, status: "skipped", diagnostics: [], files, durationMs: 0, skipReason: reason, }; }