1use 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
26pub const RUST_PATHS: &[&str] = &[
34 ".rs",
35 "Cargo.toml",
36 "Cargo.lock",
37 "rustfmt.toml",
38 "clippy.toml",
39 "rust-toolchain.toml",
41 "rust-toolchain",
42];
43
44pub 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
59fn 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
91fn 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
117fn 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
142fn 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
159fn 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
171fn 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
188fn 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
196fn 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
223fn 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 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
290fn 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
308fn 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 if run_in_roots(settings, &roots, &argv, &["fmt", "--all", "--", "--check"]) {
348 ok(settings, "Rust formatting is clean");
349 return Outcome::Passed;
350 }
351
352 if fixing_enabled(settings) && run_in_roots(settings, &roots, &argv, &["fmt", "--all"]) {
359 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 Restaged::Nothing => {}
381 }
382 }
383
384 fail(&format!("Unformatted Rust. Run {}.", hl("cargo fmt --all")));
385 Outcome::Failed
386}
387
388pub 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 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
464pub fn test(
473 settings: &crate::config::Settings,
474 refs: &[crate::pushrefs::PushRef],
475 gate: &str,
476) -> Outcome {
477 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 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 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 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 #[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}