Skip to main content

amont_runtime/hooks/
pull_rebase.rs

1//! pre-push-pull-rebase — sync a branch with ITS OWN upstream before pushing,
2//! and warn (never act) when the default branch has moved ahead.
3//!
4//! The hardening in the shell version is the point, and is preserved exactly:
5//! an older version ran `git pull --rebase origin HEAD`, where the remote ref
6//! `HEAD` resolves to the remote's DEFAULT branch — so every push silently
7//! rebased onto main, autostashing uncommitted work. Hence: never touch a dirty
8//! tree, rebase only onto the branch's own upstream, and abort cleanly on
9//! conflict rather than leaving a half-rebased state.
10
11use crate::check::Outcome;
12use crate::git;
13use crate::ui::{error_sign, highlight, valid_sign, warning_sign};
14
15/// `ahead[[:space:]]+N,[[:space:]]*behind[[:space:]]+M` over `git status -sb`.
16///
17/// Both counts present means the branch and its upstream have diverged, and an
18/// automatic rebase is exactly the wrong move. The COUNTS come back too, not
19/// just the fact: "how far apart" is the first thing anyone wants to know, and
20/// the predicate used to throw it away.
21/// `word[[:space:]]+N` at the first eligible occurrence in `s` — shared by
22/// [`divergence`] and [`behind_count`] so the question "does an `ahead`
23/// or `behind` token here actually mean a count" has exactly one answer
24/// rather than two copies that could drift.
25fn count_after(s: &str, word: &str) -> Option<(u64, usize)> {
26    let i = s.find(word)?;
27    let after = &s[i + word.len()..];
28    let trimmed = after.trim_start_matches([' ', '\t']);
29    if trimmed.len() == after.len() {
30        return None; // `word` must be followed by whitespace
31    }
32    let digits: String = trimmed.chars().take_while(char::is_ascii_digit).collect();
33    if digits.is_empty() {
34        return None;
35    }
36    let consumed = i + word.len() + (after.len() - trimmed.len()) + digits.len();
37    Some((digits.parse().ok()?, consumed))
38}
39
40pub fn divergence(status: &str) -> Option<(u64, u64)> {
41    for line in status.lines() {
42        let mut rest = line;
43        while let Some((ahead, used)) = count_after(rest, "ahead") {
44            let tail = &rest[used..];
45            if let Some(t) = tail.strip_prefix(',') {
46                if let Some((behind, _)) = count_after(t, "behind") {
47                    // `behind` must be the NEXT token, not merely present later
48                    // on the line.
49                    if t.trim_start_matches([' ', '\t']).starts_with("behind") {
50                        return Some((ahead, behind));
51                    }
52                }
53            }
54            rest = tail;
55        }
56    }
57    None
58}
59
60/// `behind[[:space:]]+N` over `git status -sb`, present or not — UNLIKE
61/// [`divergence`], which only answers when `ahead` is ALSO on the line.
62///
63/// `git status -sb` prints a bare `[behind M]` (no `ahead` at all) when the
64/// branch has nothing of its own to push yet is missing upstream commits —
65/// exactly "a sync would do something", independent of whether the branch is
66/// also ahead. `divergence` cannot answer that question; it was built to
67/// answer a narrower one (are the two DIVERGED, which needs both counts).
68pub fn behind_count(status: &str) -> Option<u64> {
69    status
70        .lines()
71        .find_map(|line| count_after(line, "behind").map(|(n, _)| n))
72}
73
74/// `^[[:space:]*+]+<name>$` over `git branch` output — the indentation git
75/// always prints, plus the markers it puts in column 0.
76///
77/// `+` is not decoration: since git 2.23, a branch checked out in ANOTHER
78/// WORKTREE is printed `+ main` rather than `  main`. That is a completely
79/// ordinary state in this repository's own workflow, and without `+` in the
80/// trim set the whole default-branch advisory (step 4) silently never fired —
81/// `lists_branch` answered false for both `main` and `master`, and the function
82/// returned before reaching it.
83///
84/// The `body.len() < stripped.len()` guard STAYS, and is why `for-each-ref` is
85/// not the answer here: it is what stops a `## main...origin/main` status line
86/// matching, and `+ main` still strips two characters, so the guard costs
87/// nothing. `for-each-ref` produces undecorated lines the guard would reject.
88pub fn lists_branch(branch_list: &str, name: &str) -> bool {
89    branch_list.lines().any(|line| {
90        let stripped = line.trim_end_matches(['\r']);
91        let body = stripped.trim_start_matches([' ', '\t', '*', '+']);
92        !body.is_empty() && body.len() < stripped.len() && body == name
93    })
94}
95
96/// Left side of `git rev-list --left-right --count <a>...<b>`: how far the
97/// default branch is ahead of us.
98pub fn ahead_count(rev_list: &str) -> Option<u64> {
99    rev_list.split_whitespace().next()?.parse().ok()
100}
101
102pub fn run(_args: &[std::ffi::OsString]) -> Outcome {
103    // 1. Never auto-rebase a dirty tree: that autostashes real work and can
104    //    leave a broken mid-rebase state during a push.
105    if !git::stdout(&["status", "--porcelain"])
106        .unwrap_or_default()
107        .is_empty()
108    {
109        println!(
110            "{} Uncommitted changes — skipping pre-push pull-rebase.",
111            warning_sign()
112        );
113        return Outcome::Passed;
114    }
115
116    // 2. Only sync a branch that HAS an upstream, and rebase onto that — never
117    //    the default branch. A brand-new branch has nothing to sync.
118    let Some(upstream) =
119        git::stdout(&["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"])
120    else {
121        return Outcome::Passed;
122    };
123
124    // 2a. The upstream has to be a REAL remote, not merely something with a
125    //     `/` in its name. `branch.<name>.remote` is what `git pull`/`fetch`
126    //     itself reads to resolve `@{u}` — asking IT, rather than guessing
127    //     the remote by splitting `upstream` on '/' and falling back to
128    //     "origin", is the fix for a real incident: `git worktree add -b x
129    //     <path> main` sets the new branch's upstream to the LOCAL branch
130    //     `main` (no slash at all — `@{u}` prints bare `main`), the old
131    //     fallback silently read that as `origin/main`, and the bare
132    //     `git pull --rebase` two steps down synced from LOCAL main — not
133    //     origin — while every check and message around it talked about
134    //     origin. Move `main` in the meantime (a `git reset --hard` on it in
135    //     another worktree, say) and the next push silently rebases onto
136    //     wherever it ended up, no divergence check catching it because the
137    //     hand-rolled remote guess was never asking the real question.
138    let Some(current) = git::stdout(&["symbolic-ref", "--short", "HEAD"]) else {
139        return Outcome::Passed; // detached HEAD: nothing to sync
140    };
141    let remote =
142        git::stdout(&["config", "--get", &format!("branch.{current}.remote")]).unwrap_or_default();
143    let is_a_real_remote = !remote.is_empty()
144        && git::stdout(&["remote"])
145            .unwrap_or_default()
146            .lines()
147            .any(|r| r == remote);
148    if !is_a_real_remote {
149        println!(
150            "{} {upstream} is not a remote-tracking branch — skipping sync.",
151            warning_sign()
152        );
153        return Outcome::Passed;
154    }
155    let branch = upstream
156        .strip_prefix(&format!("{remote}/"))
157        .unwrap_or(&upstream);
158
159    // 2b. The upstream can be configured locally but GONE on the remote — the
160    //     normal state right after a PR squash-merges with delete-on-merge.
161    //     `git pull --rebase` would fail on the missing ref and read as a
162    //     conflict, wrongly blocking the push.
163    if !git::succeeds(&["ls-remote", "--exit-code", "--heads", &remote, branch]) {
164        println!(
165            "{} Upstream {upstream} no longer exists on the remote (merged + auto-deleted?) — skipping sync.", warning_sign()
166        );
167        return Outcome::Passed;
168    }
169
170    // 3. Diverged → warn and DO NOT rebase, but carry on to the default-branch
171    //    check below (the shell fell through here too).
172    let status = git::stdout(&["status", "-sb"]).unwrap_or_default();
173    if let Some((ahead, behind)) = divergence(&status) {
174        // Divergence has two causes and they want OPPOSITE actions, so this
175        // says what it saw and lets you pick. The old copy prescribed
176        // `git pull --rebase` unconditionally, which after a local rebase or
177        // amend is the one command that undoes the work you are pushing — it
178        // replays the upstream commits you just rewrote.
179        //
180        // The hook cannot tell the two apart: git does not tell a pre-push hook
181        // whether `--force` was passed, and both cases are non-fast-forward.
182        // Guessing wrong here costs someone their rebase, so it does not guess.
183        println!(
184            "{} Branch and upstream have diverged ({ahead} ahead, {behind} behind) — not auto-rebasing.",
185            warning_sign()
186        );
187        println!(
188            "    Rebased or amended locally? That is expected — push with {}.",
189            highlight("git push --force-with-lease")
190        );
191        println!(
192            "    Someone else pushed here? Reconcile first with {} (or {}).",
193            highlight("git pull --rebase"),
194            highlight("git merge")
195        );
196    } else if behind_count(&status).unwrap_or(0) > 0
197        && !git::succeeds(&["pull", "--rebase", &remote, branch])
198    {
199        // `behind_count > 0` gates the attempt itself, not just its outcome:
200        // with nothing behind, the upstream has no commits to reconcile with,
201        // so `pull --rebase` has nothing to do BY DEFINITION — and attempting
202        // it anyway is not merely wasted work, it is a real subprocess rebase
203        // that can choke on the local branch's own history for a
204        // reconciliation nothing needed. A branch carrying a merge commit
205        // (recording a hand-resolved reconciliation with a THIRD branch, say)
206        // is exactly such a shape: `pull --rebase` tries to linearize it by
207        // full reachability rather than first-parent, replays commits that
208        // were already incorporated, and fails loudly over a push that was a
209        // clean fast-forward all along. Behind-only or diverged pushes still
210        // go through the real sync below; only the pointless case is skipped.
211        //
212        // Explicit remote and branch, not a bare `pull --rebase` trusting
213        // ambient `branch.*.remote`/`.merge` — `remote`/`branch` are already
214        // the verified pair from 2a/2b, and repeating them here means this
215        // sync can never again silently use something other than what was
216        // just checked.
217        // Abort so the tree is never left half-rebased.
218        let _ = git::succeeds(&["rebase", "--abort"]);
219        println!(
220            "{} pull --rebase hit conflicts (rebase aborted, tree restored).",
221            error_sign()
222        );
223        println!("    Resolve manually: {}", highlight("git pull --rebase"));
224        return Outcome::Failed;
225    } else {
226        println!("{} Branch is in sync with its upstream", valid_sign());
227    }
228
229    // 4. Informational only — never acts.
230    // UNTRIMMED, and that is not a detail. `git::stdout` trims the whole
231    // buffer, which strips the two leading spaces off the FIRST line — so when
232    // `git branch` happened to list the default branch first, `lists_branch`'s
233    // decoration guard rejected it and the advisory below never fired. Whether
234    // it fired depended on the alphabetical position of the branch you were on,
235    // which is why it looked intermittent rather than broken.
236    let branch_list = git::stdout_raw(&["branch"])
237        .map(|out| String::from_utf8_lossy(&out).into_owned())
238        .unwrap_or_default();
239    let default_branch = if lists_branch(&branch_list, "main") {
240        "main"
241    } else if lists_branch(&branch_list, "master") {
242        "master"
243    } else {
244        return Outcome::Passed;
245    };
246
247    // `remote`, not a hardcoded "origin". Step 2 above spends thirteen lines of
248    // comment establishing `remote` as the VERIFIED one for this branch, and
249    // then this step ignored it: in a repository whose remote is `upstream`,
250    // the fetch failed (ignored) and `rev-list origin/<branch>...HEAD` returned
251    // None, so the advisory was silently skipped.
252    let _ = git::succeeds(&["fetch", &remote, default_branch]);
253    let range = format!("{remote}/{default_branch}...HEAD");
254    if let Some(n) =
255        git::stdout(&["rev-list", "--left-right", "--count", &range]).and_then(|s| ahead_count(&s))
256    {
257        if n > 0 {
258            // The shell took `head -c 1` of this count — the FIRST CHARACTER —
259            // so 12 commits ahead printed "1". The test was only ever
260            // non-zero/zero, so the wrong number went unnoticed. Parsed properly
261            // here.
262            println!(
263                "{} {remote}/{default_branch} is ahead by {n} commit(s).",
264                warning_sign()
265            );
266            println!(
267                "    Consider before merging: {}",
268                highlight(&format!("git merge {remote}/{default_branch}"))
269            );
270        }
271    }
272    Outcome::Passed
273}
274
275#[cfg(test)]
276mod tests {
277    use super::{ahead_count, behind_count, divergence, lists_branch};
278
279    #[test]
280    fn detects_divergence_only_when_both_counts_are_present() {
281        assert!(divergence("## feat/x...origin/feat/x [ahead 1, behind 2]").is_some());
282        assert!(divergence("## a...b [ahead 12,  behind 3]").is_some());
283        // ahead only, or behind only, is NOT divergence — a rebase is fine
284        assert!(divergence("## feat/x...origin/feat/x [ahead 3]").is_none());
285        assert!(divergence("## feat/x...origin/feat/x [behind 2]").is_none());
286        assert!(divergence("## feat/x...origin/feat/x").is_none());
287        assert!(divergence("## ahead-of-time...origin/x").is_none());
288    }
289
290    /// The counts are the message now, so a wrong one is a wrong message.
291    /// Two digits especially: this file already carries a bug where a count of
292    /// 12 printed as 1.
293    #[test]
294    fn reports_how_far_apart_the_two_are() {
295        assert_eq!(
296            divergence("## feat/x...origin/feat/x [ahead 1, behind 2]"),
297            Some((1, 2))
298        );
299        assert_eq!(
300            divergence("## a...b [ahead 12,  behind 34]"),
301            Some((12, 34))
302        );
303    }
304
305    /// A branch legitimately named `ahead-of-behind` must not be parsed as a
306    /// pair of counts, and `behind` has to be the token straight after the
307    /// comma rather than merely somewhere on the line.
308    #[test]
309    fn branch_names_are_not_mistaken_for_counts() {
310        assert!(divergence("## ahead 3...origin/behind 4").is_none());
311        // The word has to be followed by a SPACE, so a branch whose name runs
312        // straight into digits is not read as a count.
313        assert!(divergence("## a...b [ahead3, behind4]").is_none());
314        assert!(divergence("## ahead12...origin/behind34").is_none());
315        assert!(divergence("## a...b [ahead 3, xbehind 4]").is_none());
316        assert!(divergence("## ahead-of/behind...origin/ahead-of/behind").is_none());
317    }
318
319    /// `git branch` puts a marker in column 0, and there are TWO of them.
320    ///
321    /// `*` is the current branch; `+` — since git 2.23 — is a branch checked
322    /// out in ANOTHER WORKTREE. That second one is an entirely ordinary state
323    /// in this repository's own workflow, and without it in the trim set the
324    /// whole default-branch advisory silently never fired: `lists_branch`
325    /// answered false for `main` and for `master`, and `run` returned before
326    /// reaching step 4.
327    #[test]
328    fn recognises_git_branch_lines() {
329        let list = "  feat/x\n* main\n  master-ish\n";
330        assert!(lists_branch(list, "main"));
331        assert!(!lists_branch(list, "master")); // master-ish is a different branch
332        assert!(!lists_branch(list, "feat")); // must match the whole name
333        assert!(lists_branch(list, "feat/x"));
334
335        // The worktree marker.
336        let elsewhere = "+ main\n* feat/x\n";
337        assert!(
338            lists_branch(elsewhere, "main"),
339            "a branch checked out in another worktree is still a branch"
340        );
341
342        // The decoration guard is DELIBERATE, not incidental: an undecorated
343        // line is not `git branch` output, and this is what stops a
344        // `## main...origin/main` status line matching. It is also why this
345        // cannot be switched to `for-each-ref`, whose lines carry no marker.
346        assert!(!lists_branch("main\n", "main"));
347        assert!(!lists_branch("## main...origin/main\n", "main"));
348
349        // …which is why `run` must NOT read `git branch` through
350        // `git::stdout`: that trims the whole buffer, eating the FIRST line's
351        // indentation. When git listed the default branch first, this is
352        // exactly the input the guard was handed, and the advisory silently
353        // never fired.
354        assert!(!lists_branch("main\n* feat/x\n", "main"));
355        assert!(lists_branch("  main\n* feat/x\n", "main"));
356    }
357
358    /// A count of 12 must read as 12, not 1 — the shell's `head -c 1`.
359    #[test]
360    fn parses_the_full_ahead_count() {
361        assert_eq!(ahead_count("12\t3"), Some(12));
362        assert_eq!(ahead_count("0\t5"), Some(0));
363        assert_eq!(ahead_count(""), None);
364    }
365
366    /// The whole point: `behind_count`, unlike `divergence`, answers even
367    /// when `ahead` is not on the line at all.
368    #[test]
369    fn behind_count_does_not_require_ahead() {
370        assert_eq!(
371            behind_count("## feat/x...origin/feat/x [behind 2]"),
372            Some(2)
373        );
374        assert_eq!(
375            behind_count("## feat/x...origin/feat/x [ahead 1, behind 2]"),
376            Some(2)
377        );
378    }
379
380    /// Ahead-only, or fully in sync, is "nothing behind" — the shape that
381    /// means a sync has nothing to reconcile.
382    #[test]
383    fn behind_count_is_none_when_there_is_nothing_behind() {
384        assert_eq!(behind_count("## feat/x...origin/feat/x [ahead 3]"), None);
385        assert_eq!(behind_count("## feat/x...origin/feat/x"), None);
386        assert_eq!(behind_count(""), None);
387    }
388
389    /// The same false-positive guard `divergence` has: a branch merely
390    /// NAMED with "behind" in it, glued to non-whitespace, is not a count.
391    #[test]
392    fn behind_count_is_not_fooled_by_a_branch_name() {
393        assert!(behind_count("## my-behind-thing...origin/my-behind-thing").is_none());
394        assert!(behind_count("## a...b [behind4]").is_none());
395    }
396}