amont_runtime/pushed_tree.rs
1//! Run a pre-push check against what is being PUSHED.
2//!
3//! `rust-test` and `run-tests-js` take their file set from the pushed refs —
4//! correct — and then run the suite with `current_dir` set to the developer's
5//! working tree. So the suite can pass on an uncommitted fix, or fail on an
6//! uncommitted experiment, and in neither case has it tested the commits being
7//! pushed. Same gap as the pre-commit one, from the other end.
8//!
9//! ## Why not the stash
10//!
11//! Holding unstaged changes aside is the pre-commit answer, and it is the wrong
12//! instrument here. A push is not a staging operation: the difference that
13//! matters is not tree-versus-index but tree-versus-the-commit-you-are-sending,
14//! and that includes everything staged-but-uncommitted too. Setting all of it
15//! aside for the length of a test suite would leave the developer looking at a
16//! tree that is not theirs for minutes at a time.
17//!
18//! ## What it costs, which is the whole question
19//!
20//! `git worktree add --detach <tip>` materialises the pushed commit somewhere
21//! else and the suite runs there. The tree is untouched, and an interrupted run
22//! leaves a worktree rather than a mangled checkout.
23//!
24//! The cost is real: a second checkout, and a build that cannot reuse the
25//! primary tree's `target/` cache, so the first push after this lands is a cold
26//! build. That is why it is opt-in — `git config amont.testPushedTree true`
27//! — rather than the default. The default keeps today's behaviour and now SAYS
28//! what it is testing, which was the actual bug: not that it used the tree, but
29//! that nobody knew it did.
30
31use std::path::{Path, PathBuf};
32
33use crate::ui::warning_sign;
34
35/// Whether the user asked for the accurate-but-slower answer.
36///
37/// Read through [`crate::config`], so `on`, `yes` and every capitalisation work
38/// exactly as git-config(1) says they do — and a value git cannot parse takes
39/// the default while SAYING so, rather than reading as a quiet "no".
40pub fn enabled(settings: &crate::config::Settings) -> bool {
41 crate::config::boolean_or(settings, "amont.testPushedTree", false)
42}
43
44/// The escape hatch: a command to run inside a fresh snapshot before any
45/// suite does, after amont's own preparation (see [`crate::snapshot_prep`]:
46/// `amont.snapshotCarry`, then the JavaScript dependencies).
47///
48/// A checkout is not a workspace, and most of what makes one is now
49/// amont's: `npm ci` / `pnpm install --frozen-lockfile` per lockfile, and
50/// the untracked files the repository names. What is left is per-repository
51/// knowledge amont cannot have — a code generator, a database client, a
52/// build step:
53///
54/// ```sh
55/// git config amont.snapshotPrepare "pnpm prisma generate"
56/// ```
57///
58/// When it is set it OWNS the dependencies — amont's own install step stands
59/// down, so a repository that already installs here does not install twice.
60/// Runs through the shell, in the snapshot, before the gate, and a failure
61/// is the snapshot's failure: no suite runs on a tree that was never made
62/// runnable. Used by both snapshot consumers — `amont.testPushedTree` at
63/// push time and the background rehearsal — so the two cannot drift. It gets
64/// `AMONT_SOURCE_WORKTREE`: the working tree the snapshot was taken from.
65const PREPARE: &str = "amont.snapshotPrepare";
66
67/// The environment variable naming the source working tree (see PREPARE).
68pub const SOURCE_WORKTREE_ENV: &str = "AMONT_SOURCE_WORKTREE";
69
70pub fn prepare_command(settings: &crate::config::Settings) -> Option<String> {
71 crate::config::string_value(settings, PREPARE).filter(|s| !s.trim().is_empty())
72}
73
74/// A checkout of the pushed commit, removed when it goes out of scope.
75pub struct PushedTree {
76 path: PathBuf,
77 repo: PathBuf,
78}
79
80impl PushedTree {
81 /// Materialise `tip`, or `None` when that is not possible — in which case
82 /// the caller falls back to the working tree and says so.
83 /// Takes the repository explicitly rather than relying on the working
84 /// directory: `set_current_dir` is process-global, so a test that changed
85 /// it would race every other test in the binary.
86 ///
87 /// Checkout AND preparation, for the push-time caller: a snapshot that
88 /// could not be prepared is no snapshot, said once, here.
89 pub fn create(
90 settings: &crate::config::Settings,
91 repo: &Path,
92 tip: &str,
93 ) -> Option<PushedTree> {
94 let tree = Self::checkout(repo, tip)?;
95 match tree.prepare(settings) {
96 Ok(()) => Some(tree),
97 Err(why) => {
98 // `Drop` removes the worktree; the caller hears `None` and
99 // says what it is doing instead.
100 println!("{} could not prepare the snapshot: {why}", warning_sign());
101 None
102 }
103 }
104 }
105
106 /// The checkout alone. The rehearsal registers itself between this and
107 /// [`PushedTree::prepare`], so an install that takes minutes is visible —
108 /// to `--status`, to a push that would otherwise start over, and to a
109 /// newer commit that must cancel it.
110 pub fn checkout(repo: &Path, tip: &str) -> Option<PushedTree> {
111 let base = std::env::temp_dir().join(unique_name("amont-push"));
112 Self::checkout_at(base, repo, tip)
113 }
114
115 /// The actual work, over an explicit path — split out so a test can hand
116 /// it a path it controls, since `create`'s own path is unpredictable BY
117 /// DESIGN and cannot be aimed at a fixture.
118 ///
119 /// `create_dir`, not a `remove_dir_all` before creating: that deleted
120 /// whatever was already at this path BEFORE this process had established
121 /// it owned it — an unpredictable name makes landing on an existing path
122 /// unlikely, not impossible, and "unlikely" is not the bar for a delete.
123 /// `create_dir` is exclusive: it fails loudly on anything already there
124 /// instead of removing it, and git's own `worktree add` is content to
125 /// receive a directory that already exists as long as it is empty —
126 /// which this one, having just been created, provably is.
127 fn checkout_at(base: PathBuf, repo: &Path, tip: &str) -> Option<PushedTree> {
128 std::fs::create_dir(&base).ok()?;
129 let ok = crate::git::succeeds(&[
130 "-C",
131 repo.to_str()?,
132 "worktree",
133 "add",
134 "--detach",
135 "--quiet",
136 base.to_str()?,
137 tip,
138 ]);
139 if !ok {
140 // Ours to clean up: we created it moments ago, so nothing else
141 // could have raced in ahead of us to make this delete unsafe.
142 let _ = std::fs::remove_dir_all(&base);
143 return None;
144 }
145 Some(PushedTree {
146 path: base,
147 repo: repo.to_path_buf(),
148 })
149 }
150
151 /// Make the checkout runnable: carry, dependencies, then
152 /// `amont.snapshotPrepare`. `Err` says why, in one line.
153 pub fn prepare(&self, settings: &crate::config::Settings) -> Result<(), String> {
154 let script = prepare_command(settings);
155 crate::snapshot_prep::run(settings, &self.repo, &self.path, script.is_some())?;
156 let Some(script) = script else {
157 return Ok(());
158 };
159 println!("preparing the snapshot: {script}");
160 #[cfg(unix)]
161 let mut cmd = {
162 let mut c = std::process::Command::new("sh");
163 c.arg("-c").arg(&script);
164 c
165 };
166 #[cfg(not(unix))]
167 let mut cmd = {
168 let mut c = std::process::Command::new("cmd");
169 c.arg("/C").arg(&script);
170 c
171 };
172 cmd.current_dir(&self.path)
173 .stdin(std::process::Stdio::null());
174 crate::hooks::common::strip_git_env(&mut cmd);
175 // the working tree the snapshot was taken FROM — where an installed
176 // workspace already lives (see PREPARE)
177 cmd.env(SOURCE_WORKTREE_ENV, &self.repo);
178 if crate::hooks::common::bounded_success(settings, &mut cmd, PREPARE) {
179 Ok(())
180 } else {
181 Err(format!("{PREPARE} failed in the snapshot"))
182 }
183 }
184
185 pub fn path(&self) -> &Path {
186 &self.path
187 }
188}
189
190/// `<prefix>-<pid>-<hash>`: the pid stays for a human correlating a leftover
191/// directory with a hung process, but the pid ALONE made the name guessable —
192/// `ps` hands it to anyone on the box — and a pre-planted directory or
193/// symlink at a predictable path in a world-writable `/tmp` is somebody
194/// else's decision about where our checkout goes.
195///
196/// It is no longer the difference between safe and destructive: `create_at`
197/// takes the path with an exclusive `create_dir` and refuses anything already
198/// there, rather than the `remove_dir_all`-first shape this comment used to
199/// describe. Unpredictability is now defence in depth — it means the refusal
200/// is not something an attacker can arrange on demand.
201///
202/// No dependency for real randomness here (this crate ships dependency-free),
203/// so the tail is a hash of the wall clock and the pid through
204/// `RandomState`'s own OS-seeded key — enough that guessing it in advance is
205/// impractical, not a cryptographic promise.
206fn unique_name(prefix: &str) -> String {
207 use std::collections::hash_map::RandomState;
208 use std::hash::{BuildHasher, Hash, Hasher};
209
210 let pid = std::process::id();
211 let mut hasher = RandomState::new().build_hasher();
212 pid.hash(&mut hasher);
213 std::time::SystemTime::now()
214 .duration_since(std::time::UNIX_EPOCH)
215 .unwrap_or_default()
216 .as_nanos()
217 .hash(&mut hasher);
218 format!("{prefix}-{pid}-{:016x}", hasher.finish())
219}
220
221impl Drop for PushedTree {
222 fn drop(&mut self) {
223 // `--force`: the suite may have written into it, and a build artefact
224 // must not be a reason to leave a worktree registered forever.
225 let _ = crate::git::succeeds(&[
226 "-C",
227 self.repo.to_str().unwrap_or_default(),
228 "worktree",
229 "remove",
230 "--force",
231 self.path.to_str().unwrap_or_default(),
232 ]);
233 let _ = std::fs::remove_dir_all(&self.path);
234 }
235}
236
237/// `(gate, tip)` pairs whose suite ACTUALLY ran in a checkout of `tip` —
238/// what happened, per check, as opposed to what `enabled()` says was asked
239/// for.
240///
241/// Read by `dispatch::stamp_tips`. It used to decide from the CONFIG plus a
242/// per-tip "the snapshot could not be made" set, which answers for the
243/// checks that asked for a snapshot and says nothing about one that never
244/// did: a declared `amont.conf` gate ran in the working tree, passed on an
245/// uncommitted fix, and was stamped onto a tip that had never been tested —
246/// so the next push of that tip skipped it. A stamp is a claim about one
247/// gate and one tree, and the record it is made from has to be that fine.
248///
249/// A `Mutex` because pre-push checks run concurrently and each loops over its
250/// own refs; a poisoned lock reads as "did not run there", which costs a
251/// redundant gate run and never a false stamp.
252static SNAPSHOTTED: std::sync::OnceLock<
253 std::sync::Mutex<std::collections::HashSet<(String, String)>>,
254> = std::sync::OnceLock::new();
255
256fn snapshotted() -> &'static std::sync::Mutex<std::collections::HashSet<(String, String)>> {
257 SNAPSHOTTED.get_or_init(|| std::sync::Mutex::new(std::collections::HashSet::new()))
258}
259
260fn note_snapshot(gate: &str, tip: &str) {
261 if let Ok(mut set) = snapshotted().lock() {
262 set.insert((gate.to_string(), tip.to_string()));
263 }
264}
265
266/// Did `gate` run in a checkout of `tip` — the pushed content itself, not
267/// whatever the working tree held?
268///
269/// `false` also when the lock is poisoned: a stamp is a claim that the gate
270/// ran on exactly this content, and a claim we cannot check is one we do not
271/// make.
272pub fn ran_on_tip(gate: &str, tip: &str) -> bool {
273 match snapshotted().lock() {
274 Ok(set) => set.contains(&(gate.to_string(), tip.to_string())),
275 Err(_) => false,
276 }
277}
278
279/// Where a pre-push suite should run, and whether that is the honest answer.
280///
281/// Takes ONE commit, not the whole ref list: a push can carry several refs
282/// (`git push origin a b`), each with its own tip, and a caller that checked
283/// out only the first one and ran every ref's tests against it would test
284/// the second ref's code against the first ref's tree. Callers loop over
285/// their own refs and pass each one's tip in turn.
286///
287/// `gate` is the check's id (`Check::name`) — what a stamp names, and what
288/// [`ran_on_tip`] is asked about when `dispatch::stamp_tips` decides whether
289/// this gate may vouch for this tip. A check that runs a suite anywhere
290/// else than the directory returned here is answering about content no
291/// stamp may claim.
292///
293/// Returns the directory plus the guard that owns it — dropping the guard
294/// removes the worktree, so the caller must hold it for the length of the run.
295pub fn where_to_run(
296 settings: &crate::config::Settings,
297 tip: &str,
298 fallback: &str,
299 gate: &str,
300) -> (PathBuf, Option<PushedTree>) {
301 // Inside a rehearsal the working tree IS a snapshot of the tip: a
302 // second checkout would test the same content twice, and the warning
303 // below would be false.
304 if crate::rehearsal::in_snapshot() {
305 return (PathBuf::from(fallback), None);
306 }
307 if !enabled(settings) {
308 // Today's behaviour, but no longer silent about it. NOT a fallback:
309 // nobody asked for a snapshot, and `stamp_tips` already knows to
310 // vouch for the working tree only when it IS the tip.
311 //
312 // Once per process: every gate in the push asks this, and one line
313 // says it — the fourth repetition would teach the reader to skip it.
314 static SAID: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
315 if !SAID.swap(true, std::sync::atomic::Ordering::Relaxed) {
316 println!(
317 "{} testing the WORKING TREE, not the pushed commits \
318 (`git config amont.testPushedTree true` to test what you are pushing)",
319 warning_sign()
320 );
321 }
322 return (PathBuf::from(fallback), None);
323 }
324 match PushedTree::create(settings, Path::new(fallback), tip) {
325 Some(tree) => {
326 // Recorded, not inferred. `stamp_tips` used to read `enabled()`
327 // and conclude "the suite ran on the tip itself" — for every
328 // gate, including ones that never came here. Only a gate that
329 // was handed this checkout can be said to have run in it.
330 note_snapshot(gate, tip);
331 let path = tree.path().to_path_buf();
332 (path, Some(tree))
333 }
334 None => {
335 // Not recorded, and that IS the record: the gate passed on a
336 // possibly-dirty working tree, and stamping the tip anyway —
337 // which reading the config would do — let the next push of that
338 // tree (a retry after a dropped connection, or a tag on the
339 // merged commit) skip a gate nobody had run on its content.
340 // `gate_stamp`'s own promise is that no path here can let an
341 // unchecked commit through.
342 println!(
343 "{} could not check out {tip} to test it; testing the working tree instead \
344 (nothing will be stamped for it)",
345 warning_sign()
346 );
347 (PathBuf::from(fallback), None)
348 }
349 }
350}
351
352#[cfg(test)]
353mod tests {
354 use super::*;
355
356 fn test_settings() -> crate::config::Settings {
357 crate::config::Settings::default()
358 }
359
360 /// The whole point: two calls must not name the same path, or a
361 /// predictable name is right back to being predictable.
362 #[test]
363 fn unique_name_does_not_repeat() {
364 let a = unique_name("amont-push");
365 let b = unique_name("amont-push");
366 assert_ne!(a, b);
367 assert!(a.starts_with("amont-push-"));
368 }
369
370 /// The point of the whole fix: something already at the target path is
371 /// left ALONE, not deleted to make way. `create_at` fails closed
372 /// (`None`) instead of the old `remove_dir_all`-first shape, which would
373 /// have destroyed `sentinel.txt` here to clear the path for a worktree
374 /// that was never going to use it anyway (the repo below is fake).
375 #[test]
376 fn an_existing_path_is_left_alone_not_cleared() {
377 let base = std::env::temp_dir().join(format!("pushed-collision-{}", std::process::id()));
378 let _ = std::fs::remove_dir_all(&base);
379 std::fs::create_dir_all(&base).unwrap();
380 std::fs::write(base.join("sentinel.txt"), "do not delete me").unwrap();
381
382 let got = PushedTree::checkout_at(base.clone(), Path::new("/does/not/matter"), "HEAD");
383 assert!(
384 got.is_none(),
385 "must refuse rather than reuse a path it did not create"
386 );
387 assert_eq!(
388 std::fs::read_to_string(base.join("sentinel.txt")).unwrap(),
389 "do not delete me",
390 "an existing path must never be cleared to make room"
391 );
392 let _ = std::fs::remove_dir_all(&base);
393 }
394
395 fn repo(name: &str) -> PathBuf {
396 let d = std::env::temp_dir().join(format!("pushed-{name}-{}", std::process::id()));
397 let _ = std::fs::remove_dir_all(&d);
398 std::fs::create_dir_all(&d).unwrap();
399 for args in [
400 vec!["init", "-q", "--template=", "."],
401 vec!["config", "user.email", "t@t.test"],
402 vec!["config", "user.name", "t"],
403 // Git for Windows rewrites line endings on checkout; a byte
404 // comparison would otherwise assert git's newline policy.
405 vec!["config", "core.autocrlf", "false"],
406 ] {
407 std::process::Command::new("git")
408 .args(&args)
409 .current_dir(&d)
410 .output()
411 .expect("git");
412 }
413 d
414 }
415
416 /// The point: the checkout holds the COMMIT, not whatever the developer
417 /// has open.
418 #[test]
419 fn the_worktree_holds_the_committed_content() {
420 let d = repo("tree");
421 let git = |args: &[&str]| {
422 std::process::Command::new("git")
423 .args(args)
424 .current_dir(&d)
425 .output()
426 .expect("git")
427 };
428 std::fs::write(d.join("a.txt"), "committed\n").unwrap();
429 git(&["add", "-A"]);
430 git(&["commit", "-qm", "seed"]);
431 let head = String::from_utf8_lossy(&git(&["rev-parse", "HEAD"]).stdout)
432 .trim()
433 .to_string();
434 // Uncommitted, and it must not travel.
435 std::fs::write(d.join("a.txt"), "dirty, not pushed\n").unwrap();
436
437 let tree = PushedTree::create(&test_settings(), &d, &head).expect("worktree");
438 let seen = std::fs::read_to_string(tree.path().join("a.txt")).unwrap();
439 let at = tree.path().to_path_buf();
440 drop(tree);
441
442 assert_eq!(seen, "committed\n", "the worktree saw the dirty tree");
443 assert!(!at.exists(), "the worktree outlived its guard");
444 let _ = std::fs::remove_dir_all(&d);
445 }
446}