Skip to main content

greengate_runtime/hooks/
branch_pattern.rs

1//! pre-push-branch-pattern — reject branch names that don't follow the
2//! convention, unless the branch is already on the remote.
3//!
4//! Ported from zsh. The shell version needed `rg` with a `grep` fallback and a
5//! pattern written to satisfy both engines; here the match is a dozen lines of
6//! ASCII checks, so the `rg`/`grep` split and `HOOKS_FORCE_GREP` disappear
7//! entirely — as does the failure mode that motivated them, where a missing
8//! `rg` made `! rg …` true and the hook rejected EVERY branch name.
9
10use crate::check::Outcome;
11use crate::git;
12use crate::pushrefs::PushRef;
13use crate::ui::{error_sign, highlight, warning_sign};
14
15use crate::vocabulary;
16
17/// The same contract, said at the FIRST COMMIT — `pre-commit-branch-pattern`.
18///
19/// pre-push is the enforcement point, and it is also the worst possible
20/// moment to learn the rule: the work is done and stacked on a name that now
21/// has to change, usually by an agent or a person who never saw the contract
22/// before creating the branch. This is `usual-name`'s argument applied to
23/// branch names — say it at the first commit, when the fix is one
24/// `git branch -m` and nothing is built on top.
25///
26/// A warning, never a block, and quiet in every state where the push check
27/// would not judge this branch:
28///
29///   - a DETACHED head (rebase, cherry-pick, bisect) names no branch;
30///   - a repository with no remote has nothing this contract gates;
31///   - a branch with a remote-tracking ref under any remote already exists
32///     on a server. pre-push authorises an existing branch by its non-zero
33///     remote oid; the remote-tracking ref is the local mirror of that same
34///     fact, and costs no network to consult.
35pub fn early(settings: &crate::config::Settings) -> Outcome {
36    let Some(branch) = git::current_branch() else {
37        return Outcome::Passed;
38    };
39    if conforms(branch) {
40        super::common::ok(settings, "Branch name conforms with authorized pattern");
41        return Outcome::Passed;
42    }
43    if !git::has_remote() {
44        return Outcome::Passed;
45    }
46    // `*` in a for-each-ref pattern does not cross `/`, so this matches the
47    // branch under any single remote name and nothing else.
48    let tracking = format!("refs/remotes/*/{branch}");
49    if git::stdout(&["for-each-ref", "--format=%(refname)", &tracking])
50        .is_some_and(|refs| !refs.is_empty())
51    {
52        return Outcome::Passed;
53    }
54    let prefixes = vocabulary::branch_prefix_list();
55    crate::say!(
56        "{} Branch {} will be refused at push time — it does not match
57    {}.
58    Rename it now, while nothing is stacked on the name: {} <prefix>/…
59    Prefixes: {prefixes}",
60        warning_sign(),
61        highlight(branch),
62        highlight(&vocabulary::branch_contract()),
63        highlight("git branch -m")
64    );
65    Outcome::Warned
66}
67
68/// Both the rule and the message now come from `vocabulary`, so what a user is
69/// told and what is enforced cannot drift — and neither can the branch prefixes
70/// and the commit types, which had diverged to the point that `docs/…` was
71/// unpushable while `docs:` was a valid commit type.
72///
73/// `[[:alnum:]]` is ASCII in both rg and `grep -E` under the C locale, which is
74/// what the shell version enforced; `is_ascii_alphanumeric` keeps that. A
75/// Unicode-aware check would silently LOOSEN the rule.
76pub fn conforms(branch: &str) -> bool {
77    let Some((prefix, rest)) = branch.split_once('/') else {
78        return false;
79    };
80    if rest.is_empty() {
81        return false;
82    }
83    let Some(p) = vocabulary::branch_prefix(prefix) else {
84        return false;
85    };
86    let name = |part: &str| {
87        !part.is_empty()
88            && part
89                .chars()
90                .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-' || (p.dots && c == '.'))
91    };
92    if p.nested {
93        // Exactly two names: `prog/<slug>/<id>`.
94        return rest
95            .split_once('/')
96            .is_some_and(|(a, b)| name(a) && name(b));
97    }
98    name(rest)
99}
100
101/// A delete pushes no name to validate. Same rule as `branch_protect::is_delete`
102/// — the all-zero local oid is how git spells it.
103fn is_delete(r: &PushRef) -> bool {
104    r.local_oid.chars().all(|c| c == '0')
105}
106
107/// The branch name this ref would CREATE on the server, if it creates one.
108///
109/// `None` for a delete, for anything that is not `refs/heads/` (tags, notes),
110/// and for a ref whose remote oid is non-zero — that last one means the branch
111/// already exists on the server, so its name was authorised the day it was
112/// created.
113fn name_to_validate<'a>(r: &'a PushRef, zero: &str) -> Option<&'a str> {
114    if is_delete(r) {
115        return None;
116    }
117    if r.remote_oid != zero {
118        return None;
119    }
120    r.remote_ref.strip_prefix("refs/heads/")
121}
122
123/// Judged on the REFS BEING PUSHED, not on the branch that happens to be
124/// checked out.
125///
126/// It used to ask `rev-parse --abbrev-ref HEAD`, exactly the mistake
127/// `branch_protect` documents avoiding, and it cost two things:
128///
129///   - `git push origin local:refs/heads/other` validated the wrong name
130///     entirely — the one you are standing on rather than the one being
131///     created;
132///   - on a DETACHED HEAD, `--abbrev-ref HEAD` returns the literal string
133///     `"HEAD"`, which `conforms` rejects. The `show-branch
134///     remotes/origin/HEAD` short-circuit hid that in a normal clone, but in a
135///     repository with no `refs/remotes/origin/HEAD` — a bare `git init` plus
136///     `git remote add`, or after `git remote set-head --delete` — a perfectly
137///     ordinary `git push origin HEAD:refs/heads/feat/x` was BLOCKED.
138///
139/// The `show-branch` probe is gone, replaced by the non-zero remote oid: git
140/// has already told us whether the branch exists on the server, and the probe
141/// depended on a remote-tracking ref that a fresh clone may not have.
142pub fn run(
143    settings: &crate::config::Settings,
144    refs: &[PushRef],
145    args: &[std::ffi::OsString],
146) -> Outcome {
147    // Matches `branch_protect::no_refs_is_a_pass`: nothing pushed, nothing to
148    // judge.
149    if refs.is_empty() {
150        return Outcome::Passed;
151    }
152    let zero = git::stdout(&["hash-object", "--stdin"])
153        .map(|h| "0".repeat(h.len()))
154        .unwrap_or_else(|| "0".repeat(40));
155
156    let candidates: Vec<&str> = refs
157        .iter()
158        .filter_map(|r| name_to_validate(r, &zero))
159        .collect();
160    if candidates.is_empty() {
161        super::common::ok(
162            settings,
163            "No new branch name to validate. Push is authorized.",
164        );
165        return Outcome::Passed;
166    }
167
168    // Initial push to a brand-new empty remote: there's no feature-branch
169    // convention to enforce while initializing a repo, and the default branch
170    // (main/master) doesn't match the pattern anyway. Still needed alongside
171    // the remote-oid rule above, because on a brand-new remote EVERY remote
172    // oid is zero. git passes the remote name as the first argument.
173    let remote = args
174        .first()
175        .and_then(|a| a.to_str())
176        .filter(|s| !s.is_empty())
177        .unwrap_or("origin");
178    // `--exit-code` turns the answer into exit codes — 2 for "connected,
179    // zero refs", 0 for "has branches" — so nothing here reads (or waits
180    // on) the listing itself. Bounded: this is a network round-trip asked
181    // before a purely local check, and offline used to hang it. Anything
182    // other than a clean "zero refs" answer falls through to the pattern
183    // check — git failing is NOT the same as "no branches".
184    match git::probe(
185        &["ls-remote", "--exit-code", "--heads", remote],
186        super::common::network_probe_budget(settings),
187    ) {
188        git::Probe::Exit(2) => {
189            super::common::ok(
190                settings,
191                "Remote has no branches yet (initial push). Name is authorized.",
192            );
193            return Outcome::Passed;
194        }
195        git::Probe::TimedOut(secs) => {
196            crate::say!(
197                "{} {remote} did not answer within {secs}s — checking the name anyway.",
198                warning_sign()
199            );
200        }
201        _ => {}
202    }
203
204    // Per offending ref, so a multi-ref push names them all rather than
205    // stopping at the first.
206    let offenders: Vec<&str> = candidates
207        .iter()
208        .copied()
209        .filter(|name| !conforms(name))
210        .collect();
211    if !offenders.is_empty() {
212        for name in &offenders {
213            crate::say!(
214                "{} Branch name {} does not adhere to this project's contract:
215    {}.
216    Rename your branch with: {} <branch name>
217    Or bypass this check with git -c hook.skip=branch-pattern push",
218                error_sign(),
219                highlight(name),
220                highlight(&vocabulary::branch_contract()),
221                highlight("git branch -m")
222            );
223        }
224        return Outcome::Failed;
225    }
226
227    super::common::ok(settings, "Branch name conforms with authorized pattern");
228    Outcome::Passed
229}
230
231#[cfg(test)]
232mod tests {
233    use super::{conforms, name_to_validate, run, Outcome, PushRef};
234
235    fn test_settings() -> crate::config::Settings {
236        crate::config::Settings::default()
237    }
238
239    const ZERO: &str = "0000000000000000000000000000000000000000";
240
241    fn r(local_oid: &str, remote_ref: &str, remote_oid: &str) -> PushRef {
242        PushRef {
243            local_ref: "refs/heads/whatever-is-checked-out".into(),
244            local_oid: local_oid.into(),
245            remote_ref: remote_ref.into(),
246            remote_oid: remote_oid.into(),
247        }
248    }
249
250    /// The table `branch_protect`'s tests are built from, applied to the
251    /// question this check actually has to answer.
252    ///
253    /// `name_to_validate` rather than `run`, because `run`'s remaining branches
254    /// consult `ls-remote` and a unit test must not reach a network.
255    #[test]
256    fn only_a_new_branch_ref_carries_a_name_to_validate() {
257        // Judged on the REMOTE ref, not on whatever is checked out.
258        // `git push origin local:refs/heads/other` creates `other`.
259        assert_eq!(
260            name_to_validate(&r("a", "refs/heads/feat/x", ZERO), ZERO),
261            Some("feat/x")
262        );
263        // Already on the server: git has told us so with a non-zero remote
264        // oid, and the name was authorised the day it was created.
265        assert_eq!(
266            name_to_validate(&r("a", "refs/heads/off-pattern", "b"), ZERO),
267            None
268        );
269        // A delete pushes no name.
270        assert_eq!(
271            name_to_validate(&r(ZERO, "refs/heads/off", ZERO), ZERO),
272            None
273        );
274        // A tag is not a branch, and neither is anything else outside
275        // `refs/heads/`.
276        assert_eq!(
277            name_to_validate(&r("a", "refs/tags/v1.0", ZERO), ZERO),
278            None
279        );
280        assert_eq!(
281            name_to_validate(&r("a", "refs/notes/commits", ZERO), ZERO),
282            None
283        );
284    }
285
286    /// Matches `branch_protect::no_refs_is_a_pass`, and reaches no git at all.
287    #[test]
288    fn no_refs_is_a_pass() {
289        assert_eq!(run(&test_settings(), &[], &[]), Outcome::Passed);
290    }
291
292    #[test]
293    fn accepts_every_declared_prefix() {
294        for p in crate::vocabulary::BRANCH_PREFIXES {
295            let name = if p.nested {
296                format!("{}/some-programme/t01-some-work", p.name)
297            } else {
298                format!("{}/some-work", p.name)
299            };
300            assert!(conforms(&name), "{}", p.name);
301        }
302    }
303
304    /// A programme ticket's branch has two names, and only `prog` may.
305    #[test]
306    fn prog_takes_exactly_two_names() {
307        assert!(conforms("prog/gate-guardrails/t12-grh-fleet-view"));
308        assert!(!conforms("prog/gate-guardrails"));
309        assert!(!conforms("prog/a/b/c"));
310        assert!(!conforms("prog//t12"));
311        assert!(!conforms("prog/a/"));
312        assert!(!conforms("prog/a.b/c"));
313        assert!(!conforms("feat/gate-guardrails/t12-grh-fleet-view"));
314    }
315
316    /// The divergence this module exists to end: these were all REJECTED as
317    /// branch names while being perfectly valid commit types.
318    #[test]
319    fn accepts_the_prefixes_that_used_to_be_rejected() {
320        for b in [
321            "docs/rust-migration",
322            "refactor/hook-registry",
323            "perf/faster-startup",
324            "build/bump-toolchain",
325            "style/reformat",
326            "revert/bad-change",
327            "add/new-thing",
328            "remove/dead-code",
329        ] {
330            assert!(conforms(b), "{b} should be allowed now");
331        }
332    }
333
334    #[test]
335    fn rejects_everything_else() {
336        assert!(!conforms("off-pattern"));
337        assert!(!conforms("duro-1.50.50"));
338        assert!(!conforms("feat/"));
339        assert!(!conforms("/x"));
340        assert!(!conforms("feat/a/b"));
341        assert!(!conforms("main"));
342        assert!(!conforms("release/1")); // not a declared prefix
343    }
344
345    /// Dots stay a chore-only affordance for version bumps.
346    #[test]
347    fn dots_are_chore_only() {
348        assert!(conforms("chore/duro-1.50.50"));
349        assert!(!conforms("feat/duro-1.50.50"));
350        assert!(!conforms("docs/1.2.3"));
351    }
352
353    /// `[[:alnum:]]` is ASCII under the C locale in both engines the shell
354    /// version used; a Unicode-aware check would LOOSEN the rule.
355    #[test]
356    fn alnum_stays_ascii() {
357        assert!(!conforms("feat/café"));
358        assert!(!conforms("chore/日本語"));
359    }
360}