1use 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
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 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
302fn 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
322fn 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
342fn 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
389fn 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 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 if fixing_enabled(settings)
447 && run_in_roots(settings, &roots, Path::new(&root), &argv, &["fmt", "--all"])
448 {
449 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 Restaged::Nothing => {}
471 }
472 }
473
474 fail(&format!("Unformatted Rust. Run {}.", hl("cargo fmt --all")));
475 Outcome::Failed
476}
477
478pub 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 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
555pub fn test(
564 settings: &crate::config::Settings,
565 refs: &[crate::pushrefs::PushRef],
566 gate: &str,
567) -> Outcome {
568 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 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 #[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 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 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 #[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}