Skip to main content

greengate_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, warning_sign};
14
15/// The words a pull-rebase that moved HEAD ends its message with.
16///
17/// `amont land` reads the hook's output for exactly this, to tell "the hook
18/// brought the branch up to date and wants a second push" from every other
19/// refusal. One constant, so the sentence and its reader cannot drift.
20pub const PUSH_AGAIN: &str = "push again";
21
22/// `ahead[[:space:]]+N,[[:space:]]*behind[[:space:]]+M` over `git status -sb`.
23///
24/// Both counts present means the branch and its upstream have diverged, and an
25/// automatic rebase is exactly the wrong move. The COUNTS come back too, not
26/// just the fact: "how far apart" is the first thing anyone wants to know, and
27/// the predicate used to throw it away.
28/// `word[[:space:]]+N` at the first eligible occurrence in `s` — shared by
29/// [`divergence`] and [`behind_count`] so the question "does an `ahead`
30/// or `behind` token here actually mean a count" has exactly one answer
31/// rather than two copies that could drift.
32fn count_after(s: &str, word: &str) -> Option<(u64, usize)> {
33    let i = s.find(word)?;
34    let after = &s[i + word.len()..];
35    let trimmed = after.trim_start_matches([' ', '\t']);
36    if trimmed.len() == after.len() {
37        return None; // `word` must be followed by whitespace
38    }
39    let digits: String = trimmed.chars().take_while(char::is_ascii_digit).collect();
40    if digits.is_empty() {
41        return None;
42    }
43    let consumed = i + word.len() + (after.len() - trimmed.len()) + digits.len();
44    Some((digits.parse().ok()?, consumed))
45}
46
47pub fn divergence(status: &str) -> Option<(u64, u64)> {
48    for line in status.lines() {
49        let mut rest = line;
50        while let Some((ahead, used)) = count_after(rest, "ahead") {
51            let tail = &rest[used..];
52            if let Some(t) = tail.strip_prefix(',') {
53                if let Some((behind, _)) = count_after(t, "behind") {
54                    // `behind` must be the NEXT token, not merely present later
55                    // on the line.
56                    if t.trim_start_matches([' ', '\t']).starts_with("behind") {
57                        return Some((ahead, behind));
58                    }
59                }
60            }
61            rest = tail;
62        }
63    }
64    None
65}
66
67/// `behind[[:space:]]+N` over `git status -sb`, present or not — UNLIKE
68/// [`divergence`], which only answers when `ahead` is ALSO on the line.
69///
70/// `git status -sb` prints a bare `[behind M]` (no `ahead` at all) when the
71/// branch has nothing of its own to push yet is missing upstream commits —
72/// exactly "a sync would do something", independent of whether the branch is
73/// also ahead. `divergence` cannot answer that question; it was built to
74/// answer a narrower one (are the two DIVERGED, which needs both counts).
75pub fn behind_count(status: &str) -> Option<u64> {
76    status
77        .lines()
78        .find_map(|line| count_after(line, "behind").map(|(n, _)| n))
79}
80
81/// `^[[:space:]*+]+<name>$` over `git branch` output — the indentation git
82/// always prints, plus the markers it puts in column 0.
83///
84/// `+` is not decoration: since git 2.23, a branch checked out in ANOTHER
85/// WORKTREE is printed `+ main` rather than `  main`. That is a completely
86/// ordinary state in this repository's own workflow, and without `+` in the
87/// trim set the whole default-branch advisory (step 4) silently never fired —
88/// `lists_branch` answered false for both `main` and `master`, and the function
89/// returned before reaching it.
90///
91/// The `body.len() < stripped.len()` guard STAYS, and is why `for-each-ref` is
92/// not the answer here: it is what stops a `## main...origin/main` status line
93/// matching, and `+ main` still strips two characters, so the guard costs
94/// nothing. `for-each-ref` produces undecorated lines the guard would reject.
95pub fn lists_branch(branch_list: &str, name: &str) -> bool {
96    branch_list.lines().any(|line| {
97        let stripped = line.trim_end_matches(['\r']);
98        let body = stripped.trim_start_matches([' ', '\t', '*', '+']);
99        !body.is_empty() && body.len() < stripped.len() && body == name
100    })
101}
102
103/// Left side of `git rev-list --left-right --count <a>...<b>`: how far the
104/// default branch is ahead of us.
105pub fn ahead_count(rev_list: &str) -> Option<u64> {
106    rev_list.split_whitespace().next()?.parse().ok()
107}
108
109/// Does this push publish `current`, the branch checked out here? Only then
110/// is syncing it this push's business. A push of tags, or of another branch,
111/// leaves the checkout alone: pushing a release tag from the live checkout
112/// used to rebase it onto its upstream and refuse with "push again".
113/// No push lines at all (a hand-run hook) keeps the old behaviour.
114pub fn publishes_branch(push: &[crate::pushrefs::PushRef], current: &str) -> bool {
115    let own = format!("refs/heads/{current}");
116    push.is_empty() || push.iter().any(|r| r.local_ref == own)
117}
118
119pub fn run(
120    settings: &crate::config::Settings,
121    push: &[crate::pushrefs::PushRef],
122    _args: &[std::ffi::OsString],
123) -> Outcome {
124    // 1. Never auto-rebase a dirty tree: that autostashes real work and can
125    //    leave a broken mid-rebase state during a push.
126    if !git::stdout(&["status", "--porcelain"])
127        .unwrap_or_default()
128        .is_empty()
129    {
130        crate::say!(
131            "{} Uncommitted changes — skipping pre-push pull-rebase.",
132            warning_sign()
133        );
134        return Outcome::Passed;
135    }
136
137    // 2. Only sync a branch that HAS an upstream, and rebase onto that — never
138    //    the default branch. A brand-new branch has nothing to sync.
139    let Some(upstream) =
140        git::stdout(&["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"])
141    else {
142        return Outcome::Passed;
143    };
144
145    // 2a. The upstream has to be a REAL remote, not merely something with a
146    //     `/` in its name. `branch.<name>.remote` is what `git pull`/`fetch`
147    //     itself reads to resolve `@{u}` — asking IT, rather than guessing
148    //     the remote by splitting `upstream` on '/' and falling back to
149    //     "origin", is the fix for a real incident: `git worktree add -b x
150    //     <path> main` sets the new branch's upstream to the LOCAL branch
151    //     `main` (no slash at all — `@{u}` prints bare `main`), the old
152    //     fallback silently read that as `origin/main`, and the bare
153    //     `git pull --rebase` two steps down synced from LOCAL main — not
154    //     origin — while every check and message around it talked about
155    //     origin. Move `main` in the meantime (a `git reset --hard` on it in
156    //     another worktree, say) and the next push silently rebases onto
157    //     wherever it ended up, no divergence check catching it because the
158    //     hand-rolled remote guess was never asking the real question.
159    let Some(current) = git::stdout(&["symbolic-ref", "--short", "HEAD"]) else {
160        return Outcome::Passed; // detached HEAD: nothing to sync
161    };
162    if !publishes_branch(push, &current) {
163        return Outcome::Passed;
164    }
165    let remote =
166        git::stdout(&["config", "--get", &format!("branch.{current}.remote")]).unwrap_or_default();
167    let is_a_real_remote = !remote.is_empty()
168        && git::stdout(&["remote"])
169            .unwrap_or_default()
170            .lines()
171            .any(|r| r == remote);
172    if !is_a_real_remote {
173        crate::say!(
174            "{} {upstream} is not a remote-tracking branch — skipping sync.",
175            warning_sign()
176        );
177        return Outcome::Passed;
178    }
179    let branch = upstream
180        .strip_prefix(&format!("{remote}/"))
181        .unwrap_or(&upstream);
182
183    // Whether this check may MUTATE and use the NETWORK. Off, it becomes a
184    // pure advisor over your last fetch: no ls-remote round-trip per push, no
185    // rebase you did not type — the shape a check is expected to have. On (the
186    // default, and the behaviour every install so far has had), it syncs a
187    // behind branch for you and then asks for a second push.
188    let auto = crate::config::boolean_or(settings, "greengate.autoRebase", true);
189
190    // 2b. The upstream can be configured locally but GONE on the remote — the
191    //     normal state right after a PR squash-merges with delete-on-merge.
192    //     `git pull --rebase` would fail on the missing ref and read as a
193    //     conflict, wrongly blocking the push. Only asked when a rebase may
194    //     actually happen: it is this check's per-push network round-trip.
195    if auto {
196        // Bounded, and the exit codes kept apart: `--exit-code` exits 2 for
197        // "connected, the ref is gone" and 128 for "could not connect", and
198        // this used to read both as the first — offline was reported as
199        // "upstream deleted", which is a diagnosis someone acts on.
200        let budget = super::common::network_probe_budget(settings);
201        match git::probe(
202            &["ls-remote", "--exit-code", "--heads", &remote, branch],
203            budget,
204        ) {
205            git::Probe::Exit(0) => {} // upstream exists — carry on to the sync
206            git::Probe::Exit(2) => {
207                crate::say!(
208                    "{} Upstream {upstream} no longer exists on the remote (merged + auto-deleted?) — skipping sync.", warning_sign()
209                );
210                return Outcome::Passed;
211            }
212            git::Probe::Exit(_) | git::Probe::Failed => {
213                crate::say!(
214                    "{} Could not reach {remote} (offline?) — skipping sync.",
215                    warning_sign()
216                );
217                return Outcome::Passed;
218            }
219            git::Probe::TimedOut(secs) => {
220                crate::say!(
221                    "{} {remote} did not answer within {secs}s — skipping sync.",
222                    warning_sign()
223                );
224                return Outcome::Passed;
225            }
226        }
227    }
228
229    // 3. Diverged → warn and DO NOT rebase, but carry on to the default-branch
230    //    check below (the shell fell through here too).
231    let status = git::stdout(&["status", "-sb"]).unwrap_or_default();
232    if let Some((ahead, behind)) = divergence(&status) {
233        // Divergence has two causes and they want OPPOSITE actions, so this
234        // says what it saw and lets you pick. The old copy prescribed
235        // `git pull --rebase` unconditionally, which after a local rebase or
236        // amend is the one command that undoes the work you are pushing — it
237        // replays the upstream commits you just rewrote.
238        //
239        // The hook cannot tell the two apart: git does not tell a pre-push hook
240        // whether `--force` was passed, and both cases are non-fast-forward.
241        // Guessing wrong here costs someone their rebase, so it does not guess.
242        crate::say!(
243            "{} Branch and upstream have diverged ({ahead} ahead, {behind} behind) — not auto-rebasing.",
244            warning_sign()
245        );
246        crate::say!(
247            "    Rebased or amended locally? That is expected — push with {}.",
248            highlight("git push --force-with-lease")
249        );
250        crate::say!(
251            "    Someone else pushed here? Reconcile first with {} (or {}).",
252            highlight("git pull --rebase"),
253            highlight("git merge")
254        );
255    } else if behind_count(&status).unwrap_or(0) > 0 {
256        if !auto {
257            // Advisory, then STOP — before the test suite spends minutes on a
258            // push the server will refuse as non-fast-forward anyway. Judged
259            // from the local tracking ref (the last fetch): with auto off
260            // this check does no network I/O at all.
261            crate::say!(
262                "{} Behind {upstream} — not auto-rebasing ({} is off).",
263                warning_sign(),
264                highlight("greengate.autoRebase")
265            );
266            crate::say!("    Sync first: {}", highlight("git pull --rebase"));
267            return Outcome::Failed;
268        }
269        // `behind_count > 0` gates the attempt itself, not just its outcome:
270        // with nothing behind, the upstream has no commits to reconcile with,
271        // so `pull --rebase` has nothing to do BY DEFINITION — and attempting
272        // it anyway is not merely wasted work, it is a real subprocess rebase
273        // that can choke on the local branch's own history for a
274        // reconciliation nothing needed. A branch carrying a merge commit
275        // (recording a hand-resolved reconciliation with a THIRD branch, say)
276        // is exactly such a shape: `pull --rebase` tries to linearize it by
277        // full reachability rather than first-parent, replays commits that
278        // were already incorporated, and fails loudly over a push that was a
279        // clean fast-forward all along.
280        //
281        // Explicit remote and branch, not a bare `pull --rebase` trusting
282        // ambient `branch.*.remote`/`.merge` — `remote`/`branch` are already
283        // the verified pair from 2a/2b, and repeating them here means this
284        // sync can never again silently use something other than what was
285        // just checked.
286        // Under the full `greengate.timeout` deadline — this is real work (a
287        // fetch plus a rebase), not a probe, but it is still a network verb
288        // and a hung fetch used to hold the push hostage with no clock
289        // anywhere. The probe above only proved the remote ANSWERS; it says
290        // nothing about how the transfer goes.
291        match git::probe(
292            &["pull", "--rebase", &remote, branch],
293            super::common::check_timeout(settings),
294        ) {
295            git::Probe::Exit(0) => {
296                // HEAD moved; the oids git handed THIS push on stdin have
297                // not. Carrying on would run the suite against packages
298                // selected from commits git is no longer pushing, and the
299                // server refuses the stale objects as non-fast-forward
300                // regardless. Fail fast, with the good news first.
301                crate::say!(
302                    "{} Rebased onto {upstream}. This push's refs predate the rebase — {PUSH_AGAIN}.",
303                    warning_sign()
304                );
305                return Outcome::Failed;
306            }
307            git::Probe::TimedOut(secs) => {
308                // Abort so the tree is never left half-rebased.
309                let _ = git::succeeds(&["rebase", "--abort"]);
310                crate::say!(
311                    "{} pull --rebase did not finish within {secs}s (rebase aborted, tree restored).",
312                    error_sign()
313                );
314                crate::say!("    Sync manually: {}", highlight("git pull --rebase"));
315                return Outcome::Failed;
316            }
317            git::Probe::Exit(_) | git::Probe::Failed => {
318                // Abort so the tree is never left half-rebased.
319                let _ = git::succeeds(&["rebase", "--abort"]);
320                crate::say!(
321                    "{} pull --rebase hit conflicts (rebase aborted, tree restored).",
322                    error_sign()
323                );
324                crate::say!("    Resolve manually: {}", highlight("git pull --rebase"));
325                return Outcome::Failed;
326            }
327        }
328    } else {
329        super::common::ok(settings, "Branch is in sync with its upstream");
330    }
331
332    // 4. Informational only — never acts.
333    // UNTRIMMED, and that is not a detail. `git::stdout` trims the whole
334    // buffer, which strips the two leading spaces off the FIRST line — so when
335    // `git branch` happened to list the default branch first, `lists_branch`'s
336    // decoration guard rejected it and the advisory below never fired. Whether
337    // it fired depended on the alphabetical position of the branch you were on,
338    // which is why it looked intermittent rather than broken.
339    let branch_list = git::stdout_raw(&["branch"])
340        .map(|out| String::from_utf8_lossy(&out).into_owned())
341        .unwrap_or_default();
342    let default_branch = if lists_branch(&branch_list, "main") {
343        "main"
344    } else if lists_branch(&branch_list, "master") {
345        "master"
346    } else {
347        return Outcome::Passed;
348    };
349
350    // `remote`, not a hardcoded "origin". Step 2 above spends thirteen lines of
351    // comment establishing `remote` as the VERIFIED one for this branch, and
352    // then this step ignored it: in a repository whose remote is `upstream`,
353    // the fetch failed (ignored) and `rev-list origin/<branch>...HEAD` returned
354    // None, so the advisory was silently skipped.
355    // The advisory's fetch is the other network round-trip; with auto off it
356    // reads the last fetch's refs instead — stale is fine for an advisory.
357    if auto {
358        let _ = git::succeeds(&["fetch", &remote, default_branch]);
359    }
360    let range = format!("{remote}/{default_branch}...HEAD");
361    if let Some(n) =
362        git::stdout(&["rev-list", "--left-right", "--count", &range]).and_then(|s| ahead_count(&s))
363    {
364        if n > 0 {
365            // The shell took `head -c 1` of this count — the FIRST CHARACTER —
366            // so 12 commits ahead printed "1". The test was only ever
367            // non-zero/zero, so the wrong number went unnoticed. Parsed properly
368            // here.
369            crate::say!(
370                "{} {remote}/{default_branch} is ahead by {n} commit(s).",
371                warning_sign()
372            );
373            crate::say!(
374                "    Consider before merging: {}",
375                highlight(&format!("git merge {remote}/{default_branch}"))
376            );
377        }
378    }
379    Outcome::Passed
380}
381
382#[cfg(test)]
383mod tests {
384    use super::{ahead_count, behind_count, divergence, lists_branch, publishes_branch};
385    use crate::pushrefs::PushRef;
386
387    fn line(local_ref: &str) -> PushRef {
388        PushRef {
389            local_ref: local_ref.into(),
390            local_oid: "a".repeat(40),
391            remote_ref: local_ref.into(),
392            remote_oid: "0".repeat(40),
393        }
394    }
395
396    /// The incident: pushing `v1.55.1` from the live checkout on `main`
397    /// rebased `main` and refused the tag with "push again".
398    #[test]
399    fn only_a_push_of_the_checked_out_branch_syncs_it() {
400        assert!(publishes_branch(&[line("refs/heads/main")], "main"));
401        assert!(!publishes_branch(&[line("refs/tags/v1.55.1")], "main"));
402        assert!(!publishes_branch(&[line("refs/heads/other")], "main"));
403        assert!(publishes_branch(
404            &[line("refs/tags/v1"), line("refs/heads/main")],
405            "main"
406        ));
407        assert!(
408            publishes_branch(&[], "main"),
409            "a hand-run hook keeps syncing"
410        );
411    }
412
413    #[test]
414    fn detects_divergence_only_when_both_counts_are_present() {
415        assert!(divergence("## feat/x...origin/feat/x [ahead 1, behind 2]").is_some());
416        assert!(divergence("## a...b [ahead 12,  behind 3]").is_some());
417        // ahead only, or behind only, is NOT divergence — a rebase is fine
418        assert!(divergence("## feat/x...origin/feat/x [ahead 3]").is_none());
419        assert!(divergence("## feat/x...origin/feat/x [behind 2]").is_none());
420        assert!(divergence("## feat/x...origin/feat/x").is_none());
421        assert!(divergence("## ahead-of-time...origin/x").is_none());
422    }
423
424    /// The counts are the message now, so a wrong one is a wrong message.
425    /// Two digits especially: this file already carries a bug where a count of
426    /// 12 printed as 1.
427    #[test]
428    fn reports_how_far_apart_the_two_are() {
429        assert_eq!(
430            divergence("## feat/x...origin/feat/x [ahead 1, behind 2]"),
431            Some((1, 2))
432        );
433        assert_eq!(
434            divergence("## a...b [ahead 12,  behind 34]"),
435            Some((12, 34))
436        );
437    }
438
439    /// A branch legitimately named `ahead-of-behind` must not be parsed as a
440    /// pair of counts, and `behind` has to be the token straight after the
441    /// comma rather than merely somewhere on the line.
442    #[test]
443    fn branch_names_are_not_mistaken_for_counts() {
444        assert!(divergence("## ahead 3...origin/behind 4").is_none());
445        // The word has to be followed by a SPACE, so a branch whose name runs
446        // straight into digits is not read as a count.
447        assert!(divergence("## a...b [ahead3, behind4]").is_none());
448        assert!(divergence("## ahead12...origin/behind34").is_none());
449        assert!(divergence("## a...b [ahead 3, xbehind 4]").is_none());
450        assert!(divergence("## ahead-of/behind...origin/ahead-of/behind").is_none());
451    }
452
453    /// `git branch` puts a marker in column 0, and there are TWO of them.
454    ///
455    /// `*` is the current branch; `+` — since git 2.23 — is a branch checked
456    /// out in ANOTHER WORKTREE. That second one is an entirely ordinary state
457    /// in this repository's own workflow, and without it in the trim set the
458    /// whole default-branch advisory silently never fired: `lists_branch`
459    /// answered false for `main` and for `master`, and `run` returned before
460    /// reaching step 4.
461    #[test]
462    fn recognises_git_branch_lines() {
463        let list = "  feat/x\n* main\n  master-ish\n";
464        assert!(lists_branch(list, "main"));
465        assert!(!lists_branch(list, "master")); // master-ish is a different branch
466        assert!(!lists_branch(list, "feat")); // must match the whole name
467        assert!(lists_branch(list, "feat/x"));
468
469        // The worktree marker.
470        let elsewhere = "+ main\n* feat/x\n";
471        assert!(
472            lists_branch(elsewhere, "main"),
473            "a branch checked out in another worktree is still a branch"
474        );
475
476        // The decoration guard is DELIBERATE, not incidental: an undecorated
477        // line is not `git branch` output, and this is what stops a
478        // `## main...origin/main` status line matching. It is also why this
479        // cannot be switched to `for-each-ref`, whose lines carry no marker.
480        assert!(!lists_branch("main\n", "main"));
481        assert!(!lists_branch("## main...origin/main\n", "main"));
482
483        // …which is why `run` must NOT read `git branch` through
484        // `git::stdout`: that trims the whole buffer, eating the FIRST line's
485        // indentation. When git listed the default branch first, this is
486        // exactly the input the guard was handed, and the advisory silently
487        // never fired.
488        assert!(!lists_branch("main\n* feat/x\n", "main"));
489        assert!(lists_branch("  main\n* feat/x\n", "main"));
490    }
491
492    /// A count of 12 must read as 12, not 1 — the shell's `head -c 1`.
493    #[test]
494    fn parses_the_full_ahead_count() {
495        assert_eq!(ahead_count("12\t3"), Some(12));
496        assert_eq!(ahead_count("0\t5"), Some(0));
497        assert_eq!(ahead_count(""), None);
498    }
499
500    /// The whole point: `behind_count`, unlike `divergence`, answers even
501    /// when `ahead` is not on the line at all.
502    #[test]
503    fn behind_count_does_not_require_ahead() {
504        assert_eq!(
505            behind_count("## feat/x...origin/feat/x [behind 2]"),
506            Some(2)
507        );
508        assert_eq!(
509            behind_count("## feat/x...origin/feat/x [ahead 1, behind 2]"),
510            Some(2)
511        );
512    }
513
514    /// Ahead-only, or fully in sync, is "nothing behind" — the shape that
515    /// means a sync has nothing to reconcile.
516    #[test]
517    fn behind_count_is_none_when_there_is_nothing_behind() {
518        assert_eq!(behind_count("## feat/x...origin/feat/x [ahead 3]"), None);
519        assert_eq!(behind_count("## feat/x...origin/feat/x"), None);
520        assert_eq!(behind_count(""), None);
521    }
522
523    /// The same false-positive guard `divergence` has: a branch merely
524    /// NAMED with "behind" in it, glued to non-whitespace, is not a count.
525    #[test]
526    fn behind_count_is_not_fooled_by_a_branch_name() {
527        assert!(behind_count("## my-behind-thing...origin/my-behind-thing").is_none());
528        assert!(behind_count("## a...b [behind4]").is_none());
529    }
530}