Classify every comment as tautology, stale, excuse or decision record. Tautology/stale/excuse comments are deleted (excuses filed as issues #196-#236), decisions moved to docs/adr/0001-0034. - scripts/lint-comments.sh + .comment-baseline: per-file comment count may only go down; wired into tests/all.sh - .claude/skills/delete-comment: repeatable audit workflow - cargo fmt applied to touched crates Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
506 lines
16 KiB
Rust
506 lines
16 KiB
Rust
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,
|
|
pub line: u32,
|
|
pub col: u32,
|
|
pub severity: u8,
|
|
pub rule: String,
|
|
pub message: String,
|
|
pub source: String,
|
|
}
|
|
|
|
impl Finding {
|
|
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],
|
|
pub markers: &'static [&'static str],
|
|
pub bin: &'static str,
|
|
}
|
|
|
|
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",
|
|
},
|
|
];
|
|
|
|
pub fn marker_root(file: &Path, markers: &[&str], ws: &Path) -> Option<PathBuf> {
|
|
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
|
|
}
|
|
|
|
pub fn applies(r: &Runner, file: &Path, ws: &Path) -> Option<PathBuf> {
|
|
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)?;
|
|
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<Finding>,
|
|
pub took: Duration,
|
|
pub error: Option<String>,
|
|
pub changed: Vec<PathBuf>,
|
|
}
|
|
|
|
async fn exec(cmd: &mut Command, timeout: Duration) -> Result<(Vec<u8>, Option<i32>), 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)
|
|
}
|
|
}
|
|
|
|
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<Option<Vec<u8>>> = 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
|
|
}
|
|
|
|
async fn clippy(root: &Path, timeout: Duration) -> Result<Vec<Finding>, 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::<Value>(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;
|
|
};
|
|
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<Vec<Finding>, String> {
|
|
let (o, _) = exec(
|
|
sandboxed("ruff")
|
|
.args(["check", "--output-format=json", "--no-fix", "--quiet"])
|
|
.args(files)
|
|
.current_dir(root),
|
|
timeout,
|
|
)
|
|
.await?;
|
|
let a: Vec<Value> = 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,
|
|
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<Vec<Finding>, 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<Vec<Finding>, String> {
|
|
let (o, _) = exec(
|
|
sandboxed("eslint")
|
|
.args(["--format", "json"])
|
|
.args(files)
|
|
.current_dir(root),
|
|
timeout,
|
|
)
|
|
.await?;
|
|
let a: Vec<Value> = 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<Vec<Finding>, 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<Value> = 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));
|
|
std::fs::create_dir_all(ws.join(".hx/rules")).unwrap();
|
|
assert!(applies(runner("ast-grep"), &f, ws).is_none());
|
|
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::<u8>.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)
|
|
);
|
|
}
|
|
}
|
|
}
|