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, staged_files, warn, which,
18    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. `--workspace` then covers every member from that point, so
64/// one invocation per manifest root is enough.
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/// Run one cargo invocation in every manifest root. True when all succeeded.
291fn run_in_roots(
292    settings: &crate::config::Settings,
293    roots: &[PathBuf],
294    argv: &[String],
295    args: &[&str],
296) -> bool {
297    let extra: Vec<String> = args.iter().map(|s| (*s).to_string()).collect();
298    let mut all_ok = true;
299    for dir in roots {
300        let d = dir.to_string_lossy().into_owned();
301        if !run_tool(settings, &d, argv, &extra) {
302            all_ok = false;
303        }
304    }
305    all_ok
306}
307
308/// Shared shape: find the manifest roots, verify the component if there is one
309/// to verify, run the command in each, report once.
310///
311/// `component` is `Some` only for rustfmt/clippy; `None` means a built-in
312/// subcommand where cargo's own presence is the whole requirement.
313fn each_root(
314    settings: &crate::config::Settings,
315    roots: &[PathBuf],
316    component: Option<&str>,
317    args: &[&str],
318    missing: &str,
319) -> Result<bool, Outcome> {
320    let argv = cargo_for(roots, component, missing)?;
321    Ok(run_in_roots(settings, roots, &argv, args))
322}
323
324pub fn fmt(settings: &crate::config::Settings, _args: &[std::ffi::OsString]) -> Outcome {
325    let files = staged_files(EXTS);
326    if files.is_empty() {
327        return Outcome::Passed;
328    }
329    let root = repo_root();
330    let roots = cargo_roots(&root, files.iter().map(String::as_str));
331    if roots.is_empty() {
332        return Outcome::Passed;
333    }
334    const MISSING: &str =
335        "Rust staged but rustfmt is not installed. `rustup component add rustfmt`.";
336    let argv = match cargo_for(&roots, Some("fmt"), MISSING) {
337        Ok(argv) => argv,
338        Err(outcome) => return outcome,
339    };
340
341    // `--all -- --check` per the project convention. It inspects the working
342    // TREE rather than the index — and that is now correct, because the
343    // pre-commit stage holds the unstaged changes aside for the duration, so
344    // the tree IS the staged content. This comment used to call that "the same
345    // trade-off cargo fmt gives everyone", which was true of the observation
346    // and wrong about the conclusion: see `staged_only`.
347    if run_in_roots(settings, &roots, &argv, &["fmt", "--all", "--", "--check"]) {
348        ok(settings, "Rust formatting is clean");
349        return Outcome::Passed;
350    }
351
352    // The registry has always declared `Fix::Rewrite` for this check, and
353    // `amont list --json` reported `"fix":"rewrite"` — which `agents_md`
354    // explicitly tells agents to trust — while no fixing code existed
355    // anywhere. Only prettier and the manifest's externals ever called
356    // `restage`. Rather than downgrade the declaration, the fixing is now
357    // real.
358    if fixing_enabled(settings) && run_in_roots(settings, &roots, &argv, &["fmt", "--all"]) {
359        // The non-obvious guard: `cargo fmt --all` formats the WHOLE
360        // workspace, not just the staged files — but `restage` is handed the
361        // staged `.rs` list, so nothing the author did not stage is staged
362        // here. The formatter's other edits stay in the working tree, exactly
363        // as an unrelated unstaged change would.
364        match restage(&files) {
365            Restaged::Staged => {
366                ok(settings, "Rust reformatted and re-staged");
367                return Outcome::Fixed;
368            }
369            Restaged::Failed(stuck) => {
370                fail(&format!(
371                    "cargo fmt rewrote these files but {} failed — the index still holds the \
372                     UNFORMATTED content: {}",
373                    hl("git add"),
374                    stuck.join(", ")
375                ));
376                return Outcome::Failed;
377            }
378            // Nothing staged differed, so whatever `--check` objected to was
379            // outside the staged set. Fall through and report it.
380            Restaged::Nothing => {}
381        }
382    }
383
384    fail(&format!("Unformatted Rust. Run {}.", hl("cargo fmt --all")));
385    Outcome::Failed
386}
387
388/// What pre-commit clippy judges (ADR-0009, `hooks.clippy-scope`). It runs
389/// in the package root nearest each staged `.rs`, and without `--workspace`
390/// cargo judges that package alone (the default members, at a virtual
391/// root). The whole workspace is judged when a manifest, the lockfile, a
392/// lint config or the toolchain pin is staged — they change how every
393/// package compiles — or when the file set is not the index
394/// (`--all-files`). Lints a change provokes in a DEPENDENT package are
395/// caught by CI's workspace clippy, not here: a cold `--workspace` per
396/// worktree was the longest and most lock-hungry check of a commit.
397pub fn clippy_args(staged: &[String], not_the_index: bool) -> &'static [&'static str] {
398    const PACKAGE: &[&str] = &[
399        "clippy",
400        "--all-targets",
401        "--all-features",
402        "--",
403        "-D",
404        "warnings",
405    ];
406    const WORKSPACE: &[&str] = &[
407        "clippy",
408        "--workspace",
409        "--all-targets",
410        "--all-features",
411        "--",
412        "-D",
413        "warnings",
414    ];
415    let shared = staged
416        .iter()
417        .any(|f| is_rust_path(f) && !f.ends_with(".rs"));
418    if not_the_index || shared {
419        WORKSPACE
420    } else {
421        PACKAGE
422    }
423}
424
425pub fn clippy(settings: &crate::config::Settings, _args: &[std::ffi::OsString]) -> Outcome {
426    // `staged_files` matches by suffix, which would also accept
427    // `vendor/NotCargo.toml`. `is_rust_path` compares the basename, so let it
428    // be the only filter rather than keeping two that disagree.
429    let files: Vec<String> = staged_files(&[])
430        .into_iter()
431        .filter(|f| is_rust_path(f))
432        .collect();
433    if files.is_empty() {
434        return Outcome::Passed;
435    }
436    let root = repo_root();
437    let roots = cargo_roots(&root, files.iter().map(String::as_str));
438    if roots.is_empty() {
439        return Outcome::Passed;
440    }
441    let args = clippy_args(&files, crate::hooks::common::not_the_index());
442    match each_root(
443        settings,
444        &roots,
445        Some("clippy"),
446        args,
447        "Rust staged but clippy is not installed. `rustup component add clippy`.",
448    ) {
449        Err(outcome) => outcome,
450        Ok(true) => {
451            ok(settings, "Clippy passed");
452            Outcome::Passed
453        }
454        Ok(false) => {
455            fail(&format!(
456                "Clippy warnings. Fix them or run {}.",
457                hl("cargo clippy --fix")
458            ));
459            Outcome::Failed
460        }
461    }
462}
463
464/// pre-push. Mirrors `run-tests-js`: the range that is actually being pushed
465/// decides whether the suite runs, so a docs-only push costs nothing.
466///
467/// PER REF, not once for the whole push: `git push origin a b` carries two
468/// tips, and a single worktree checked out to the first one would run the
469/// second ref's tests against the first ref's tree — a real failure in the
470/// untested branch reported as a pass because nothing actually ran against
471/// it. Each ref that touches Rust gets its own worktree and its own verdict.
472pub fn test(
473    settings: &crate::config::Settings,
474    refs: &[crate::pushrefs::PushRef],
475    gate: &str,
476) -> Outcome {
477    // `Unavailable`, never `Passed`, when git will not answer — same argument
478    // and same wording as run-tests-js: a gate must not report green having
479    // asked nothing.
480    let Some(root) = git::stdout(&["rev-parse", "--show-toplevel"]) else {
481        super::common::warn("cargo-test: git would not answer — the gate did NOT run");
482        return Outcome::Unavailable;
483    };
484    let zero = git::stdout(&["hash-object", "--stdin"])
485        .map(|h| "0".repeat(h.len()))
486        .unwrap_or_else(|| "0".repeat(40));
487    let mut ran_any = false;
488    for r in refs {
489        let changed = crate::pushrefs::changed_files_for(r, &zero);
490        let roots = cargo_roots(&root, changed.iter().map(String::as_str));
491        if roots.is_empty() {
492            continue;
493        }
494        // Where THIS ref's suite runs decides what it is answering about.
495        // `_guard` owns the checkout for the length of this ref's run;
496        // dropping it removes the worktree before the next ref's begins.
497        let (where_, _guard) =
498            crate::pushed_tree::where_to_run(settings, &r.local_oid, &root, gate);
499        let roots: Vec<PathBuf> = roots
500            .iter()
501            .map(|rt| {
502                rt.strip_prefix(&root)
503                    .map(|rel| where_.join(rel))
504                    .unwrap_or_else(|_| rt.clone())
505            })
506            .collect();
507        match each_root(
508            settings,
509            &roots,
510            None,
511            &["test", "--workspace", "--all-features"],
512            "Rust changed but cargo is not installed.",
513        ) {
514            Err(outcome) => return outcome,
515            Ok(true) => ran_any = true,
516            Ok(false) => {
517                fail("Rust tests failed. Push aborted.");
518                return Outcome::Failed;
519            }
520        }
521    }
522    if ran_any {
523        ok(settings, "Rust tests passed");
524    }
525    Outcome::Passed
526}
527
528#[cfg(test)]
529mod tests {
530    use super::*;
531
532    #[test]
533    fn recognises_rust_paths() {
534        assert!(is_rust_path("src/main.rs"));
535        assert!(is_rust_path("Cargo.toml"));
536        assert!(is_rust_path("crates/a/Cargo.lock"));
537        assert!(is_rust_path("rustfmt.toml"));
538        assert!(!is_rust_path("README.md"));
539        assert!(!is_rust_path("src/main.rsx"));
540        // A file merely CONTAINING the name is not the manifest.
541        assert!(!is_rust_path("docs/Cargo.toml.md"));
542        assert!(!is_rust_path("vendor/NotCargo.toml"));
543    }
544
545    #[test]
546    fn finds_the_nearest_manifest_not_the_repo_root() {
547        let tmp = std::env::temp_dir().join("amont-cargo-roots");
548        let _ = std::fs::remove_dir_all(&tmp);
549        let nested = tmp.join("services/engine");
550        std::fs::create_dir_all(nested.join("src")).unwrap();
551        std::fs::write(nested.join("Cargo.toml"), "[package]\n").unwrap();
552        let root = tmp.to_string_lossy().into_owned();
553
554        let got = cargo_roots(&root, ["services/engine/src/main.rs"].into_iter());
555        assert_eq!(got, vec![nested.clone()], "should find the nested manifest");
556
557        // A Rust file with no manifest anywhere above it is not a cargo project.
558        std::fs::create_dir_all(tmp.join("scripts")).unwrap();
559        let none = cargo_roots(&root, ["scripts/loose.rs"].into_iter());
560        assert!(none.is_empty(), "no manifest above it: {none:?}");
561        let _ = std::fs::remove_dir_all(&tmp);
562    }
563
564    #[test]
565    fn several_files_in_one_crate_yield_one_root() {
566        let tmp = std::env::temp_dir().join("amont-cargo-dedupe");
567        let _ = std::fs::remove_dir_all(&tmp);
568        std::fs::create_dir_all(tmp.join("src")).unwrap();
569        std::fs::write(tmp.join("Cargo.toml"), "[package]\n").unwrap();
570        let root = tmp.to_string_lossy().into_owned();
571        let got = cargo_roots(&root, ["src/a.rs", "src/b.rs", "Cargo.toml"].into_iter());
572        assert_eq!(got.len(), 1, "one cargo invocation, not three: {got:?}");
573        let _ = std::fs::remove_dir_all(&tmp);
574    }
575
576    #[test]
577    fn non_rust_files_select_nothing() {
578        let got = cargo_roots("/tmp", ["README.md", "a.py"].into_iter());
579        assert!(got.is_empty());
580    }
581
582    #[test]
583    fn reads_the_channel_out_of_the_toml() {
584        let text = "# pinned\n[toolchain]\nchannel = \"1.94.1\" # why\ncomponents = [\"clippy\"]\n";
585        assert_eq!(parse_toolchain_toml(text).as_deref(), Some("1.94.1"));
586        assert_eq!(
587            parse_toolchain_toml("[toolchain]\nchannel = 'stable'\n").as_deref(),
588            Some("stable")
589        );
590        assert_eq!(parse_toolchain_toml("[toolchain]\ncomponents = []\n"), None);
591        assert_eq!(parse_toolchain_toml("# channel = \"1.0\"\n"), None);
592    }
593
594    #[test]
595    fn only_a_version_is_held_against_cargo() {
596        assert_eq!(version_pin("1.94.1"), Some("1.94.1"));
597        assert_eq!(version_pin("1.94"), Some("1.94"));
598        assert_eq!(version_pin("stable"), None);
599        assert_eq!(version_pin("nightly-2026-01-01"), None);
600        assert_eq!(version_pin("1"), None);
601        assert!(version_matches("1.94.1", "1.94.1"));
602        assert!(version_matches("1.94", "1.94.1"));
603        assert!(!version_matches("1.94.1", "1.98.0"));
604        assert!(!version_matches("1.9", "1.94.1"));
605    }
606
607    #[test]
608    fn the_nearest_pin_above_the_manifest_wins() {
609        let tmp = std::env::temp_dir().join("amont-toolchain-pin");
610        let _ = std::fs::remove_dir_all(&tmp);
611        let nested = tmp.join("services/engine");
612        std::fs::create_dir_all(&nested).unwrap();
613        std::fs::write(tmp.join("rust-toolchain"), "1.85.0\n").unwrap();
614        let (file, pin) = pinned_toolchain(&nested).unwrap();
615        assert_eq!((file, pin.as_str()), (tmp.join("rust-toolchain"), "1.85.0"));
616        std::fs::write(
617            nested.join("rust-toolchain.toml"),
618            "[toolchain]\nchannel = \"1.94.1\"\n",
619        )
620        .unwrap();
621        let (file, pin) = pinned_toolchain(&nested).unwrap();
622        assert_eq!(
623            (file, pin.as_str()),
624            (nested.join("rust-toolchain.toml"), "1.94.1")
625        );
626        let _ = std::fs::remove_dir_all(&tmp);
627    }
628    /// Source alone: the package, no `--workspace`. A manifest, lockfile,
629    /// lint config or pin staged, or a file set that is not the index:
630    /// the whole workspace.
631    #[test]
632    fn clippy_judges_the_package_unless_something_shared_is_staged() {
633        use super::clippy_args;
634        let s = |v: &[&str]| v.iter().map(|x| x.to_string()).collect::<Vec<_>>();
635        let pkg = clippy_args(&s(&["crates/a/src/lib.rs", "README.md"]), false);
636        assert!(!pkg.contains(&"--workspace"), "{pkg:?}");
637        assert_eq!(pkg.first(), Some(&"clippy"));
638        for shared in [
639            "Cargo.lock",
640            "crates/a/Cargo.toml",
641            "clippy.toml",
642            "rust-toolchain.toml",
643        ] {
644            let ws = clippy_args(&s(&["crates/a/src/lib.rs", shared]), false);
645            assert!(ws.contains(&"--workspace"), "{shared}: {ws:?}");
646        }
647        assert!(clippy_args(&s(&["crates/a/src/lib.rs"]), true).contains(&"--workspace"));
648    }
649}