amont_runtime/hooks/common.rs
1//! Shared plumbing for the linter-orchestration hooks.
2//!
3//! Nine of them do the same four things: collect staged files of some kind,
4//! bail out if there are none, resolve a tool, run it. In shell that was ~65
5//! lines apiece, mostly duplicated; here it is a handful of helpers and each
6//! hook keeps only what is actually specific to it.
7
8use crate::git;
9use crate::ui::{error_sign, valid_sign, warning_sign};
10use std::path::Path;
11use std::process::{Command, Stdio};
12use std::sync::OnceLock;
13
14/// Staged files, deletions excluded, whose name ends with one of `exts`.
15/// The file set every check asks about, when it is not the staged one.
16///
17/// Set at most once, before any check runs, by `amont run --all-files`. A
18/// process-level override rather than a parameter because a check's signature
19/// is `(&[OsString])` — it never sees a `Ctx` — and threading a file set
20/// through twenty of them to serve one mode would be a worse trade than a
21/// value that is written once and read many times.
22///
23/// Same shape as `PushRefs`: read once, lent to every check that asks.
24static OVERRIDE: OnceLock<Vec<String>> = OnceLock::new();
25
26/// Set once the file set stops being the index.
27///
28/// `restage`'s own doc says what makes re-staging safe: the pre-commit stage
29/// holds the unstaged changes aside, so the tree contains the staged content
30/// and nothing else, and anything a formatter touched is by definition part of
31/// this commit. `amont run --all-files` replaces the file set with every
32/// tracked path — which is that precondition being FALSE.
33///
34/// With `amont.fix true`, every fixer's `restage(&files)` would then `git
35/// add` everything in the working tree that differs from the index, turning a
36/// read-only "does my tree pass" query into `git add .`. That is the hazard §2
37/// of docs/index-fidelity-and-run-modes.md names.
38///
39/// The gate hangs off the OVERRIDE rather than off a flag threaded through
40/// twenty check signatures, because the override IS the fact that matters. It
41/// therefore covers built-ins and `manifest::External::run` (which consults
42/// `fixing_enabled` in two places) in one change, and a future check cannot
43/// forget it.
44static NOT_THE_INDEX: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
45
46/// Make every subsequent `staged_files` answer from `files` instead of the
47/// index. Only the first call counts.
48pub fn override_file_set(files: Vec<String>) {
49 // Set unconditionally, even if a set already won the `OnceLock`: the
50 // statement "the file set is not the index" is true from the first call
51 // onwards regardless of which one supplied the paths.
52 NOT_THE_INDEX.store(true, std::sync::atomic::Ordering::SeqCst);
53 let _ = OVERRIDE.set(files);
54}
55
56/// Whether the file set every check sees is something other than the index.
57pub fn not_the_index() -> bool {
58 NOT_THE_INDEX.load(std::sync::atomic::Ordering::SeqCst)
59}
60
61/// An empty `exts` returns them all.
62///
63/// The UNFILTERED list is read from git ONCE per process and lent to every
64/// caller — the per-stage snapshot. Eleven of the pre-commit checks ask this
65/// question, concurrently, and each used to pay its own `git diff` spawn for
66/// an answer that cannot change while the stage runs: the index-fidelity
67/// hold pins the tree, and a fixer's `restage()` re-adds only paths already
68/// on this list. `PushRefs` ("read once and lent") and `Overrides` ("ONE
69/// subprocess for the whole stage") are the same pattern; this was the last
70/// hot question still answered per asker.
71pub fn staged_files(exts: &[&str]) -> Vec<String> {
72 if let Some(all) = OVERRIDE.get() {
73 return all
74 .iter()
75 .filter(|f| exts.is_empty() || exts.iter().any(|e| f.ends_with(e)))
76 .cloned()
77 .collect();
78 }
79 static INDEX: OnceLock<Vec<String>> = OnceLock::new();
80 INDEX
81 .get_or_init(|| {
82 match git::stdout_paths(&["diff", "--diff-filter=d", "--cached", "--name-only"]) {
83 Some(files) => files,
84 // The third member of a bug family (`repo_hooks`, the push
85 // gates): git FAILING is not git answering "empty", and a
86 // stage that judges an empty set on a git failure reports
87 // clean having verified nothing. Say so — once, this cache
88 // being the once — and still fail open: pre-commit's job is
89 // never to block a commit over its own plumbing.
90 None => {
91 warn(
92 "git would not list the staged files — the checks are judging \
93 an EMPTY set, not a verified one",
94 );
95 Vec::new()
96 }
97 }
98 })
99 .iter()
100 .filter(|f| exts.is_empty() || exts.iter().any(|e| f.ends_with(e)))
101 .cloned()
102 .collect()
103}
104
105/// Repo root, or "." when git cannot say.
106///
107/// **For CHECK BODIES ONLY.** The fallback is safe there and nowhere else: git
108/// invokes a hook with the working tree as the current directory, so a check
109/// that reaches this line is already standing in the repository, and "." is the
110/// right answer rather than a guess.
111///
112/// Anything a user types — `amont agents-md`, `install`, `trust`, `restore`
113/// — can be typed from any directory on the machine, and there the fallback is
114/// not a fallback but a wrong answer that reads as a right one. Use
115/// [`repo_root_checked`] at every command entry point.
116pub fn repo_root() -> String {
117 // Cached: the answer is a property of the process's repository, and
118 // every check asked it through its own subprocess.
119 static ROOT: OnceLock<String> = OnceLock::new();
120 ROOT.get_or_init(|| {
121 git::stdout(&["rev-parse", "--show-toplevel"]).unwrap_or_else(|| ".".into())
122 })
123 .clone()
124}
125
126/// Repo root, or an error naming the problem.
127///
128/// The same question as [`repo_root`] without the "." — because "." is a
129/// PLAUSIBLE root, and that is what made it dangerous. `amont agents-md`
130/// run outside a repository did not fail; it resolved the root to the current
131/// directory and wrote `./AGENTS.md` into whatever directory the user happened
132/// to be standing in, then printed `wrote ./AGENTS.md` as if that were the
133/// answer. Same shape in `install`'s two prompts, in `trust` (which then
134/// looked for a manifest, and would have recorded trust, under `.`) and in
135/// `restore`.
136///
137/// Every one of those is a command somebody types, and a command somebody
138/// types is a command they can type from `~`. There is no correct behaviour
139/// available to this function when git cannot answer, so it does not invent
140/// one.
141pub fn repo_root_checked() -> Result<String, String> {
142 git::stdout(&["rev-parse", "--show-toplevel"])
143 .filter(|s| !s.is_empty())
144 .ok_or_else(|| "not inside a git repository".to_string())
145}
146
147/// Resolve a tool, preferring the repo's PINNED copy so the hook matches CI.
148///
149///
150/// Order: `<root>/node_modules/.bin/<tool>`, then the MAIN worktree's (a linked
151/// worktree has no node_modules of its own — this is why the shell version
152/// consulted the git common dir), then PATH.
153pub fn resolve_tool(root: &str, tool: &str) -> Option<Vec<String>> {
154 // Same extension problem as `which`: an npm-installed binary is `eslint.cmd`
155 // on Windows, so the bare name misses the repo's PINNED copy and the hook
156 // silently falls through to an ambient one.
157 if let Some(p) = in_bin_dir(&format!("{root}/node_modules/.bin"), tool) {
158 return Some(vec![p]);
159 }
160 if let Some(common) = git::stdout(&["rev-parse", "--path-format=absolute", "--git-common-dir"])
161 {
162 if let Some(main) = Path::new(&common).parent() {
163 if let Some(p) = in_bin_dir(&main.join("node_modules/.bin").to_string_lossy(), tool) {
164 return Some(vec![p]);
165 }
166 }
167 }
168 if let Some(full) = which(tool) {
169 return Some(vec![full]);
170 }
171 // `npx --no-install`: never silently download a random latest version — a
172 // hook that quietly pulls a different linter than CI uses is worse than one
173 // that skips.
174 if which("npx").is_some()
175 && Command::new(program("npx"))
176 .args(["--no-install", tool, "--version"])
177 .current_dir(root)
178 .stdin(Stdio::null())
179 .stdout(Stdio::null())
180 .stderr(Stdio::null())
181 .status()
182 .map(|s| s.success())
183 .unwrap_or(false)
184 {
185 return Some(vec![
186 program("npx"),
187 "--no-install".to_string(),
188 tool.to_string(),
189 ]);
190 }
191 None
192}
193
194/// First match for `tool` on PATH.
195///
196/// Windows executables carry an extension — `git` is `git.exe`, an npm-installed
197/// `eslint` is `eslint.cmd` — so the bare name finds nothing there. PATHEXT is
198/// the OS's own list of what counts as executable; fall back to the usual set
199/// when it is unset. Found by the Windows CI job on its first run, where
200/// `which("git")` returned None on a machine that plainly has git.
201pub fn which(tool: &str) -> Option<String> {
202 which_on(&std::env::var_os("PATH")?, tool)
203}
204
205/// [`which`] against an EXPLICIT path list — the seam its own test needs.
206///
207/// The test that pins the Windows extension order used to `set_var("PATH")`
208/// around the call, which is process-global: for the length of that call
209/// every OTHER test in the binary — 340 of them, running in parallel, many
210/// spawning git — had a PATH containing one fake tool and nothing else. A
211/// git spawned in that window fails with "not found", which is not a
212/// transient `git::retrying` may retry (correctly: it is a hard error), so
213/// the caller reads it as git's ANSWER. In `gate_stamp` that answer is
214/// "nothing is stamped". Passing the path in deletes the shared state
215/// rather than guarding it — a lock only protects the callers who remember
216/// to take it, and every future test here would have to remember.
217pub fn which_on(path: &std::ffi::OsStr, tool: &str) -> Option<String> {
218 let exts: Vec<String> = if cfg!(windows) {
219 std::env::var("PATHEXT")
220 .unwrap_or_else(|_| ".COM;.EXE;.BAT;.CMD".into())
221 .split(';')
222 .filter(|e| !e.is_empty())
223 .map(|e| e.to_lowercase())
224 .collect()
225 } else {
226 Vec::new()
227 };
228 for dir in std::env::split_paths(path) {
229 // On Windows the EXTENSION forms come first. A node install ships both
230 // `npm` (an extensionless shell script, for MSYS) and `npm.cmd` in the
231 // same directory; preferring the bare name hands CreateProcess a shell
232 // script it cannot execute — "%1 is not a valid Win32 application" —
233 // and the hook reports an installed tool as broken.
234 for e in &exts {
235 let c = dir.join(format!("{tool}{e}"));
236 if c.is_file() {
237 return Some(c.to_string_lossy().into_owned());
238 }
239 }
240 let bare = dir.join(tool);
241 if bare.is_file() {
242 return Some(bare.to_string_lossy().into_owned());
243 }
244 }
245 None
246}
247
248/// `<dir>/<tool>`, trying the Windows executable extensions too.
249fn in_bin_dir(dir: &str, tool: &str) -> Option<String> {
250 let bare = Path::new(dir).join(tool);
251 if bare.is_file() {
252 return Some(bare.to_string_lossy().into_owned());
253 }
254 if cfg!(windows) {
255 for e in [".cmd", ".exe", ".bat", ".ps1"] {
256 let c = Path::new(dir).join(format!("{tool}{e}"));
257 if c.is_file() {
258 return Some(c.to_string_lossy().into_owned());
259 }
260 }
261 }
262 None
263}
264
265/// Resolve a tool name to a full path for spawning.
266///
267/// `Command::new("npm")` cannot execute `npm.cmd`: Rust does no PATHEXT
268/// resolution, so on Windows every bare-name spawn fails with "program not
269/// found" and the hook reports the tool as broken rather than absent. Found by
270/// the Windows job on its first FULL-suite run — the smoke never spawned a
271/// tool, so it could not have surfaced this.
272///
273/// Falls back to the name unchanged, so a caller still gets a sensible error.
274pub fn program(name: &str) -> String {
275 which(name).unwrap_or_else(|| name.to_string())
276}
277
278/// The first of `names` that exists at the repo root — how these hooks decide
279/// a repo has opted into a tool.
280pub fn first_existing(root: &str, names: &[&str]) -> Option<String> {
281 names
282 .iter()
283 .find(|n| Path::new(root).join(n).exists())
284 .map(|n| (*n).to_string())
285}
286
287/// Strip git's own environment before handing a Command to another tool.
288///
289/// git exports GIT_DIR, GIT_INDEX_FILE, GIT_WORK_TREE and friends to every
290/// hook. Those OVERRIDE the working directory, so any tool that shells out to
291/// git operates on the hook's repository no matter where it was launched.
292///
293/// That is not hypothetical: `pre-push-cargo-test` runs a project's test suite,
294/// and this repo's own suite creates throwaway repos and commits to them. With
295/// GIT_DIR inherited, `git commit` in a test wrote into the REAL repository —
296/// an actual stray commit, authored by the test fixture, pushed to a branch.
297///
298/// A test suite should behave exactly as it does when run by hand, which means
299/// seeing no git environment at all.
300pub fn strip_git_env(cmd: &mut Command) {
301 for (k, _) in std::env::vars_os() {
302 let key = k.to_string_lossy();
303 if key.starts_with("GIT_") {
304 cmd.env_remove(&k);
305 }
306 }
307}
308
309/// The wall-clock budget for one check's spawned command, in seconds.
310///
311/// `amont.timeout`, default 600 — ten minutes, the figure the generated
312/// agent guidance already tells tooling to allow a whole commit or push; a
313/// single check that outlives it is not slow, it is stuck. `0` disables.
314/// Read once per process: twenty concurrent checks must not each spawn a
315/// `git config` to learn the same number.
316pub fn check_timeout() -> u64 {
317 static TIMEOUT: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
318 *TIMEOUT.get_or_init(|| crate::config::integer_or("amont.timeout", 600, 0..=86_400) as u64)
319}
320
321/// The deadline for a network PROBE — an `ls-remote` asked before the real
322/// work, not the work itself. Capped at 30s below [`check_timeout`]: a
323/// probe answers in a second or two when the network is there at all, and
324/// a healthy `amont.timeout` of ten minutes is sized for a test suite, not
325/// for deciding whether the remote is reachable. Shrinking `amont.timeout`
326/// below the cap shrinks this too, and `0` keeps meaning no deadline —
327/// somebody who disabled the clock disabled all of it.
328pub fn network_probe_budget() -> u64 {
329 match check_timeout() {
330 0 => 0,
331 t => t.min(30),
332 }
333}
334
335/// What became of a command run under the deadline.
336pub enum Ran {
337 Status(std::process::ExitStatus),
338 /// Killed at the deadline; carries the budget it exceeded, in seconds.
339 TimedOut(u64),
340}
341
342/// `cmd.status()`, bounded by [`check_timeout`].
343///
344/// Without a bound, one hung tool — a linter deadlocked on a lock file, a
345/// plugin doing network I/O — blocked the commit FOREVER, and it hung inside
346/// the index-fidelity hold: the user's unstaged changes parked in `$GIT_DIR`,
347/// their tree showing staged content only, for as long as they were willing
348/// to wait. The learned response to that is `--no-verify`, permanently —
349/// which disarms every check to escape one.
350///
351/// The kill reaches the direct child only. A grandchild that detached
352/// survives, orphaned — but the COMMIT is no longer hostage to it, which is
353/// the property that matters.
354pub fn status_within(cmd: &mut Command) -> std::io::Result<Ran> {
355 status_within_secs(cmd, check_timeout())
356}
357
358/// [`status_within`] with an explicit budget — the testable seam.
359pub fn status_within_secs(cmd: &mut Command, budget_secs: u64) -> std::io::Result<Ran> {
360 if budget_secs == 0 {
361 return cmd.status().map(Ran::Status);
362 }
363 let mut child = cmd.spawn()?;
364 wait_within(&mut child, budget_secs)
365}
366
367/// [`status_within`], with the child's stdout and stderr CAPTURED into the
368/// calling check's slot instead of inherited — the other half of one-check-
369/// one-block: a linter's twelve lines used to land on the shared terminal
370/// between two other checks' lines. Falls back to plain [`status_within`]
371/// when no slot is installed on this thread (`amont.progress false`, or a
372/// spawn outside a stage), which is byte-for-byte the old behaviour.
373///
374/// stdout and stderr merge in ARRIVAL order inside the block, which is what
375/// the terminal showed before. The readers are threads, not processes, and
376/// they are joined before the status is returned so a block can never grow
377/// after its check finished.
378pub fn status_streamed(cmd: &mut Command) -> std::io::Result<Ran> {
379 let Some((stage, idx)) = crate::live::current_sink() else {
380 return status_within(cmd);
381 };
382 cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
383 if crate::live::watching() {
384 // The block lands on a real terminal but the tool sees a pipe and
385 // would strip its colors; the big three opt-in knobs put them back.
386 cmd.env("FORCE_COLOR", "1")
387 .env("CLICOLOR_FORCE", "1")
388 .env("CARGO_TERM_COLOR", "always");
389 }
390 let budget = check_timeout();
391 let mut child = cmd.spawn()?;
392 let mut readers = Vec::new();
393 for pipe in [
394 child
395 .stdout
396 .take()
397 .map(|p| Box::new(p) as Box<dyn std::io::Read + Send>),
398 child
399 .stderr
400 .take()
401 .map(|p| Box::new(p) as Box<dyn std::io::Read + Send>),
402 ]
403 .into_iter()
404 .flatten()
405 {
406 let stage = std::sync::Arc::clone(&stage);
407 readers.push(std::thread::spawn(move || {
408 let mut pipe = pipe;
409 let mut chunk = [0u8; 4096];
410 loop {
411 match std::io::Read::read(&mut pipe, &mut chunk) {
412 Ok(0) | Err(_) => break,
413 Ok(n) => stage.append_raw(idx, &chunk[..n]),
414 }
415 }
416 }));
417 }
418 let ran = wait_within(&mut child, budget)?;
419 for r in readers {
420 let _ = r.join();
421 }
422 Ok(ran)
423}
424
425/// Run to completion under the `amont.timeout` deadline with stdout and
426/// stderr CAPTURED into a string the caller can parse — what the audit
427/// checks need: their verdict lives in the tool's output, not its exit
428/// code alone. Arrival-ordered merge of both streams, like
429/// [`status_streamed`]'s blocks. `None` when the child cannot be spawned.
430pub fn capture_within(cmd: &mut Command) -> Option<(Ran, String)> {
431 cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
432 let budget = check_timeout();
433 let mut child = cmd.spawn().ok()?;
434 let text = std::sync::Arc::new(std::sync::Mutex::new(String::new()));
435 let mut readers = Vec::new();
436 for pipe in [
437 child
438 .stdout
439 .take()
440 .map(|p| Box::new(p) as Box<dyn std::io::Read + Send>),
441 child
442 .stderr
443 .take()
444 .map(|p| Box::new(p) as Box<dyn std::io::Read + Send>),
445 ]
446 .into_iter()
447 .flatten()
448 {
449 let text = std::sync::Arc::clone(&text);
450 readers.push(std::thread::spawn(move || {
451 let mut pipe = pipe;
452 let mut chunk = [0u8; 4096];
453 loop {
454 match std::io::Read::read(&mut pipe, &mut chunk) {
455 Ok(0) | Err(_) => break,
456 Ok(n) => {
457 let piece = String::from_utf8_lossy(&chunk[..n]).into_owned();
458 text.lock()
459 .unwrap_or_else(|p| p.into_inner())
460 .push_str(&piece);
461 }
462 }
463 }
464 }));
465 }
466 let ran = wait_within(&mut child, budget).ok()?;
467 for r in readers {
468 let _ = r.join();
469 }
470 let text = std::sync::Arc::try_unwrap(text)
471 .map(|m| m.into_inner().unwrap_or_else(|p| p.into_inner()))
472 .unwrap_or_default();
473 Some((ran, text))
474}
475
476/// The deadline loop over an already-spawned child — shared by the
477/// inherited and captured runners.
478pub(crate) fn wait_within(
479 child: &mut std::process::Child,
480 budget_secs: u64,
481) -> std::io::Result<Ran> {
482 if budget_secs == 0 {
483 return child.wait().map(Ran::Status);
484 }
485 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(budget_secs);
486 loop {
487 if let Some(status) = child.try_wait()? {
488 return Ok(Ran::Status(status));
489 }
490 if std::time::Instant::now() >= deadline {
491 let _ = child.kill();
492 let _ = child.wait();
493 return Ok(Ran::TimedOut(budget_secs));
494 }
495 std::thread::sleep(std::time::Duration::from_millis(25));
496 }
497}
498
499/// Say a command was killed at the deadline, and how to change the deadline.
500pub fn say_timed_out(what: &str, budget_secs: u64) {
501 fail(&format!(
502 "{} timed out after {budget_secs}s — killed. {} raises the budget",
503 hl(what),
504 hl("git config amont.timeout <secs>")
505 ));
506}
507
508/// [`status_within`], collapsed to "did it exit 0" — the shape the one-shot
509/// tool spawns want. A timeout says so, names `what`, and reads as failure.
510pub fn bounded_success(cmd: &mut Command, what: &str) -> bool {
511 match status_streamed(cmd) {
512 Ok(Ran::Status(s)) => s.success(),
513 Ok(Ran::TimedOut(b)) => {
514 say_timed_out(what, b);
515 false
516 }
517 Err(_) => false,
518 }
519}
520
521/// Run `argv` from `root`, inheriting stdio. True when it exits 0.
522pub fn run(root: &str, argv: &[String], extra: &[String]) -> bool {
523 let Some((program, rest)) = argv.split_first() else {
524 return true;
525 };
526 let mut cmd = Command::new(program);
527 cmd.args(rest)
528 .args(extra)
529 .current_dir(root)
530 .stdin(Stdio::null());
531 strip_git_env(&mut cmd);
532 bounded_success(&mut cmd, program)
533}
534
535/// As [`run`], but with the tool's own output discarded.
536///
537/// For a pass whose only job is to decide something — prettier's `--check`,
538/// ruff's `--fix` sweep — where the offenders are printed once, by the pass
539/// that reports them, rather than twice.
540pub fn run_quiet(root: &str, argv: &[String], extra: &[String]) -> bool {
541 let Some((program, rest)) = argv.split_first() else {
542 return true;
543 };
544 let mut cmd = Command::new(program);
545 cmd.args(rest)
546 .args(extra)
547 .current_dir(root)
548 .stdin(Stdio::null())
549 .stdout(Stdio::null())
550 .stderr(Stdio::null());
551 strip_git_env(&mut cmd);
552 // Deliberately NOT the streamed runner: this helper's contract is that
553 // the output is discarded, and capture would resurrect it into the block.
554 match status_within(&mut cmd) {
555 Ok(Ran::Status(s)) => s.success(),
556 Ok(Ran::TimedOut(b)) => {
557 say_timed_out(program, b);
558 false
559 }
560 Err(_) => false,
561 }
562}
563
564/// Whether the user asked for checks to repair what they find.
565///
566/// OFF by default. `git config amont.fix true` turns it on, per repository,
567/// because a hook that edits your files without being asked is a larger
568/// surprise than one that complains — and because with index fidelity in place
569/// the repair lands in the commit you are making, which is a bigger claim to
570/// make on somebody's behalf than printing an error.
571pub fn fixing_enabled() -> bool {
572 // Never while the file set is not the index — see `NOT_THE_INDEX`.
573 !not_the_index() && fixing_requested()
574}
575
576/// What the CONFIG says, ignoring whether the current run may act on it.
577///
578/// Split out so `run_all` can tell the difference between "fixing is off" and
579/// "you asked for fixing and this mode will not do it", and say the second out
580/// loud instead of silently ignoring the key.
581pub fn fixing_requested() -> bool {
582 crate::config::boolean_or("amont.fix", false)
583}
584
585/// What a re-stage actually did. THREE answers, because the old `bool`
586/// conflated two of them and the conflation shipped unformatted code.
587///
588/// `prettier.rs` read `if run_quiet(write) && restage(&files) { … Fixed }`. When
589/// `git add` FAILED, `restage` returned `false` — indistinguishable from
590/// "nothing needed staging" — so control fell through to a second `--check`
591/// pass, which inspected the NOW-FORMATTED WORKING TREE, passed, printed
592/// "Prettier passed" and returned `Outcome::Passed`. The index still held the
593/// unformatted content, so the commit contained unformatted code and the hook
594/// said it had passed. `manifest.rs` had the same shape.
595#[derive(Debug, Clone, PartialEq, Eq)]
596pub enum Restaged {
597 /// No path differed from the index — nothing to do, and nothing wrong.
598 Nothing,
599 /// `git add` succeeded; the index now holds the repair.
600 Staged,
601 /// `git add` failed, carrying the paths it could not stage. The index
602 /// holds content the fixer has already replaced on disk, so this MUST be
603 /// loud at every call site — and naming the files is the difference
604 /// between a message somebody can act on and one they cannot.
605 Failed(Vec<String>),
606}
607
608/// Serialises this process's own `git add` calls.
609///
610/// pre-commit runs its checks concurrently (`dispatch.rs`), and up to three of
611/// them can re-stage. git takes `$GIT_DIR/index.lock` exclusively, so two
612/// concurrent `git add`s in the same repository make one of them fail — which,
613/// before `Restaged`, was silently read as "nothing moved". Holding this across
614/// the `git add` removes self-contention entirely; the retry below is only for
615/// OTHER processes.
616static INDEX_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
617
618/// Re-stage exactly the paths a fixer rewrote, and say what happened.
619///
620/// Safe ONLY because the pre-commit stage holds unstaged changes aside: the
621/// tree contains the staged content and nothing else, so anything a formatter
622/// touched is by definition part of this commit. Without that, re-staging would
623/// sweep in work the author deliberately kept back.
624pub fn restage(paths: &[String]) -> Restaged {
625 // Belt and braces alongside `fixing_enabled`: a future fixer that forgets
626 // the gate still cannot turn `amont run --all-files` into `git add .`.
627 if not_the_index() {
628 return Restaged::Nothing;
629 }
630 let changed: Vec<String> = paths
631 .iter()
632 .filter(|p| !git::succeeds(&["diff", "--quiet", "--", p]))
633 .cloned()
634 .collect();
635 if changed.is_empty() {
636 return Restaged::Nothing;
637 }
638 let mut args = vec!["add", "--"];
639 args.extend(changed.iter().map(String::as_str));
640
641 let _serialised = INDEX_LOCK.lock().unwrap_or_else(|e| e.into_inner());
642 // Another PROCESS can hold `index.lock` — a `git status` from an editor, a
643 // second hook in a linked worktree. Back off and retry rather than
644 // reporting a transient collision as a failed repair. `git add` of the same
645 // paths is idempotent: it records the paths' current worktree content, so
646 // running it twice records the same thing twice and cannot double-stage.
647 const BACKOFF_MS: [u64; 3] = [50, 150, 400];
648 if git::succeeds(&args) {
649 return Restaged::Staged;
650 }
651 for wait in BACKOFF_MS {
652 std::thread::sleep(std::time::Duration::from_millis(wait));
653 if git::succeeds(&args) {
654 return Restaged::Staged;
655 }
656 }
657 Restaged::Failed(changed)
658}
659
660pub fn ok(msg: &str) {
661 crate::live::say(&format!("{} {msg}", valid_sign()));
662}
663pub fn fail(msg: &str) {
664 crate::live::say(&format!("{} {msg}", error_sign()));
665}
666pub fn warn(msg: &str) {
667 crate::live::say(&format!("{} {msg}", warning_sign()));
668}
669/// A line with no sign of its own — what a check's direct `println!` becomes,
670/// so it lands in the check's block instead of interleaving. See `live::say`.
671pub fn say(msg: &str) {
672 crate::live::say(msg);
673}
674
675/// Orange, for the fragments these hooks highlight.
676pub fn hl(s: &str) -> String {
677 crate::ui::highlight(s)
678}
679
680#[cfg(test)]
681mod tests {
682
683 /// The deadline kills what outlives it and reports what finished.
684 #[cfg(unix)]
685 #[test]
686 fn the_deadline_kills_a_sleeper_and_spares_a_finisher() {
687 let started = std::time::Instant::now();
688 let mut slow = Command::new(program("sleep"));
689 slow.arg("300").stdin(Stdio::null());
690 match status_within_secs(&mut slow, 1) {
691 Ok(Ran::TimedOut(1)) => {}
692 other => panic!("expected TimedOut(1), got {:?}", other.map(|_| "ran")),
693 }
694 assert!(
695 started.elapsed() < std::time::Duration::from_secs(60),
696 "the kill did not happen at the deadline"
697 );
698
699 let mut quick = Command::new(program("true"));
700 quick.stdin(Stdio::null());
701 match status_within_secs(&mut quick, 60) {
702 Ok(Ran::Status(s)) => assert!(s.success()),
703 other => panic!("expected a clean exit, got {:?}", other.map(|_| "?")),
704 }
705 }
706
707 use super::*;
708
709 #[test]
710 fn which_finds_a_real_binary_and_not_a_fake_one() {
711 assert!(which("git").is_some());
712 assert!(which("definitely-not-a-real-binary-xyz").is_none());
713 }
714
715 /// On Windows a tool can exist BOTH as an extensionless shell script and as
716 /// a .cmd/.exe in the same directory; only the latter is executable by
717 /// CreateProcess, so the extension forms must win.
718 #[test]
719 #[cfg(windows)]
720 fn windows_prefers_an_executable_extension_over_a_bare_file() {
721 let dir = std::env::temp_dir().join("amont-which-order");
722 let _ = std::fs::create_dir_all(&dir);
723 std::fs::write(dir.join("faketool"), "#!/bin/sh\n").unwrap();
724 std::fs::write(dir.join("faketool.cmd"), "@echo off\n").unwrap();
725 // The path is PASSED, never installed into this process: see
726 // `which_on`. The old spelling swapped the real PATH out from under
727 // every other test in this binary for the length of the call.
728 let found = which_on(dir.as_os_str(), "faketool").unwrap();
729 assert!(found.ends_with(".cmd"), "got {found}");
730 let _ = std::fs::remove_dir_all(&dir);
731 }
732
733 /// "Nothing moved" and "`git add` FAILED" are different answers, and the
734 /// old `bool` gave the same one for both.
735 ///
736 /// That conflation is what shipped unformatted code: `prettier.rs` read
737 /// `if wrote && restage(&files)`, so a failed `git add` fell through to a
738 /// second `--check` against the now-formatted WORKING TREE, which passed —
739 /// while the INDEX still held the unformatted content the commit would
740 /// carry.
741 ///
742 /// An absolute path outside any repository is a `git add` git will always
743 /// refuse, which is the only way to reach the failing branch without
744 /// sabotaging a real index.
745 #[test]
746 fn restage_distinguishes_nothing_from_failure() {
747 // `restage` runs `git add` in the PROCESS cwd, so this test depends
748 // on that cwd as surely as one that moves it — see `crate::TEST_CWD`.
749 // Without the lock it ran inside whatever fixture `gate_stamp` had
750 // moved into, and took that repository's index.lock out from under
751 // its own commit.
752 let _cwd = crate::TEST_CWD.lock().unwrap_or_else(|p| p.into_inner());
753 let outside = std::env::temp_dir()
754 .join("amont-restage-outside-any-repo")
755 .to_string_lossy()
756 .into_owned();
757 assert_eq!(
758 restage(std::slice::from_ref(&outside)),
759 Restaged::Failed(vec![outside]),
760 "a `git add` git refuses must report Failed, never Nothing"
761 );
762 assert_eq!(
763 restage(&[]),
764 Restaged::Nothing,
765 "no paths is nothing to do, and nothing wrong"
766 );
767 }
768
769 /// No check may hand `Command` a bare program name.
770 ///
771 /// `Command::new` does NO PATHEXT resolution, so `Command::new("npm")`
772 /// cannot execute `npm.cmd` and `Command::new("uvx")` cannot execute
773 /// `uvx.exe`: the spawn fails with "program not found" and a
774 /// `Severity::Block` check reports an installed tool as broken. That is the
775 /// incident `program()` exists for, and it kept recurring — `yamllint` and
776 /// three sites in `python_tools` were still doing it, THREE OF THEM after
777 /// `which()` had already succeeded and discarded the answer.
778 ///
779 /// A source scan rather than a runtime assertion because the failure only
780 /// reproduces on Windows, and the whole point is to catch the next one on
781 /// every platform. Comment lines are skipped: `program()`'s own doc quotes
782 /// the offending call. The needle is assembled from two pieces so this
783 /// module — which the scan also reads — does not match itself.
784 #[test]
785 fn no_hook_spawns_a_bare_program_name() {
786 let needle = concat!("Command", "::new(");
787 let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/src/hooks");
788 let mut scanned = 0usize;
789 for entry in std::fs::read_dir(dir).expect("hooks dir").flatten() {
790 let path = entry.path();
791 if path.extension().and_then(|e| e.to_str()) != Some("rs") {
792 continue;
793 }
794 scanned += 1;
795 let src = std::fs::read_to_string(&path).expect("read a hook module");
796 for (n, line) in src.lines().enumerate() {
797 if line.trim_start().starts_with("//") {
798 continue;
799 }
800 let Some(after) = line.split_once(needle) else {
801 continue;
802 };
803 assert!(
804 !after.1.starts_with('"'),
805 "{}:{} spawns a bare name — route it through `program()` or \
806 the path `which()` already resolved: {}",
807 path.display(),
808 n + 1,
809 line.trim()
810 );
811 }
812 }
813 assert!(
814 scanned > 10,
815 "the scan found almost nothing: {scanned} files"
816 );
817 }
818
819 #[test]
820 fn first_existing_picks_the_earliest_present_name() {
821 let dir = std::env::temp_dir().join("amont-first-existing-test");
822 let _ = std::fs::create_dir_all(&dir);
823 let root = dir.to_string_lossy().into_owned();
824 let _ = std::fs::write(dir.join("second"), "x");
825 assert_eq!(
826 first_existing(&root, &["first", "second", "third"]).as_deref(),
827 Some("second")
828 );
829 assert_eq!(first_existing(&root, &["nope"]), None);
830 let _ = std::fs::remove_dir_all(&dir);
831 }
832}