Skip to main content

greengate_runtime/hooks/
rust_tools.rs

1//! The three Rust hooks: `cargo fmt --check`, `cargo clippy`, `cargo test`.
2//!
3//! Scoped like every other language hook — they fire only when the commit (or
4//! push) touches Rust, and only in a directory that actually has a `Cargo.toml`.
5//! A Python repo never invokes cargo.
6//!
7//! Split across the two dispatchers by COST, matching what the other languages
8//! already do: `fmt` and `clippy` are pre-commit (as ruff and pyright are),
9//! `test` is pre-push (as `run-tests-js` is). Nobody wants to wait for a
10//! workspace test run on every commit.
11//!
12//! Each is a separate check rather than one "rust" hook, so `hook.skip` can
13//! disable them individually — `git config hook.skip clippy` when you are
14//! mid-refactor, without losing the formatting gate.
15
16use super::common::{
17    fail, fixing_enabled, hl, ok, repo_root, restage, run as run_tool, say, staged_files, warn,
18    which, Restaged,
19};
20use crate::check::Outcome;
21use crate::git;
22use std::collections::BTreeSet;
23use std::path::{Path, PathBuf};
24use std::process::{Command, Stdio};
25
26/// Files that mean "this commit touches Rust". `Cargo.toml` and `Cargo.lock`
27/// count: a dependency bump compiles differently without a single `.rs` edit,
28/// and that is exactly when clippy earns its keep.
29///
30/// Exported for the registry: `pre-push-cargo-test` declares this whole set
31/// as its scope (rehearsal, pairing and stamps read the scope), and clippy
32/// consumes it while declaring only `.rs` plus a `Cargo.toml` opt-in.
33pub const RUST_PATHS: &[&str] = &[
34    ".rs",
35    "Cargo.toml",
36    "Cargo.lock",
37    "rustfmt.toml",
38    "clippy.toml",
39    // A pin bump changes which clippy judges the same source.
40    "rust-toolchain.toml",
41    "rust-toolchain",
42];
43
44/// What `cargo fmt` is handed. Exported so `registry.rs` declares the scope
45/// from the same constant — see `lint_json_yaml::EXTS`.
46pub const EXTS: &[&str] = &[".rs"];
47
48fn is_rust_path(f: &str) -> bool {
49    let name = f.rsplit('/').next().unwrap_or(f);
50    RUST_PATHS.iter().any(|pattern| {
51        if pattern.starts_with('.') {
52            name.ends_with(pattern)
53        } else {
54            name == *pattern
55        }
56    })
57}
58
59/// The nearest ancestor of `file` holding a `Cargo.toml`, bounded by the repo.
60///
61/// Not simply "the repo root": plenty of repos keep a Rust component in a
62/// subdirectory next to services in other languages, and cargo must run where
63/// the manifest is. For a member that is its own manifest, so a command that
64/// spans the workspace collapses these roots first (`workspace_roots`).
65fn cargo_root_for(root: &str, file: &str) -> Option<PathBuf> {
66    let mut dir = Path::new(root).join(file);
67    dir.pop();
68    loop {
69        if dir.join("Cargo.toml").is_file() {
70            return Some(dir);
71        }
72        if dir == Path::new(root) || !dir.starts_with(root) {
73            return None;
74        }
75        if !dir.pop() {
76            return None;
77        }
78    }
79}
80
81fn cargo_roots<'a>(root: &str, files: impl Iterator<Item = &'a str>) -> Vec<PathBuf> {
82    let mut seen = BTreeSet::new();
83    for f in files.filter(|f| is_rust_path(f)) {
84        if let Some(d) = cargo_root_for(root, f) {
85            seen.insert(d);
86        }
87    }
88    seen.into_iter().collect()
89}
90
91/// True when `cargo <component> --version` works.
92///
93/// Only for separately-installable COMPONENTS — rustfmt and clippy, which a
94/// toolchain can legitimately lack. A missing one must warn and pass, never
95/// fail a commit for a tool the developer never chose.
96///
97/// Do NOT probe a BUILT-IN subcommand this way: `cargo test --version` is
98/// "unexpected argument '--version'", so the probe reports test as unavailable
99/// and the gate silently passes — it would never have run a test anywhere.
100fn component_available(cargo: &[String], dir: &Path, sub: &str) -> bool {
101    let Some((program, rest)) = cargo.split_first() else {
102        return false;
103    };
104    Command::new(program)
105        .args(rest)
106        .arg(sub)
107        .arg("--version")
108        .current_dir(dir)
109        .stdin(Stdio::null())
110        .stdout(Stdio::null())
111        .stderr(Stdio::null())
112        .status()
113        .map(|s| s.success())
114        .unwrap_or(false)
115}
116
117/// The toolchain `dir` (or an ancestor) pins, with the file that pins it:
118/// `rust-toolchain.toml`'s `[toolchain] channel`, or the legacy one-line
119/// `rust-toolchain`. The walk is rustup's own — it reads the nearest pin
120/// above the working directory — so what this finds is what rustup applies.
121fn pinned_toolchain(dir: &Path) -> Option<(PathBuf, String)> {
122    let mut d = Some(dir);
123    while let Some(cur) = d {
124        let toml = cur.join("rust-toolchain.toml");
125        if let Ok(text) = std::fs::read_to_string(&toml) {
126            if let Some(ch) = parse_toolchain_toml(&text) {
127                return Some((toml, ch));
128            }
129        }
130        let legacy = cur.join("rust-toolchain");
131        if let Ok(text) = std::fs::read_to_string(&legacy) {
132            let ch = text.lines().next().unwrap_or("").trim();
133            if !ch.is_empty() {
134                return Some((legacy, ch.to_string()));
135            }
136        }
137        d = cur.parent();
138    }
139    None
140}
141
142/// `channel = "1.94.1"` out of a `rust-toolchain.toml`, ignoring comments.
143fn parse_toolchain_toml(text: &str) -> Option<String> {
144    text.lines()
145        .map(str::trim)
146        .filter(|l| !l.starts_with('#'))
147        .find_map(|l| {
148            let rest = l
149                .strip_prefix("channel")?
150                .trim_start()
151                .strip_prefix('=')?
152                .trim();
153            let rest = rest.split('#').next()?.trim();
154            let v = rest.trim_matches(|c| c == '"' || c == '\'');
155            (!v.is_empty()).then(|| v.to_string())
156        })
157}
158
159/// A pin we can hold a `cargo --version` against: `1.94` or `1.94.1`. A
160/// channel name (`stable`, `nightly-2026-01-01`) is a moving target and is
161/// left to rustup.
162fn version_pin(pin: &str) -> Option<&str> {
163    let parts: Vec<&str> = pin.split('.').collect();
164    let numeric = (2..=3).contains(&parts.len())
165        && parts
166            .iter()
167            .all(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit()));
168    numeric.then_some(pin)
169}
170
171/// `1.94.1` out of `cargo 1.94.1 (29ea6fb6a 2026-03-24)`, run where the pin
172/// applies so a rustup shim answers for that directory.
173fn cargo_version(cargo: &[String], dir: &Path) -> Option<String> {
174    let (program, rest) = cargo.split_first()?;
175    let out = Command::new(program)
176        .args(rest)
177        .arg("--version")
178        .current_dir(dir)
179        .stdin(Stdio::null())
180        .stderr(Stdio::null())
181        .output()
182        .ok()?;
183    let text = String::from_utf8_lossy(&out.stdout);
184    let v = text.split_whitespace().nth(1)?;
185    Some(v.to_string())
186}
187
188/// `1.94` matches `1.94.1`; `1.94.1` matches only itself.
189fn version_matches(pin: &str, version: &str) -> bool {
190    version == pin
191        || version
192            .strip_prefix(pin)
193            .is_some_and(|rest| rest.starts_with('.'))
194}
195
196/// The cargo invocation a directory means, as an argv. With a pin and a
197/// rustup: `rustup run <pin> cargo`, so the pin is applied by rustup AND
198/// exported (`RUSTUP_TOOLCHAIN`, PATH) to every `rustc` cargo spawns. Without
199/// either: the first `cargo` on PATH, as before.
200///
201/// Why not `which`: on a machine with a second cargo ahead of the rustup shim
202/// (Homebrew's `rust` formula in /usr/local/bin, measured 2026-09-21) it finds
203/// the wrong one and the pin is silently ignored — clippy then judges with
204/// lints CI never sees.
205///
206/// Why not the toolchain's cargo binary by path (`rustup which cargo`, the
207/// first shape of this fix): run directly, that cargo spawns each `rustc`
208/// through the PATH proxy with cwd set to the crate being compiled, and the
209/// proxy re-resolves the toolchain from THERE. A dependency that ships its own
210/// `rust-toolchain` — `convert_case` 0.10 pins 1.83.0 — was built by 1.83.0
211/// inside a 1.94.1 build: `E0514: crate compiled by an incompatible version
212/// of rustc`, on the release commit of the change itself. `rustup run` is
213/// the invocation that keeps one toolchain for the whole build.
214fn resolve_cargo(dir: &Path) -> Option<Vec<String>> {
215    if let Some((_, pin)) = pinned_toolchain(dir) {
216        if let Some(rustup) = which("rustup") {
217            return Some(vec![rustup, "run".into(), pin, "cargo".into()]);
218        }
219    }
220    which("cargo").map(|c| vec![c])
221}
222
223/// Resolve cargo, hold it against the pin, verify the component.
224///
225/// `Err(Outcome::Unavailable)` when there is no cargo or no component (warned,
226/// never failed: a tool the developer never chose cannot block a commit).
227/// `Err(Outcome::Failed)` when the cargo that would run is NOT the pinned
228/// toolchain: a green verdict from the wrong clippy is worth less than none,
229/// and a red one wastes time on lints that are not CI's.
230///
231/// Split out from `each_root` because `fmt` now runs TWO passes — a `--check`
232/// and, when repairing, a write — and the second must not re-probe rustfmt
233/// (a second `cargo fmt --version` per manifest root) nor duplicate the
234/// resolution it would have to get identical.
235fn cargo_for(
236    roots: &[PathBuf],
237    component: Option<&str>,
238    missing: &str,
239) -> Result<Vec<String>, Outcome> {
240    let first = roots
241        .first()
242        .map(PathBuf::as_path)
243        .unwrap_or(Path::new("."));
244    let Some(cargo) = resolve_cargo(first) else {
245        warn(missing);
246        return Err(Outcome::Unavailable);
247    };
248    for dir in roots {
249        let Some((file, pin)) = pinned_toolchain(dir) else {
250            continue;
251        };
252        let Some(got) = cargo_version(&cargo, dir) else {
253            // `rustup run <pin>` with nothing installed under that name
254            // answers nothing: say which toolchain to install rather than
255            // let the real run fail on rustup's own message.
256            fail(&format!(
257                "{} pins `{pin}` and no cargo answers for it. {}.",
258                file.display(),
259                hl(&format!("rustup toolchain install {pin}"))
260            ));
261            return Err(Outcome::Failed);
262        };
263        let Some(want) = version_pin(&pin) else {
264            continue;
265        };
266        if !version_matches(want, &got) {
267            fail(&format!(
268                "cargo is {got} but {} pins {want}, so this check would judge with a \
269                 toolchain CI never runs. Put the rustup shim first on PATH — a second \
270                 cargo ahead of it (Homebrew's {} in /usr/local/bin) is the usual cause — \
271                 or {}.",
272                file.display(),
273                hl("rust"),
274                hl(&format!("rustup toolchain install {want}"))
275            ));
276            return Err(Outcome::Failed);
277        }
278    }
279    if let Some(c) = component {
280        for dir in roots {
281            if !component_available(&cargo, dir, c) {
282                warn(missing);
283                return Err(Outcome::Unavailable);
284            }
285        }
286    }
287    Ok(cargo)
288}
289
290/// True when `args` make cargo act on the whole workspace from any member:
291/// `--workspace` (test, clippy's workspace mode) and `fmt --all`.
292fn spans_workspace(args: &[&str]) -> bool {
293    args.iter()
294        .take_while(|a| **a != "--")
295        .any(|a| *a == "--workspace" || (args.first() == Some(&"fmt") && *a == "--all"))
296}
297
298fn canonical(p: &Path) -> PathBuf {
299    std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf())
300}
301
302/// The workspace root cargo resolves for `dir`, asked of cargo itself
303/// (`locate-project --workspace`) so `exclude`, `package.workspace` and
304/// nested workspaces mean what cargo says. `None` when cargo does not answer.
305fn workspace_root(cargo: &[String], dir: &Path) -> Option<PathBuf> {
306    let (program, rest) = cargo.split_first()?;
307    let out = Command::new(program)
308        .args(rest)
309        .args(["locate-project", "--workspace", "--message-format", "plain"])
310        .current_dir(dir)
311        .stdin(Stdio::null())
312        .stderr(Stdio::null())
313        .output()
314        .ok()?;
315    if !out.status.success() {
316        return None;
317    }
318    let manifest = PathBuf::from(String::from_utf8_lossy(&out.stdout).trim());
319    manifest.parent().filter(|p| p.is_absolute()).map(canonical)
320}
321
322/// Manifest roots collapsed to their workspace roots, for a command that
323/// spans the workspace. `cargo_roots` gives the nearest `Cargo.toml` of each
324/// changed file, which for a member is the member's own manifest, and
325/// `cargo test --workspace` run from each member ran the whole suite once per
326/// touched member (six times for a six-crate change, 2026-11-10). A root cargo
327/// will not place, or places above `bound` (the repository or the pushed
328/// tree's checkout), is kept as it is: running it alone is what it did before.
329fn workspace_roots(cargo: &[String], roots: &[PathBuf], bound: &Path) -> Vec<PathBuf> {
330    let bound = canonical(bound);
331    let mut seen = BTreeSet::new();
332    for dir in roots {
333        let dir = canonical(dir);
334        let ws = workspace_root(cargo, &dir)
335            .filter(|ws| dir.starts_with(ws) && ws.starts_with(&bound))
336            .unwrap_or(dir);
337        seen.insert(ws);
338    }
339    seen.into_iter().collect()
340}
341
342/// Run one cargo invocation in every manifest root. True when all succeeded.
343///
344/// A command that spans the workspace runs once per workspace, not once per
345/// touched member. When more than one invocation is still due, each is
346/// announced, so a second suite run never looks like the first one stalling.
347/// The line is progress, like the dispatcher's "still running" lines, so
348/// `amont.quiet` does not hide it: an agent's piped run is where a silent
349/// second run cost two hours.
350fn run_in_roots(
351    settings: &crate::config::Settings,
352    roots: &[PathBuf],
353    bound: &Path,
354    argv: &[String],
355    args: &[&str],
356) -> bool {
357    let roots = if spans_workspace(args) {
358        workspace_roots(argv, roots, bound)
359    } else {
360        roots.to_vec()
361    };
362    let extra: Vec<String> = args.iter().map(|s| (*s).to_string()).collect();
363    let bound = canonical(bound);
364    let mut all_ok = true;
365    for (i, dir) in roots.iter().enumerate() {
366        if roots.len() > 1 {
367            let shown = canonical(dir);
368            let rel = shown
369                .strip_prefix(&bound)
370                .ok()
371                .map(|r| r.to_string_lossy().into_owned())
372                .filter(|r| !r.is_empty())
373                .unwrap_or_else(|| ".".into());
374            say(&format!(
375                "cargo {}: {} of {}, in {rel}",
376                args.first().copied().unwrap_or(""),
377                i + 1,
378                roots.len()
379            ));
380        }
381        let d = dir.to_string_lossy().into_owned();
382        if !run_tool(settings, &d, argv, &extra) {
383            all_ok = false;
384        }
385    }
386    all_ok
387}
388
389/// Shared shape: find the manifest roots, verify the component if there is one
390/// to verify, run the command in each, report once.
391///
392/// `component` is `Some` only for rustfmt/clippy; `None` means a built-in
393/// subcommand where cargo's own presence is the whole requirement.
394fn each_root(
395    settings: &crate::config::Settings,
396    roots: &[PathBuf],
397    bound: &Path,
398    component: Option<&str>,
399    args: &[&str],
400    missing: &str,
401) -> Result<bool, Outcome> {
402    let argv = cargo_for(roots, component, missing)?;
403    Ok(run_in_roots(settings, roots, bound, &argv, args))
404}
405
406pub fn fmt(settings: &crate::config::Settings, _args: &[std::ffi::OsString]) -> Outcome {
407    let files = staged_files(EXTS);
408    if files.is_empty() {
409        return Outcome::Passed;
410    }
411    let root = repo_root();
412    let roots = cargo_roots(&root, files.iter().map(String::as_str));
413    if roots.is_empty() {
414        return Outcome::Passed;
415    }
416    const MISSING: &str =
417        "Rust staged but rustfmt is not installed. `rustup component add rustfmt`.";
418    let argv = match cargo_for(&roots, Some("fmt"), MISSING) {
419        Ok(argv) => argv,
420        Err(outcome) => return outcome,
421    };
422
423    // `--all -- --check` per the project convention. It inspects the working
424    // TREE rather than the index — and that is now correct, because the
425    // pre-commit stage holds the unstaged changes aside for the duration, so
426    // the tree IS the staged content. This comment used to call that "the same
427    // trade-off cargo fmt gives everyone", which was true of the observation
428    // and wrong about the conclusion: see `staged_only`.
429    if run_in_roots(
430        settings,
431        &roots,
432        Path::new(&root),
433        &argv,
434        &["fmt", "--all", "--", "--check"],
435    ) {
436        ok(settings, "Rust formatting is clean");
437        return Outcome::Passed;
438    }
439
440    // The registry has always declared `Fix::Rewrite` for this check, and
441    // `amont list --json` reported `"fix":"rewrite"` — which `agents_md`
442    // explicitly tells agents to trust — while no fixing code existed
443    // anywhere. Only prettier and the manifest's externals ever called
444    // `restage`. Rather than downgrade the declaration, the fixing is now
445    // real.
446    if fixing_enabled(settings)
447        && run_in_roots(settings, &roots, Path::new(&root), &argv, &["fmt", "--all"])
448    {
449        // The non-obvious guard: `cargo fmt --all` formats the WHOLE
450        // workspace, not just the staged files — but `restage` is handed the
451        // staged `.rs` list, so nothing the author did not stage is staged
452        // here. The formatter's other edits stay in the working tree, exactly
453        // as an unrelated unstaged change would.
454        match restage(&files) {
455            Restaged::Staged => {
456                ok(settings, "Rust reformatted and re-staged");
457                return Outcome::Fixed;
458            }
459            Restaged::Failed(stuck) => {
460                fail(&format!(
461                    "cargo fmt rewrote these files but {} failed — the index still holds the \
462                     UNFORMATTED content: {}",
463                    hl("git add"),
464                    stuck.join(", ")
465                ));
466                return Outcome::Failed;
467            }
468            // Nothing staged differed, so whatever `--check` objected to was
469            // outside the staged set. Fall through and report it.
470            Restaged::Nothing => {}
471        }
472    }
473
474    fail(&format!("Unformatted Rust. Run {}.", hl("cargo fmt --all")));
475    Outcome::Failed
476}
477
478/// What pre-commit clippy judges (ADR-0009, `hooks.clippy-scope`). It runs
479/// in the package root nearest each staged `.rs`, and without `--workspace`
480/// cargo judges that package alone (the default members, at a virtual
481/// root). The whole workspace is judged when a manifest, the lockfile, a
482/// lint config or the toolchain pin is staged — they change how every
483/// package compiles — or when the file set is not the index
484/// (`--all-files`). Lints a change provokes in a DEPENDENT package are
485/// caught by CI's workspace clippy, not here: a cold `--workspace` per
486/// worktree was the longest and most lock-hungry check of a commit.
487pub fn clippy_args(staged: &[String], not_the_index: bool) -> &'static [&'static str] {
488    const PACKAGE: &[&str] = &[
489        "clippy",
490        "--all-targets",
491        "--all-features",
492        "--",
493        "-D",
494        "warnings",
495    ];
496    const WORKSPACE: &[&str] = &[
497        "clippy",
498        "--workspace",
499        "--all-targets",
500        "--all-features",
501        "--",
502        "-D",
503        "warnings",
504    ];
505    let shared = staged
506        .iter()
507        .any(|f| is_rust_path(f) && !f.ends_with(".rs"));
508    if not_the_index || shared {
509        WORKSPACE
510    } else {
511        PACKAGE
512    }
513}
514
515pub fn clippy(settings: &crate::config::Settings, _args: &[std::ffi::OsString]) -> Outcome {
516    // `staged_files` matches by suffix, which would also accept
517    // `vendor/NotCargo.toml`. `is_rust_path` compares the basename, so let it
518    // be the only filter rather than keeping two that disagree.
519    let files: Vec<String> = staged_files(&[])
520        .into_iter()
521        .filter(|f| is_rust_path(f))
522        .collect();
523    if files.is_empty() {
524        return Outcome::Passed;
525    }
526    let root = repo_root();
527    let roots = cargo_roots(&root, files.iter().map(String::as_str));
528    if roots.is_empty() {
529        return Outcome::Passed;
530    }
531    let args = clippy_args(&files, crate::hooks::common::not_the_index());
532    match each_root(
533        settings,
534        &roots,
535        Path::new(&root),
536        Some("clippy"),
537        args,
538        "Rust staged but clippy is not installed. `rustup component add clippy`.",
539    ) {
540        Err(outcome) => outcome,
541        Ok(true) => {
542            ok(settings, "Clippy passed");
543            Outcome::Passed
544        }
545        Ok(false) => {
546            fail(&format!(
547                "Clippy warnings. Fix them or run {}.",
548                hl("cargo clippy --fix")
549            ));
550            Outcome::Failed
551        }
552    }
553}
554
555/// pre-push. Mirrors `run-tests-js`: the range that is actually being pushed
556/// decides whether the suite runs, so a docs-only push costs nothing.
557///
558/// PER REF, not once for the whole push: `git push origin a b` carries two
559/// tips, and a single worktree checked out to the first one would run the
560/// second ref's tests against the first ref's tree — a real failure in the
561/// untested branch reported as a pass because nothing actually ran against
562/// it. Each ref that touches Rust gets its own worktree and its own verdict.
563pub fn test(
564    settings: &crate::config::Settings,
565    refs: &[crate::pushrefs::PushRef],
566    gate: &str,
567) -> Outcome {
568    // `Unavailable`, never `Passed`, when git will not answer — same argument
569    // and same wording as run-tests-js: a gate must not report green having
570    // asked nothing.
571    let Some(root) = git::stdout(&["rev-parse", "--show-toplevel"]) else {
572        super::common::warn("cargo-test: git would not answer — the gate did NOT run");
573        return Outcome::Unavailable;
574    };
575    let zero = git::stdout(&["hash-object", "--stdin"])
576        .map(|h| "0".repeat(h.len()))
577        .unwrap_or_else(|| "0".repeat(40));
578    let mut ran_any = false;
579    for r in refs {
580        let changed = crate::pushrefs::changed_files_for(r, &zero);
581        let roots = cargo_roots(&root, changed.iter().map(String::as_str));
582        if roots.is_empty() {
583            continue;
584        }
585        // Where THIS ref's suite runs decides what it is answering about.
586        // `_guard` owns the checkout for the length of this ref's run;
587        // dropping it removes the worktree before the next ref's begins.
588        let (where_, _guard) =
589            crate::pushed_tree::where_to_run(settings, &r.local_oid, &root, gate);
590        let roots: Vec<PathBuf> = roots
591            .iter()
592            .map(|rt| {
593                rt.strip_prefix(&root)
594                    .map(|rel| where_.join(rel))
595                    .unwrap_or_else(|_| rt.clone())
596            })
597            .collect();
598        match each_root(
599            settings,
600            &roots,
601            &where_,
602            None,
603            &["test", "--workspace", "--all-features"],
604            "Rust changed but cargo is not installed.",
605        ) {
606            Err(outcome) => return outcome,
607            Ok(true) => ran_any = true,
608            Ok(false) => {
609                fail("Rust tests failed. Push aborted.");
610                return Outcome::Failed;
611            }
612        }
613    }
614    if ran_any {
615        ok(settings, "Rust tests passed");
616    }
617    Outcome::Passed
618}
619
620#[cfg(test)]
621mod tests {
622    use super::*;
623
624    /// Only a command cargo runs over the whole workspace is collapsed to
625    /// the workspace root; clippy's per-package mode keeps one run per
626    /// touched package, and a `--workspace` after `--` is the tool's, not
627    /// cargo's.
628    #[test]
629    fn only_workspace_wide_commands_collapse_to_the_workspace() {
630        assert!(spans_workspace(&["test", "--workspace", "--all-features"]));
631        assert!(spans_workspace(&["fmt", "--all", "--", "--check"]));
632        assert!(spans_workspace(clippy_args(&["Cargo.toml".into()], false)));
633        assert!(!spans_workspace(clippy_args(&["src/a.rs".into()], false)));
634        assert!(!spans_workspace(&["clippy", "--", "--workspace"]));
635        assert!(!spans_workspace(&["test", "--all"]));
636    }
637
638    #[test]
639    fn recognises_rust_paths() {
640        assert!(is_rust_path("src/main.rs"));
641        assert!(is_rust_path("Cargo.toml"));
642        assert!(is_rust_path("crates/a/Cargo.lock"));
643        assert!(is_rust_path("rustfmt.toml"));
644        assert!(!is_rust_path("README.md"));
645        assert!(!is_rust_path("src/main.rsx"));
646        // A file merely CONTAINING the name is not the manifest.
647        assert!(!is_rust_path("docs/Cargo.toml.md"));
648        assert!(!is_rust_path("vendor/NotCargo.toml"));
649    }
650
651    #[test]
652    fn finds_the_nearest_manifest_not_the_repo_root() {
653        let tmp = std::env::temp_dir().join("amont-cargo-roots");
654        let _ = std::fs::remove_dir_all(&tmp);
655        let nested = tmp.join("services/engine");
656        std::fs::create_dir_all(nested.join("src")).unwrap();
657        std::fs::write(nested.join("Cargo.toml"), "[package]\n").unwrap();
658        let root = tmp.to_string_lossy().into_owned();
659
660        let got = cargo_roots(&root, ["services/engine/src/main.rs"].into_iter());
661        assert_eq!(got, vec![nested.clone()], "should find the nested manifest");
662
663        // A Rust file with no manifest anywhere above it is not a cargo project.
664        std::fs::create_dir_all(tmp.join("scripts")).unwrap();
665        let none = cargo_roots(&root, ["scripts/loose.rs"].into_iter());
666        assert!(none.is_empty(), "no manifest above it: {none:?}");
667        let _ = std::fs::remove_dir_all(&tmp);
668    }
669
670    #[test]
671    fn several_files_in_one_crate_yield_one_root() {
672        let tmp = std::env::temp_dir().join("amont-cargo-dedupe");
673        let _ = std::fs::remove_dir_all(&tmp);
674        std::fs::create_dir_all(tmp.join("src")).unwrap();
675        std::fs::write(tmp.join("Cargo.toml"), "[package]\n").unwrap();
676        let root = tmp.to_string_lossy().into_owned();
677        let got = cargo_roots(&root, ["src/a.rs", "src/b.rs", "Cargo.toml"].into_iter());
678        assert_eq!(got.len(), 1, "one cargo invocation, not three: {got:?}");
679        let _ = std::fs::remove_dir_all(&tmp);
680    }
681
682    #[test]
683    fn non_rust_files_select_nothing() {
684        let got = cargo_roots("/tmp", ["README.md", "a.py"].into_iter());
685        assert!(got.is_empty());
686    }
687
688    #[test]
689    fn reads_the_channel_out_of_the_toml() {
690        let text = "# pinned\n[toolchain]\nchannel = \"1.94.1\" # why\ncomponents = [\"clippy\"]\n";
691        assert_eq!(parse_toolchain_toml(text).as_deref(), Some("1.94.1"));
692        assert_eq!(
693            parse_toolchain_toml("[toolchain]\nchannel = 'stable'\n").as_deref(),
694            Some("stable")
695        );
696        assert_eq!(parse_toolchain_toml("[toolchain]\ncomponents = []\n"), None);
697        assert_eq!(parse_toolchain_toml("# channel = \"1.0\"\n"), None);
698    }
699
700    #[test]
701    fn only_a_version_is_held_against_cargo() {
702        assert_eq!(version_pin("1.94.1"), Some("1.94.1"));
703        assert_eq!(version_pin("1.94"), Some("1.94"));
704        assert_eq!(version_pin("stable"), None);
705        assert_eq!(version_pin("nightly-2026-01-01"), None);
706        assert_eq!(version_pin("1"), None);
707        assert!(version_matches("1.94.1", "1.94.1"));
708        assert!(version_matches("1.94", "1.94.1"));
709        assert!(!version_matches("1.94.1", "1.98.0"));
710        assert!(!version_matches("1.9", "1.94.1"));
711    }
712
713    #[test]
714    fn the_nearest_pin_above_the_manifest_wins() {
715        let tmp = std::env::temp_dir().join("amont-toolchain-pin");
716        let _ = std::fs::remove_dir_all(&tmp);
717        let nested = tmp.join("services/engine");
718        std::fs::create_dir_all(&nested).unwrap();
719        std::fs::write(tmp.join("rust-toolchain"), "1.85.0\n").unwrap();
720        let (file, pin) = pinned_toolchain(&nested).unwrap();
721        assert_eq!((file, pin.as_str()), (tmp.join("rust-toolchain"), "1.85.0"));
722        std::fs::write(
723            nested.join("rust-toolchain.toml"),
724            "[toolchain]\nchannel = \"1.94.1\"\n",
725        )
726        .unwrap();
727        let (file, pin) = pinned_toolchain(&nested).unwrap();
728        assert_eq!(
729            (file, pin.as_str()),
730            (nested.join("rust-toolchain.toml"), "1.94.1")
731        );
732        let _ = std::fs::remove_dir_all(&tmp);
733    }
734    /// Source alone: the package, no `--workspace`. A manifest, lockfile,
735    /// lint config or pin staged, or a file set that is not the index:
736    /// the whole workspace.
737    #[test]
738    fn clippy_judges_the_package_unless_something_shared_is_staged() {
739        use super::clippy_args;
740        let s = |v: &[&str]| v.iter().map(|x| x.to_string()).collect::<Vec<_>>();
741        let pkg = clippy_args(&s(&["crates/a/src/lib.rs", "README.md"]), false);
742        assert!(!pkg.contains(&"--workspace"), "{pkg:?}");
743        assert_eq!(pkg.first(), Some(&"clippy"));
744        for shared in [
745            "Cargo.lock",
746            "crates/a/Cargo.toml",
747            "clippy.toml",
748            "rust-toolchain.toml",
749        ] {
750            let ws = clippy_args(&s(&["crates/a/src/lib.rs", shared]), false);
751            assert!(ws.contains(&"--workspace"), "{shared}: {ws:?}");
752        }
753        assert!(clippy_args(&s(&["crates/a/src/lib.rs"]), true).contains(&"--workspace"));
754    }
755}