//! Non-LSP runners: linters, formatter, ast-grep rules. Each runs a CLI and parses its JSON. //! //! All runners report `Finding`s; the dispatcher runs the applicable ones in parallel with a timeout. use crate::manager::which; use hx_core::sandbox::command as sandboxed; use serde_json::Value; use std::path::{Path, PathBuf}; use std::time::{Duration, Instant}; use tokio::process::Command; #[derive(Debug, Clone, PartialEq)] pub struct Finding { pub path: PathBuf, /// 1-based pub line: u32, pub col: u32, /// 1 error, 2 warning pub severity: u8, pub rule: String, pub message: String, /// runner id pub source: String, } impl Finding { /// Stable identity for triage marks: survives line shifts. pub fn key(&self) -> String { format!("{}|{}|{}", self.source, self.rule, self.message) } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Kind { Lint, Format, } #[derive(Debug, Clone)] pub struct Runner { pub id: &'static str, pub kind: Kind, pub extensions: &'static [&'static str], /// project marker files; any present (at a root between file and workspace) enables the runner pub markers: &'static [&'static str], pub bin: &'static str, } /// Runners not run unless enabled in config. pub const OPT_IN: &[&str] = &["clippy"]; pub const RUNNERS: &[Runner] = &[ Runner { id: "clippy", kind: Kind::Lint, extensions: &["rs"], markers: &["Cargo.toml"], bin: "cargo", }, Runner { id: "ruff", kind: Kind::Lint, extensions: &["py", "pyi"], markers: &[], bin: "ruff", }, Runner { id: "biome", kind: Kind::Lint, extensions: &["js", "jsx", "ts", "tsx", "json", "mjs", "cjs"], markers: &["biome.json", "biome.jsonc"], bin: "biome", }, Runner { id: "eslint", kind: Kind::Lint, extensions: &["js", "jsx", "ts", "tsx", "mjs", "cjs"], markers: &[ "eslint.config.js", "eslint.config.mjs", "eslint.config.cjs", ".eslintrc.json", ".eslintrc.js", ".eslintrc.cjs", ], bin: "eslint", }, Runner { id: "ast-grep", kind: Kind::Lint, extensions: &[], markers: &[".hx/rules"], bin: "ast-grep", }, Runner { id: "rustfmt", kind: Kind::Format, extensions: &["rs"], markers: &["rustfmt.toml", ".rustfmt.toml"], bin: "rustfmt", }, Runner { id: "ruff-format", kind: Kind::Format, extensions: &["py", "pyi"], markers: &["ruff.toml", ".ruff.toml"], bin: "ruff", }, Runner { id: "biome-format", kind: Kind::Format, extensions: &["js", "jsx", "ts", "tsx", "json"], markers: &["biome.json", "biome.jsonc"], bin: "biome", }, ]; /// Nearest dir (file..=ws) containing any marker; ws when markers are empty. pub fn marker_root(file: &Path, markers: &[&str], ws: &Path) -> Option { if markers.is_empty() { return Some(ws.to_path_buf()); } for d in file.ancestors().skip(1) { if markers.iter().any(|m| d.join(m).exists()) { return Some(d.to_path_buf()); } if d == ws { break; } } None } /// Root the runner would run in for `file`, ignoring whether its binary is installed. pub fn applies(r: &Runner, file: &Path, ws: &Path) -> Option { let ext = file .extension() .and_then(|e| e.to_str()) .unwrap_or_default(); if !r.extensions.is_empty() && !r.extensions.contains(&ext) { return None; } let root = marker_root(file, r.markers, ws)?; // ast-grep: any extension, but only if rules exist if r.id == "ast-grep" && std::fs::read_dir(root.join(".hx/rules")).is_ok_and(|mut d| d.next().is_none()) { return None; } Some(root) } pub fn installed(r: &Runner) -> bool { which(r.bin) } pub struct Output { pub findings: Vec, pub took: Duration, /// set when the runner could not produce results pub error: Option, /// files the formatter changed pub changed: Vec, } async fn exec(cmd: &mut Command, timeout: Duration) -> Result<(Vec, Option), String> { cmd.stdin(std::process::Stdio::null()) .stdout(std::process::Stdio::piped()) .stderr(std::process::Stdio::piped()) .kill_on_drop(true); match tokio::time::timeout(timeout, cmd.output()).await { Err(_) => Err(format!("timed out after {}s", timeout.as_secs())), Ok(Err(e)) => Err(e.to_string()), Ok(Ok(o)) => Ok((o.stdout, o.status.code())), } } fn rel_to(root: &Path, p: &str) -> PathBuf { let p = Path::new(p); if p.is_absolute() { p.into() } else { root.join(p) } } /// Run `r` once for all `files` under `root`. Findings are limited to `files`. pub async fn run(r: &Runner, root: &Path, files: &[PathBuf], timeout: Duration) -> Output { let t = Instant::now(); let mut out = Output { findings: vec![], took: Duration::ZERO, error: None, changed: vec![], }; let before: Vec>> = if r.kind == Kind::Format { files.iter().map(|f| std::fs::read(f).ok()).collect() } else { vec![] }; let res = match r.id { "clippy" => clippy(root, timeout).await, "ruff" => ruff(root, files, timeout).await, "biome" => biome(root, files, timeout).await, "eslint" => eslint(root, files, timeout).await, "ast-grep" => ast_grep(root, files, timeout).await, "rustfmt" => exec( sandboxed("rustfmt") .args(["--edition", "2024"]) .args(files) .current_dir(root), timeout, ) .await .map(|_| vec![]), "ruff-format" => exec( sandboxed("ruff") .args(["format", "--quiet"]) .args(files) .current_dir(root), timeout, ) .await .map(|_| vec![]), "biome-format" => exec( sandboxed("biome") .args(["format", "--write"]) .args(files) .current_dir(root), timeout, ) .await .map(|_| vec![]), _ => Err(format!("unknown runner {}", r.id)), }; match res { Ok(f) => out.findings = f.into_iter().filter(|x| files.contains(&x.path)).collect(), Err(e) => out.error = Some(e), } for (f, b) in files.iter().zip(before) { if b.is_some() && std::fs::read(f).ok() != b { out.changed.push(f.clone()); } } out.took = t.elapsed(); out } /// clippy checks the whole crate; `run` filters to changed files. async fn clippy(root: &Path, timeout: Duration) -> Result, String> { let (o, _) = exec( sandboxed("cargo") .args([ "clippy", "--quiet", "--message-format=json", "--all-targets", ]) .current_dir(root), timeout, ) .await?; let mut v = vec![]; for l in String::from_utf8_lossy(&o).lines() { let Ok(m) = serde_json::from_str::(l) else { continue; }; if m["reason"] != "compiler-message" { continue; } let mm = &m["message"]; let Some(sp) = mm["spans"] .as_array() .and_then(|a| a.iter().find(|s| s["is_primary"] == true)) else { continue; }; // cargo reports paths relative to the workspace root, which may be above `root` let p = sp["file_name"].as_str().unwrap_or_default(); let Some(file) = root.ancestors().map(|r| rel_to(r, p)).find(|c| c.exists()) else { continue; }; let severity = match mm["level"].as_str() { Some("error") => 1, Some("warning") => 2, _ => continue, }; v.push(Finding { path: file, line: sp["line_start"].as_u64().unwrap_or(1) as u32, col: sp["column_start"].as_u64().unwrap_or(1) as u32, severity, rule: mm["code"]["code"].as_str().unwrap_or_default().to_string(), message: mm["message"].as_str().unwrap_or_default().to_string(), source: "clippy".into(), }); } Ok(v) } async fn ruff(root: &Path, files: &[PathBuf], timeout: Duration) -> Result, String> { let (o, _) = exec( sandboxed("ruff") .args(["check", "--output-format=json", "--no-fix", "--quiet"]) .args(files) .current_dir(root), timeout, ) .await?; let a: Vec = serde_json::from_slice(&o).map_err(|e| format!("ruff output: {e}"))?; Ok(a.iter() .map(|x| Finding { path: rel_to(root, x["filename"].as_str().unwrap_or_default()), line: x["location"]["row"].as_u64().unwrap_or(1) as u32, col: x["location"]["column"].as_u64().unwrap_or(1) as u32, // ruff has no severities; syntax errors: code null (old) or "invalid-syntax" (new) severity: if x["code"].is_null() || x["code"] == "invalid-syntax" { 1 } else { 2 }, rule: x["code"].as_str().unwrap_or("syntax").to_string(), message: x["message"].as_str().unwrap_or_default().to_string(), source: "ruff".into(), }) .collect()) } async fn biome(root: &Path, files: &[PathBuf], timeout: Duration) -> Result, String> { let (o, _) = exec( sandboxed("biome") .args(["lint", "--reporter=json"]) .args(files) .current_dir(root), timeout, ) .await?; let v: Value = serde_json::from_slice(&o).map_err(|e| format!("biome output: {e}"))?; Ok(v["diagnostics"] .as_array() .into_iter() .flatten() .filter_map(|x| { let severity = match x["severity"].as_str()? { "error" | "fatal" => 1, "warning" => 2, _ => return None, }; Some(Finding { path: rel_to(root, x["location"]["path"].as_str().unwrap_or_default()), line: x["location"]["start"]["line"].as_u64().unwrap_or(1) as u32, col: x["location"]["start"]["column"].as_u64().unwrap_or(1) as u32, severity, rule: x["category"].as_str().unwrap_or_default().to_string(), message: x["message"].as_str().unwrap_or_default().to_string(), source: "biome".into(), }) }) .collect()) } async fn eslint(root: &Path, files: &[PathBuf], timeout: Duration) -> Result, String> { let (o, _) = exec( sandboxed("eslint") .args(["--format", "json"]) .args(files) .current_dir(root), timeout, ) .await?; let a: Vec = serde_json::from_slice(&o).map_err(|e| format!("eslint output: {e}"))?; Ok(a.iter() .flat_map(|f| { let p = rel_to(root, f["filePath"].as_str().unwrap_or_default()); f["messages"] .as_array() .cloned() .unwrap_or_default() .into_iter() .map(move |m| (p.clone(), m)) }) .map(|(p, m)| Finding { path: p, line: m["line"].as_u64().unwrap_or(1) as u32, col: m["column"].as_u64().unwrap_or(1) as u32, severity: if m["severity"] == 2 { 1 } else { 2 }, rule: m["ruleId"].as_str().unwrap_or_default().to_string(), message: m["message"].as_str().unwrap_or_default().to_string(), source: "eslint".into(), }) .collect()) } async fn ast_grep( root: &Path, files: &[PathBuf], timeout: Duration, ) -> Result, String> { let mut rules = vec![]; let mut paths: Vec<_> = std::fs::read_dir(root.join(".hx/rules")) .map_err(|e| e.to_string())? .flatten() .map(|e| e.path()) .collect(); paths.sort(); for p in paths .iter() .filter(|p| matches!(p.extension().and_then(|e| e.to_str()), Some("yml" | "yaml"))) { rules.push(std::fs::read_to_string(p).map_err(|e| e.to_string())?); } if rules.is_empty() { return Ok(vec![]); } let (o, _) = exec( sandboxed("ast-grep") .args(["scan", "--json=compact", "--inline-rules"]) .arg(rules.join("\n---\n")) .args(files) .current_dir(root), timeout, ) .await?; let a: Vec = serde_json::from_slice(&o).map_err(|e| format!("ast-grep output: {e}"))?; Ok(a.iter() .filter_map(|x| { let severity = match x["severity"].as_str().unwrap_or("error") { "error" => 1, "warning" => 2, _ => return None, }; Some(Finding { path: rel_to(root, x["file"].as_str().unwrap_or_default()), line: x["range"]["start"]["line"].as_u64().unwrap_or(0) as u32 + 1, col: x["range"]["start"]["column"].as_u64().unwrap_or(0) as u32 + 1, severity, rule: x["ruleId"].as_str().unwrap_or_default().to_string(), message: x["message"].as_str().unwrap_or_default().to_string(), source: "ast-grep".into(), }) }) .collect()) } #[cfg(test)] mod tests { use super::*; fn runner(id: &str) -> &'static Runner { RUNNERS.iter().find(|r| r.id == id).unwrap() } #[test] fn applicability() { let d = tempfile::tempdir().unwrap(); let ws = d.path(); std::fs::create_dir_all(ws.join("web/src")).unwrap(); std::fs::write(ws.join("web/biome.json"), "{}").unwrap(); let f = ws.join("web/src/a.ts"); assert_eq!( marker_root(&f, &["biome.json"], ws).as_deref(), Some(ws.join("web").as_path()) ); assert_eq!(marker_root(&ws.join("x.ts"), &["biome.json"], ws), None); assert_eq!(marker_root(&f, &[], ws).as_deref(), Some(ws)); // empty rules dir: ast-grep off std::fs::create_dir_all(ws.join(".hx/rules")).unwrap(); assert!(applies(runner("ast-grep"), &f, ws).is_none()); // wrong extension assert!(applies(runner("ruff"), &f, ws).is_none()); } #[tokio::test] async fn real_tools() { let d = tempfile::tempdir().unwrap(); let ws = d.path().to_path_buf(); let t = Duration::from_secs(60); if which("ruff") { let f = ws.join("p.py"); std::fs::write(&f, "import os\nx = (\n").unwrap(); let o = run(runner("ruff"), &ws, std::slice::from_ref(&f), t).await; assert!(o.error.is_none(), "{:?}", o.error); assert!( o.findings.iter().any(|x| x.severity == 1), "{:?}", o.findings ); std::fs::write(&f, "x = 1\n").unwrap(); let o = run(runner("ruff-format"), &ws, std::slice::from_ref(&f), t).await; assert!(o.changed == [f.clone()] && std::fs::read_to_string(&f).unwrap() == "x = 1\n"); } if which("biome") { std::fs::write(ws.join("biome.json"), "{}").unwrap(); let f = ws.join("a.js"); std::fs::write(&f, "if (x == 2) { debugger; }\n").unwrap(); let o = run(runner("biome"), &ws, std::slice::from_ref(&f), t).await; assert!( o.findings .iter() .any(|x| x.rule == "lint/suspicious/noDebugger" && x.line == 1), "{:?} {:?}", o.findings, o.error ); } if which("ast-grep") { std::fs::create_dir_all(ws.join(".hx/rules")).unwrap(); std::fs::write(ws.join(".hx/rules/u.yml"), "id: no-unwrap\nlanguage: rust\nseverity: warning\nmessage: avoid unwrap\nrule:\n pattern: $A.unwrap()\n").unwrap(); let f = ws.join("m.rs"); std::fs::write(&f, "fn main() {\n let v = Some(1).unwrap();\n}\n").unwrap(); assert!(applies(runner("ast-grep"), &f, &ws).is_some()); let other = ws.join("n.rs"); std::fs::write(&other, "fn g() { None::.unwrap(); }\n").unwrap(); let o = run(runner("ast-grep"), &ws, std::slice::from_ref(&f), t).await; assert_eq!(o.findings.len(), 1, "{:?}", o.error); assert_eq!( ( o.findings[0].line, o.findings[0].col, o.findings[0].severity ), (2, 13, 2) ); } } }