Skip to main content

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() -> bool {
41    crate::config::boolean_or("amont.testPushedTree", false)
42}
43
44/// A checkout of the pushed commit, removed when it goes out of scope.
45pub struct PushedTree {
46    path: PathBuf,
47    repo: PathBuf,
48}
49
50impl PushedTree {
51    /// Materialise `tip`, or `None` when that is not possible — in which case
52    /// the caller falls back to the working tree and says so.
53    /// Takes the repository explicitly rather than relying on the working
54    /// directory: `set_current_dir` is process-global, so a test that changed
55    /// it would race every other test in the binary.
56    pub fn create(repo: &Path, tip: &str) -> Option<PushedTree> {
57        let base = std::env::temp_dir().join(unique_name("amont-push"));
58        Self::create_at(base, repo, tip)
59    }
60
61    /// The actual work, over an explicit path — split out so a test can hand
62    /// it a path it controls, since `create`'s own path is unpredictable BY
63    /// DESIGN and cannot be aimed at a fixture.
64    ///
65    /// `create_dir`, not a `remove_dir_all` before creating: that deleted
66    /// whatever was already at this path BEFORE this process had established
67    /// it owned it — an unpredictable name makes landing on an existing path
68    /// unlikely, not impossible, and "unlikely" is not the bar for a delete.
69    /// `create_dir` is exclusive: it fails loudly on anything already there
70    /// instead of removing it, and git's own `worktree add` is content to
71    /// receive a directory that already exists as long as it is empty —
72    /// which this one, having just been created, provably is.
73    fn create_at(base: PathBuf, repo: &Path, tip: &str) -> Option<PushedTree> {
74        std::fs::create_dir(&base).ok()?;
75        let ok = crate::git::succeeds(&[
76            "-C",
77            repo.to_str()?,
78            "worktree",
79            "add",
80            "--detach",
81            "--quiet",
82            base.to_str()?,
83            tip,
84        ]);
85        if !ok {
86            // Ours to clean up: we created it moments ago, so nothing else
87            // could have raced in ahead of us to make this delete unsafe.
88            let _ = std::fs::remove_dir_all(&base);
89            return None;
90        }
91        Some(PushedTree {
92            path: base,
93            repo: repo.to_path_buf(),
94        })
95    }
96
97    pub fn path(&self) -> &Path {
98        &self.path
99    }
100}
101
102/// `<prefix>-<pid>-<hash>`: the pid stays for a human correlating a leftover
103/// directory with a hung process, but the pid ALONE is what made the old name
104/// guessable — `ps` hands it to anyone on the box — which matters because
105/// this path is `remove_dir_all`'d before it is used. A pre-planted symlink
106/// at a predictable name turns that into a race with whatever the symlink
107/// points at. No dependency for real randomness here (this crate ships
108/// dependency-free), so the tail is a hash of the wall clock and the pid
109/// through `RandomState`'s own OS-seeded key — enough that guessing it in
110/// advance is impractical, not a cryptographic promise.
111fn unique_name(prefix: &str) -> String {
112    use std::collections::hash_map::RandomState;
113    use std::hash::{BuildHasher, Hash, Hasher};
114
115    let pid = std::process::id();
116    let mut hasher = RandomState::new().build_hasher();
117    pid.hash(&mut hasher);
118    std::time::SystemTime::now()
119        .duration_since(std::time::UNIX_EPOCH)
120        .unwrap_or_default()
121        .as_nanos()
122        .hash(&mut hasher);
123    format!("{prefix}-{pid}-{:016x}", hasher.finish())
124}
125
126impl Drop for PushedTree {
127    fn drop(&mut self) {
128        // `--force`: the suite may have written into it, and a build artefact
129        // must not be a reason to leave a worktree registered forever.
130        let _ = crate::git::succeeds(&[
131            "-C",
132            self.repo.to_str().unwrap_or_default(),
133            "worktree",
134            "remove",
135            "--force",
136            self.path.to_str().unwrap_or_default(),
137        ]);
138        let _ = std::fs::remove_dir_all(&self.path);
139    }
140}
141
142/// Where a pre-push suite should run, and whether that is the honest answer.
143///
144/// Takes ONE commit, not the whole ref list: a push can carry several refs
145/// (`git push origin a b`), each with its own tip, and a caller that checked
146/// out only the first one and ran every ref's tests against it would test
147/// the second ref's code against the first ref's tree. Callers loop over
148/// their own refs and pass each one's tip in turn.
149///
150/// Returns the directory plus the guard that owns it — dropping the guard
151/// removes the worktree, so the caller must hold it for the length of the run.
152pub fn where_to_run(tip: &str, fallback: &str) -> (PathBuf, Option<PushedTree>) {
153    if !enabled() {
154        // Today's behaviour, but no longer silent about it.
155        println!(
156            "{} testing the WORKING TREE, not the pushed commits \
157             (`git config amont.testPushedTree true` to test what you are pushing)",
158            warning_sign()
159        );
160        return (PathBuf::from(fallback), None);
161    }
162    match PushedTree::create(Path::new(fallback), tip) {
163        Some(tree) => {
164            let path = tree.path().to_path_buf();
165            (path, Some(tree))
166        }
167        None => {
168            println!(
169                "{} could not check out {tip} to test it; testing the working tree instead",
170                warning_sign()
171            );
172            (PathBuf::from(fallback), None)
173        }
174    }
175}
176
177#[cfg(test)]
178mod tests {
179    use super::*;
180
181    /// The whole point: two calls must not name the same path, or a
182    /// predictable name is right back to being predictable.
183    #[test]
184    fn unique_name_does_not_repeat() {
185        let a = unique_name("amont-push");
186        let b = unique_name("amont-push");
187        assert_ne!(a, b);
188        assert!(a.starts_with("amont-push-"));
189    }
190
191    /// The point of the whole fix: something already at the target path is
192    /// left ALONE, not deleted to make way. `create_at` fails closed
193    /// (`None`) instead of the old `remove_dir_all`-first shape, which would
194    /// have destroyed `sentinel.txt` here to clear the path for a worktree
195    /// that was never going to use it anyway (the repo below is fake).
196    #[test]
197    fn an_existing_path_is_left_alone_not_cleared() {
198        let base = std::env::temp_dir().join(format!("pushed-collision-{}", std::process::id()));
199        let _ = std::fs::remove_dir_all(&base);
200        std::fs::create_dir_all(&base).unwrap();
201        std::fs::write(base.join("sentinel.txt"), "do not delete me").unwrap();
202
203        let got = PushedTree::create_at(base.clone(), Path::new("/does/not/matter"), "HEAD");
204        assert!(
205            got.is_none(),
206            "must refuse rather than reuse a path it did not create"
207        );
208        assert_eq!(
209            std::fs::read_to_string(base.join("sentinel.txt")).unwrap(),
210            "do not delete me",
211            "an existing path must never be cleared to make room"
212        );
213        let _ = std::fs::remove_dir_all(&base);
214    }
215
216    fn repo(name: &str) -> PathBuf {
217        let d = std::env::temp_dir().join(format!("pushed-{name}-{}", std::process::id()));
218        let _ = std::fs::remove_dir_all(&d);
219        std::fs::create_dir_all(&d).unwrap();
220        for args in [
221            vec!["init", "-q", "--template=", "."],
222            vec!["config", "user.email", "t@t.test"],
223            vec!["config", "user.name", "t"],
224            // Git for Windows rewrites line endings on checkout; a byte
225            // comparison would otherwise assert git's newline policy.
226            vec!["config", "core.autocrlf", "false"],
227        ] {
228            std::process::Command::new("git")
229                .args(&args)
230                .current_dir(&d)
231                .output()
232                .expect("git");
233        }
234        d
235    }
236
237    /// The point: the checkout holds the COMMIT, not whatever the developer
238    /// has open.
239    #[test]
240    fn the_worktree_holds_the_committed_content() {
241        let d = repo("tree");
242        let git = |args: &[&str]| {
243            std::process::Command::new("git")
244                .args(args)
245                .current_dir(&d)
246                .output()
247                .expect("git")
248        };
249        std::fs::write(d.join("a.txt"), "committed\n").unwrap();
250        git(&["add", "-A"]);
251        git(&["commit", "-qm", "seed"]);
252        let head = String::from_utf8_lossy(&git(&["rev-parse", "HEAD"]).stdout)
253            .trim()
254            .to_string();
255        // Uncommitted, and it must not travel.
256        std::fs::write(d.join("a.txt"), "dirty, not pushed\n").unwrap();
257
258        let tree = PushedTree::create(&d, &head).expect("worktree");
259        let seen = std::fs::read_to_string(tree.path().join("a.txt")).unwrap();
260        let at = tree.path().to_path_buf();
261        drop(tree);
262
263        assert_eq!(seen, "committed\n", "the worktree saw the dirty tree");
264        assert!(!at.exists(), "the worktree outlived its guard");
265        let _ = std::fs::remove_dir_all(&d);
266    }
267}