drep/languages/runner/mod.rs
1//! Run a project's own deterministic checkers and turn their output into Findings.
2//!
3//! This is the gating half of analysis. Tool findings are precise - they come
4//! from the rules the project itself configured - so they block, while the
5//! LLM's semantic findings inform. Keeping the two apart by *source* rather
6//! than by severity is what makes the gate calibratable at all.
7//!
8//! Three states, deliberately distinct:
9//!
10//! - [`ToolStatus::Ok`] the tool ran; its findings are authoritative.
11//! - [`ToolStatus::Skipped`] the project has not configured this tool, so it
12//! has no opinion here. A pass.
13//! - [`ToolStatus::Unavailable`] the tool should have run and could not.
14//! **Not** a pass - reporting it as clean is the same "unanalyzed is not
15//! clean" mistake that would let a commit gate rubber-stamp commits.
16
17use std::path::{Path, PathBuf};
18use std::process::Stdio;
19use std::time::Duration;
20
21use tokio::process::Command;
22
23use crate::analysis::findings::Finding;
24use crate::languages::spec::{DEFAULT_TOOL_TIMEOUT_SECS, DiagnosticsStream, ToolSpec};
25
26mod narrow;
27pub mod parsers;
28mod uri;
29
30pub use parsers::parse_output;
31
32pub(crate) use narrow::joined_reported;
33use narrow::retain_requested;
34
35#[cfg(test)]
36mod tests;
37
38/// Default ceiling for deterministic tools. Individual tools can extend it
39/// when their own execution model includes a legitimate wait, such as Cargo's
40/// build-directory lock.
41pub const TOOL_TIMEOUT: Duration = Duration::from_secs(DEFAULT_TOOL_TIMEOUT_SECS);
42
43/// Whether a tool ran, declined to run, or failed to.
44///
45/// The three are distinct because only the third is a problem: `Skipped` is
46/// the project exercising a choice, `Unavailable` is drep failing to check
47/// something it was supposed to.
48#[derive(Debug, Clone, PartialEq, Eq)]
49pub enum ToolStatus {
50 /// The tool ran. Its findings are authoritative.
51 Ok,
52 /// The project has not configured this tool, so it has no opinion here.
53 Skipped,
54 /// The tool should have run and could not. **Not** a pass.
55 Unavailable,
56}
57
58/// What happened when one tool was asked to check some files.
59#[derive(Debug, Clone, PartialEq, Eq)]
60pub struct ToolOutcome {
61 pub tool: &'static str,
62 pub status: ToolStatus,
63 pub findings: Vec<Finding>,
64 pub detail: String,
65 pub compilation_succeeded: bool,
66}
67
68impl ToolOutcome {
69 fn skipped(spec: &ToolSpec) -> Self {
70 let listed = spec.config_files[..spec.config_files.len().min(3)].join(", ");
71 Self::empty(
72 spec,
73 ToolStatus::Skipped,
74 format!("not configured (add one of: {listed})"),
75 )
76 }
77
78 fn unavailable(spec: &ToolSpec, detail: String) -> Self {
79 Self::empty(spec, ToolStatus::Unavailable, detail)
80 }
81
82 fn ready(spec: &ToolSpec) -> Self {
83 Self::empty(spec, ToolStatus::Ok, "ready".to_owned())
84 }
85
86 fn empty(spec: &ToolSpec, status: ToolStatus, detail: String) -> Self {
87 Self {
88 tool: spec.name,
89 status,
90 findings: Vec::new(),
91 detail,
92 compilation_succeeded: false,
93 }
94 }
95}
96
97/// The tool produced output we could not parse.
98///
99/// Raised rather than swallowed: unparseable output means we do not know
100/// whether the file is clean, and guessing "clean" is the failure this module
101/// exists to prevent.
102#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
103#[error("{0}")]
104pub struct ToolOutputError(pub String);
105
106/// Whether a path is a regular file that the OS will execute.
107///
108/// `pub(crate)` because `cli::init` needs the same answer when it decides
109/// whether a git hook will actually run - git ignores a non-executable hook
110/// silently, which is the same class of failure this function was written for.
111/// Two definitions of "executable" that could disagree is exactly the bug.
112///
113/// One function with the `cfg` inside its body, not two cfg-gated
114/// definitions. Two definitions means the inactive one is unreachable on
115/// this platform, so every mutation of it survives by construction and
116/// shows up as an untestable finding in `cargo mutants`. This way the
117/// mutation lands in code the tests actually run.
118pub(crate) fn is_executable(path: &Path) -> bool {
119 #[cfg(unix)]
120 {
121 use std::os::unix::fs::PermissionsExt;
122 match path.metadata() {
123 Ok(meta) => meta.is_file() && meta.permissions().mode() & 0o111 != 0,
124 Err(_) => false,
125 }
126 }
127 // Windows has no executable bit; existence is the only signal there is.
128 #[cfg(not(unix))]
129 {
130 path.is_file()
131 }
132}
133
134/// Find the executable for a tool, preferring the project's own copy.
135///
136/// Repo-local first so a project is checked by the version its CI runs -
137/// `node_modules/.bin/eslint` rather than whatever happens to be installed
138/// globally, which may resolve plugins differently or not at all.
139///
140/// A path that exists but is not executable is **skipped**, not failed -
141/// half-installed shims on `PATH` would otherwise block a tool that
142/// happens to be on PATH under the same name.
143pub fn resolve_tool(spec: &ToolSpec, root: &Path) -> Option<PathBuf> {
144 resolve_tool_in(spec, root, std::env::var_os("PATH").as_deref())
145}
146
147/// `resolve_tool`, against an explicit `PATH` value. See [`which_first_in`]
148/// for why this seam exists.
149pub(crate) fn resolve_tool_in(
150 spec: &ToolSpec,
151 root: &Path,
152 path: Option<&std::ffi::OsStr>,
153) -> Option<PathBuf> {
154 resolve_tool_at(spec, root, root, path)
155}
156
157/// Resolve a tool for a configured workspace, allowing dependencies hoisted
158/// to any ancestor up to the repository root.
159fn resolve_tool_at(
160 spec: &ToolSpec,
161 repository_root: &Path,
162 workspace_root: &Path,
163 path: Option<&std::ffi::OsStr>,
164) -> Option<PathBuf> {
165 for directory in ancestors_within(workspace_root, repository_root) {
166 for relative in spec.local_paths {
167 let candidate = directory.join(relative);
168 if is_executable(&candidate) {
169 return Some(candidate);
170 }
171 }
172 }
173
174 // `first()`, not `[0]`. A `ToolSpec` with an empty `command` is a
175 // definitions bug, but this function is documented never to panic and a
176 // panic here would take the whole gate down rather than reporting the
177 // tool unavailable.
178 let name = spec.command.first()?;
179 which_first_in(name, path?).map(PathBuf::from)
180}
181
182pub(crate) fn absolute(path: &Path) -> PathBuf {
183 if path.is_absolute() {
184 path.to_path_buf()
185 } else {
186 std::env::current_dir()
187 .map(|cwd| cwd.join(path))
188 .unwrap_or_else(|_| path.to_path_buf())
189 }
190}
191
192fn ancestors_within(start: &Path, root: &Path) -> Vec<PathBuf> {
193 let root = absolute(root);
194 let start = absolute(start);
195 if !start.starts_with(&root) {
196 return Vec::new();
197 }
198 start
199 .ancestors()
200 .take_while(|ancestor| ancestor.starts_with(&root))
201 .map(Path::to_path_buf)
202 .collect()
203}
204
205/// Look up `command` on PATH; `std::process::Command` does not expose this
206/// resolution directly.
207///
208/// Crucially checks executability, not just existence: a half-installed
209/// shim on PATH that is not executable would otherwise be reported as `Ok`
210/// by `tool_status` only to fail when `run_tool` actually executed it.
211/// Using the same `is_executable` helper the repo-local branch uses keeps
212/// the two paths consistent — a path that passes one is rejected by the
213/// other is the bug this guard exists to prevent.
214/// `which_first`, against an explicit `PATH` value.
215///
216/// Split out so tests can exercise PATH lookup without mutating the process
217/// environment. `std::env::set_var` is `unsafe` in edition 2024 because any
218/// other thread reading the environment concurrently is a data race - and
219/// these tests run beside ones that spawn `git`, which reads `PATH` to find
220/// it. A test-local mutex cannot fix that: it excludes other tests that take
221/// the same mutex, not every reader in the process. Passing the value in
222/// removes the shared mutable state instead of guarding it.
223fn which_first_in(command: &str, path: &std::ffi::OsStr) -> Option<String> {
224 for dir in std::env::split_paths(path) {
225 let candidate = dir.join(command);
226 if is_executable(&candidate) {
227 return Some(candidate.to_string_lossy().into_owned());
228 }
229 }
230 None
231}
232
233/// Whether the project has opted into this tool.
234///
235/// "Style adherence where defined": a repo with no eslint config has not
236/// chosen eslint's defaults, so running it would invent findings the
237/// project never asked for.
238pub fn is_configured(spec: &ToolSpec, root: &Path) -> bool {
239 configured_marker(spec, root).is_some()
240}
241
242/// Which of `config_files` is present in `root`, in declaration order.
243///
244/// One definition of "which config file is here", because two callers need
245/// the answer and they need slightly different halves of it: eligibility
246/// wants only whether there was one, while `config_flag` has to pass the
247/// *name* to a tool that will not look for its own. The flag branch used to
248/// ask separately with a bare `join(name).exists()`, which does not
249/// understand the leading `*.` glob `marker_match` accepts - so a spec
250/// pairing a glob marker with a flag would be judged configured and then run
251/// without the flag it needs. Only the pairing of tools kept that dormant:
252/// `dotnet format` already has glob markers and checkstyle already has a
253/// flag.
254///
255/// The list reads as a preference rather than as whatever the filesystem
256/// returns, so the first declared match wins.
257fn configured_marker(spec: &ToolSpec, root: &Path) -> Option<String> {
258 spec.config_files
259 .iter()
260 .find_map(|name| marker_match(root, name))
261}
262
263/// The marker `name` claims in `root`, as the name of the file found.
264///
265/// A `*.ext` entry matches any file in the directory carrying that extension.
266/// C# is the first language whose workspace is identified by a glob rather
267/// than a fixed name: MSBuild has to run from the directory holding the
268/// `.csproj` or `.sln`, and those are named after the project. Keying
269/// `dotnet format` on `.editorconfig` instead - the file it reads its rules
270/// from - picks whichever ancestor happens to hold one, which in a solution
271/// laid out with projects in subdirectories is a directory with no project in
272/// it at all, where MSBuild exits with "Could not find a project or solution
273/// file" and drep reports a configured tool that could not run.
274///
275/// Only a leading `*.` is a glob. A name is otherwise taken literally, so
276/// `.eslintrc.json` and the rest keep costing one `exists` rather than a
277/// directory read.
278fn marker_match(root: &Path, name: &str) -> Option<String> {
279 let Some(extension) = name.strip_prefix("*.") else {
280 return root.join(name).exists().then(|| name.to_owned());
281 };
282 let Ok(entries) = std::fs::read_dir(root) else {
283 // An unreadable directory holds no marker we can see. `exists()`
284 // answers false the same way for a path we cannot stat.
285 return None;
286 };
287 entries.flatten().find_map(|entry| {
288 let found = entry.file_name();
289 // The extension test first: it is a string comparison that rejects
290 // nearly every entry, while `file_type` falls back to an `lstat`
291 // whenever `readdir` reports `DT_UNKNOWN` (network mounts, some FUSE
292 // filesystems). This predicate runs once per ancestor directory per
293 // file per spec, so the selective half belongs in front.
294 //
295 // A *file* with the extension: a directory named `Widget.csproj` is
296 // not a project, and counting it would run the tool one level above
297 // the project it was meant to find.
298 let matches = Path::new(&found)
299 .extension()
300 .is_some_and(|ext| ext.eq_ignore_ascii_case(extension))
301 && entry.file_type().is_ok_and(|kind| kind.is_file());
302 matches.then(|| found.to_string_lossy().into_owned())
303 })
304}
305
306/// The nearest configured ancestor for `file`, bounded by `repository_root`.
307///
308/// Looking along the file's ancestor chain avoids both monorepo blind spots
309/// and accidental discovery in unrelated dependency/build directories.
310pub(crate) fn configuration_root(
311 spec: &ToolSpec,
312 repository_root: &Path,
313 file: &Path,
314) -> Option<PathBuf> {
315 let repository_root = absolute(repository_root);
316 let file = if file.is_absolute() {
317 file.to_path_buf()
318 } else {
319 repository_root.join(file)
320 };
321 ancestors_within(file.parent()?, &repository_root)
322 .into_iter()
323 .find(|directory| is_configured(spec, directory))
324}
325
326/// Whether this tool will run here, without running it.
327///
328/// The single derivation of eligibility, so `drep doctor` reports exactly
329/// what `drep check` will do. Deriving it twice means doctor confidently
330/// says "ready" for a tool check then skips - the failure doctor exists
331/// to prevent.
332pub fn tool_status(spec: &ToolSpec, root: &Path) -> ToolOutcome {
333 tool_status_at(spec, root, root)
334}
335
336/// Run one deterministic tool over some files.
337///
338/// Never returns an error and never panics for an absent or failing tool;
339/// that is reported as [`ToolStatus::Unavailable`] so the caller can surface
340/// it rather than mistake it for a clean result.
341pub async fn run_tool(spec: &ToolSpec, root: &Path, files: &[String]) -> ToolOutcome {
342 run_tool_at(spec, root, root, files).await
343}
344
345/// Run a tool from one configured workspace, resolving hoisted executables
346/// through the repository root.
347pub(crate) async fn run_tool_at(
348 spec: &ToolSpec,
349 repository_root: &Path,
350 workspace_root: &Path,
351 files: &[String],
352) -> ToolOutcome {
353 let executable = match eligible_executable(spec, repository_root, workspace_root) {
354 Ok(executable) => executable,
355 Err(outcome) => return outcome,
356 };
357
358 // Absolutised before spawning. `resolve_tool` returns `root.join(relative)`
359 // for a repo-local hit, and the child gets `current_dir(root)` below - so a
360 // relative `root` like "repo" produced "repo/node_modules/.bin/eslint"
361 // resolved *from* "repo", i.e. "repo/repo/node_modules/...". It works today
362 // only because the CLI passes "." and the tests pass absolute temp dirs.
363 let executable = if executable.is_relative() {
364 std::env::current_dir()
365 .map(|cwd| cwd.join(&executable))
366 .unwrap_or(executable)
367 } else {
368 executable
369 };
370
371 let mut argv: Vec<String> = Vec::with_capacity(spec.command.len() + files.len() + 2);
372 argv.push(executable.to_string_lossy().into_owned());
373 argv.extend(spec.command[1..].iter().map(|s| (*s).to_owned()));
374 // A tool that will not look for its own config gets handed the one
375 // `config_files` found - through the same lookup that decided the tool was
376 // configured at all, so the two cannot disagree about what counts.
377 if let Some(flag) = spec.config_flag
378 && let Some(config) = configured_marker(spec, workspace_root)
379 {
380 argv.push(flag.to_owned());
381 argv.push(config);
382 }
383 // A repository can contain a file whose name begins with `-`, and every
384 // checker here would read `--fix` as an option rather than a path. `--`
385 // is the conventional guard but is not universally supported across
386 // ruff/eslint/tsc/gofmt/go vet/clippy, whereas a `./` prefix is
387 // unambiguous to any argument parser and leaves ordinary paths untouched.
388 // A whole-project tool is invoked bare. `cargo clippy` rejects a path
389 // argument outright ("unexpected argument"), so appending files made every
390 // Rust run fail - reported honestly as `Unavailable`, which is why it
391 // surfaced as exit 2 on every Rust repository rather than as wrong
392 // findings. Its output is narrowed back to `files` after parsing.
393 if spec.accepts_files {
394 argv.extend(files.iter().map(|f| {
395 if f.starts_with('-') {
396 format!("./{f}")
397 } else {
398 f.clone()
399 }
400 }));
401 }
402
403 let mut command = Command::new(&argv[0]);
404 command.args(&argv[1..]);
405 command.current_dir(workspace_root);
406 command.stdin(Stdio::null());
407 command.stdout(Stdio::piped());
408 command.stderr(Stdio::piped());
409 command.kill_on_drop(true);
410
411 let child = match command.spawn() {
412 Ok(child) => child,
413 Err(err) => {
414 return ToolOutcome::unavailable(
415 spec,
416 format!("{} could not be executed: {err}", spec.name),
417 );
418 }
419 };
420
421 // `wait_with_output` drains both pipes into buffers before returning,
422 // and rejects on any IO error from the spawn or the read.
423 let timeout = Duration::from_secs(spec.timeout_secs);
424 let output = match tokio::time::timeout(timeout, child.wait_with_output()).await {
425 Ok(Ok(output)) => output,
426 Ok(Err(err)) => {
427 return ToolOutcome::unavailable(
428 spec,
429 format!("{} could not be executed: {err}", spec.name),
430 );
431 }
432 Err(_) => {
433 let context = spec.timeout_context.unwrap_or_default();
434 return ToolOutcome::unavailable(
435 spec,
436 format!(
437 "{} timed out after {}s{context}",
438 spec.name, spec.timeout_secs
439 ),
440 );
441 }
442 };
443
444 // The exit code alone is not a verdict: ruff/eslint/clippy exit non-zero
445 // *because* they found issues, and that is the success path. But it is not
446 // irrelevant either. A tool that exits non-zero having produced no
447 // diagnostics at all did not run - a bad config, a crash, a bad
448 // invocation - and reporting that as `Ok` with zero findings is precisely
449 // the "unavailable is not a pass" failure this module exists to prevent.
450 // So the rule is the conjunction: non-zero AND nothing on the diagnostics
451 // stream. For the skipping parsers the conjunction needs a second form:
452 // they drop lines they do not recognise by design, so a run whose every
453 // diagnostic is of a shape they do not know - an SDK error such as
454 // MSBuild's position-less `x.csproj : error NETSDK1004`, a rejected tsc
455 // option - parses as zero findings on a *non-empty* stream, invisible to
456 // the first form. The JSON-shaped parsers error on such output instead,
457 // which is already `Unavailable`.
458 let stdout = String::from_utf8_lossy(&output.stdout);
459 let stderr = String::from_utf8_lossy(&output.stderr);
460 let (diagnostics, other) = match spec.diagnostics_stream {
461 DiagnosticsStream::Stderr => (stderr.as_ref(), stdout.as_ref()),
462 DiagnosticsStream::Stdout => (stdout.as_ref(), stderr.as_ref()),
463 };
464
465 let parse_result = parse_output(
466 spec,
467 diagnostics,
468 files.first().map(String::as_str).unwrap_or(""),
469 );
470 let compilation_succeeded = spec.establishes_compilation && output.status.success();
471 match parse_result {
472 Ok(findings)
473 if findings.is_empty() && !output.status.success() && diagnostics.trim().is_empty() =>
474 {
475 // Exited non-zero, said nothing on the stream we read for
476 // diagnostics, and produced no findings. Whatever it did, it did
477 // not check the files. The other stream usually carries the real
478 // error, so it becomes the detail.
479 ToolOutcome::unavailable(
480 spec,
481 format!(
482 "{} exited {} without producing diagnostics: {}",
483 spec.name,
484 exit_word(&output.status),
485 stream_detail(other)
486 ),
487 )
488 }
489 Ok(findings)
490 if findings.is_empty()
491 && !output.status.success()
492 && spec.output_format.skips_unmatched_input() =>
493 {
494 // Exited non-zero and every line it did produce was dropped by a
495 // parser that skips what it cannot match: the run failed in a
496 // shape the parser does not know. The unmatched lines are the
497 // diagnostic, so they become the detail.
498 ToolOutcome::unavailable(
499 spec,
500 format!(
501 "{} exited {} without a recognisable diagnostic: {}",
502 spec.name,
503 exit_word(&output.status),
504 stream_detail(diagnostics)
505 ),
506 )
507 }
508 Ok(findings) => ToolOutcome {
509 tool: spec.name,
510 status: ToolStatus::Ok,
511 findings: retain_requested(spec, findings, files, workspace_root),
512 detail: stream_detail(other),
513 compilation_succeeded,
514 },
515 Err(err) => ToolOutcome::unavailable(
516 spec,
517 format!("{err}. other stream: {}", stream_detail(other)),
518 ),
519 }
520}
521
522pub(crate) fn tool_status_at(
523 spec: &ToolSpec,
524 repository_root: &Path,
525 workspace_root: &Path,
526) -> ToolOutcome {
527 match eligible_executable(spec, repository_root, workspace_root) {
528 Ok(_) => ToolOutcome::ready(spec),
529 Err(outcome) => outcome,
530 }
531}
532
533fn eligible_executable(
534 spec: &ToolSpec,
535 repository_root: &Path,
536 workspace_root: &Path,
537) -> Result<PathBuf, ToolOutcome> {
538 if !is_configured(spec, workspace_root) {
539 return Err(ToolOutcome::skipped(spec));
540 }
541 if let Some(executable) = resolve_tool_at(
542 spec,
543 repository_root,
544 workspace_root,
545 std::env::var_os("PATH").as_deref(),
546 ) {
547 return Ok(executable);
548 }
549 let looked = if spec.local_paths.is_empty() {
550 "PATH".to_owned()
551 } else if absolute(repository_root) == absolute(workspace_root) {
552 format!("{}, then PATH", spec.local_paths.join(", "))
553 } else {
554 format!(
555 "{} from {} through {}, then PATH",
556 spec.local_paths.join(", "),
557 workspace_root.display(),
558 repository_root.display()
559 )
560 };
561 Err(ToolOutcome::unavailable(
562 spec,
563 format!("configured but not found (looked in {looked})"),
564 ))
565}
566
567/// One of a tool's own streams, bounded for the `detail` field.
568///
569/// `crate::text::excerpt` is the single bounding of text drep did not write,
570/// and a tool's stdout and stderr are exactly that: they reach a terminal
571/// through `doctor` and through the failure block, so an escape sequence in
572/// them must be stripped rather than passed through. The predecessor here
573/// bounded *bytes* and stripped nothing, which is the second copy that rule
574/// exists to prevent.
575///
576/// The empty case is the one thing `excerpt` cannot answer for this caller.
577/// A clean run's other stream is legitimately empty and `detail` is then the
578/// empty string; `excerpt` returns `<nothing>`, which is right for a quoted
579/// model response and wrong for a field `doctor` prints after a colon.
580pub(crate) fn stream_detail(stream: &str) -> String {
581 let trimmed = stream.trim();
582 if trimmed.is_empty() {
583 return String::new();
584 }
585 crate::text::excerpt(trimmed, DETAIL_MAX_CHARS)
586}
587
588/// How much of a tool's stream reaches the `detail` field.
589const DETAIL_MAX_CHARS: usize = 200;
590
591/// How a process ended, for a diagnostic sentence.
592///
593/// Shared by the two `Unavailable` arms below so the signal wording has one
594/// definition rather than one per arm.
595fn exit_word(status: &std::process::ExitStatus) -> String {
596 status
597 .code()
598 .map_or("by signal".to_owned(), |code| code.to_string())
599}