Skip to main content

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