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        println!(
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    println!(
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        println!(
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    // `None` here means git failed, which is NOT the same as "no branches" —
174    // treat only a successful, empty listing as the initial-push case.
175    if git::stdout(&["ls-remote", "--heads", remote]).is_some_and(|s| s.is_empty()) {
176        println!(
177            "{} Remote has no branches yet (initial push). Name is authorized.",
178            valid_sign()
179        );
180        return Outcome::Passed;
181    }
182
183    // Per offending ref, so a multi-ref push names them all rather than
184    // stopping at the first.
185    let offenders: Vec<&str> = candidates
186        .iter()
187        .copied()
188        .filter(|name| !conforms(name))
189        .collect();
190    if !offenders.is_empty() {
191        for name in &offenders {
192            println!(
193                "{} Branch name {} does not adhere to this project's contract:
194    {}.
195    Rename your branch with: {} <branch name>
196    Or bypass this check with git -c hook.skip=branch-pattern push",
197                error_sign(),
198                highlight(name),
199                highlight(&vocabulary::branch_contract()),
200                highlight("git branch -m")
201            );
202        }
203        return Outcome::Failed;
204    }
205
206    println!(
207        "{} Branch name conforms with authorized pattern",
208        valid_sign()
209    );
210    Outcome::Passed
211}
212
213#[cfg(test)]
214mod tests {
215    use super::{conforms, name_to_validate, run, Outcome, PushRef};
216
217    const ZERO: &str = "0000000000000000000000000000000000000000";
218
219    fn r(local_oid: &str, remote_ref: &str, remote_oid: &str) -> PushRef {
220        PushRef {
221            local_ref: "refs/heads/whatever-is-checked-out".into(),
222            local_oid: local_oid.into(),
223            remote_ref: remote_ref.into(),
224            remote_oid: remote_oid.into(),
225        }
226    }
227
228    /// The table `branch_protect`'s tests are built from, applied to the
229    /// question this check actually has to answer.
230    ///
231    /// `name_to_validate` rather than `run`, because `run`'s remaining branches
232    /// consult `ls-remote` and a unit test must not reach a network.
233    #[test]
234    fn only_a_new_branch_ref_carries_a_name_to_validate() {
235        // Judged on the REMOTE ref, not on whatever is checked out.
236        // `git push origin local:refs/heads/other` creates `other`.
237        assert_eq!(
238            name_to_validate(&r("a", "refs/heads/feat/x", ZERO), ZERO),
239            Some("feat/x")
240        );
241        // Already on the server: git has told us so with a non-zero remote
242        // oid, and the name was authorised the day it was created.
243        assert_eq!(
244            name_to_validate(&r("a", "refs/heads/off-pattern", "b"), ZERO),
245            None
246        );
247        // A delete pushes no name.
248        assert_eq!(
249            name_to_validate(&r(ZERO, "refs/heads/off", ZERO), ZERO),
250            None
251        );
252        // A tag is not a branch, and neither is anything else outside
253        // `refs/heads/`.
254        assert_eq!(
255            name_to_validate(&r("a", "refs/tags/v1.0", ZERO), ZERO),
256            None
257        );
258        assert_eq!(
259            name_to_validate(&r("a", "refs/notes/commits", ZERO), ZERO),
260            None
261        );
262    }
263
264    /// Matches `branch_protect::no_refs_is_a_pass`, and reaches no git at all.
265    #[test]
266    fn no_refs_is_a_pass() {
267        assert_eq!(run(&[], &[]), Outcome::Passed);
268    }
269
270    #[test]
271    fn accepts_every_declared_prefix() {
272        for p in crate::vocabulary::BRANCH_PREFIXES {
273            assert!(conforms(&format!("{}/some-work", p.name)), "{}", p.name);
274        }
275    }
276
277    /// The divergence this module exists to end: these were all REJECTED as
278    /// branch names while being perfectly valid commit types.
279    #[test]
280    fn accepts_the_prefixes_that_used_to_be_rejected() {
281        for b in [
282            "docs/rust-migration",
283            "refactor/hook-registry",
284            "perf/faster-startup",
285            "build/bump-toolchain",
286            "style/reformat",
287            "revert/bad-change",
288            "add/new-thing",
289            "remove/dead-code",
290        ] {
291            assert!(conforms(b), "{b} should be allowed now");
292        }
293    }
294
295    #[test]
296    fn rejects_everything_else() {
297        assert!(!conforms("off-pattern"));
298        assert!(!conforms("duro-1.50.50"));
299        assert!(!conforms("feat/"));
300        assert!(!conforms("/x"));
301        assert!(!conforms("feat/a/b"));
302        assert!(!conforms("main"));
303        assert!(!conforms("release/1")); // not a declared prefix
304    }
305
306    /// Dots stay a chore-only affordance for version bumps.
307    #[test]
308    fn dots_are_chore_only() {
309        assert!(conforms("chore/duro-1.50.50"));
310        assert!(!conforms("feat/duro-1.50.50"));
311        assert!(!conforms("docs/1.2.3"));
312    }
313
314    /// `[[:alnum:]]` is ASCII under the C locale in both engines the shell
315    /// version used; a Unicode-aware check would LOOSEN the rule.
316    #[test]
317    fn alnum_stays_ascii() {
318        assert!(!conforms("feat/café"));
319        assert!(!conforms("chore/日本語"));
320    }
321}