Skip to main content

greengate_runtime/
vocabulary.rs

1//! The project's vocabulary: commit types and branch prefixes, in one place.
2//!
3//! These were two hand-maintained lists in two hooks, and they drifted badly —
4//! 8 of 12 commit types were REJECTED as branch prefixes, so `docs/…` and
5//! `refactor/…` could not be pushed even though `docs:` and `refactor:` were
6//! valid commit types. It cost two branch renames before anyone looked.
7//!
8//! Syncing them once would not hold: the next type added drifts again. So the
9//! lists live here, each derived view reads from them, and the reconciliation
10//! test below FAILS unless every name is either shared or explicitly declared
11//! as an exception WITH A REASON. Adding a type now forces the decision rather
12//! than deferring it to whoever next hits a rejected push.
13
14/// A conventional-commit type and the gitmoji `commit-msg` prepends.
15pub struct CommitType {
16    pub name: &'static str,
17    pub emoji: &'static str,
18}
19
20/// Order is user-visible: `commit-msg` lists these when it rejects a message.
21pub const COMMIT_TYPES: &[CommitType] = &[
22    CommitType {
23        name: "build",
24        emoji: "👷",
25    },
26    CommitType {
27        name: "chore",
28        emoji: "🔧",
29    },
30    CommitType {
31        name: "docs",
32        emoji: "📝️",
33    },
34    CommitType {
35        name: "feat",
36        emoji: "✨",
37    },
38    CommitType {
39        name: "fix",
40        emoji: "🐛",
41    },
42    CommitType {
43        name: "perf",
44        emoji: "⚡️",
45    },
46    CommitType {
47        name: "refactor",
48        emoji: "♻️",
49    },
50    CommitType {
51        name: "revert",
52        emoji: "⏪️",
53    },
54    CommitType {
55        name: "style",
56        emoji: "🎨",
57    },
58    CommitType {
59        name: "test",
60        emoji: "🚨",
61    },
62    CommitType {
63        name: "add",
64        emoji: "➕",
65    },
66    CommitType {
67        name: "remove",
68        emoji: "➖",
69    },
70];
71
72/// A branch prefix, and what may follow it.
73pub struct BranchPrefix {
74    pub name: &'static str,
75    /// One more name after the first (`prog/<slug>/<id>`): a programme ticket's
76    /// branch is named by the programme and the ticket, and the programme
77    /// skill's scanner finds in-flight tickets by that shape. Every other
78    /// prefix takes a single name.
79    pub nested: bool,
80    /// Dots suit version-bump branches (`chore/duro-1.50.50`) and would only be
81    /// noise elsewhere. Git already rejects the dangerous forms (`..`, trailing
82    /// `.lock`).
83    pub dots: bool,
84}
85
86pub const BRANCH_PREFIXES: &[BranchPrefix] = &[
87    BranchPrefix {
88        name: "add",
89        dots: false,
90        nested: false,
91    },
92    BranchPrefix {
93        name: "automation",
94        dots: false,
95        nested: false,
96    },
97    BranchPrefix {
98        name: "build",
99        dots: false,
100        nested: false,
101    },
102    BranchPrefix {
103        name: "chore",
104        dots: true,
105        nested: false,
106    },
107    BranchPrefix {
108        name: "docs",
109        dots: false,
110        nested: false,
111    },
112    BranchPrefix {
113        name: "feat",
114        dots: false,
115        nested: false,
116    },
117    BranchPrefix {
118        name: "fix",
119        dots: false,
120        nested: false,
121    },
122    BranchPrefix {
123        name: "hotfix",
124        dots: false,
125        nested: false,
126    },
127    BranchPrefix {
128        name: "prog",
129        dots: false,
130        nested: true,
131    },
132    BranchPrefix {
133        name: "perf",
134        dots: false,
135        nested: false,
136    },
137    BranchPrefix {
138        name: "refactor",
139        dots: false,
140        nested: false,
141    },
142    BranchPrefix {
143        name: "remove",
144        dots: false,
145        nested: false,
146    },
147    BranchPrefix {
148        name: "revert",
149        dots: false,
150        nested: false,
151    },
152    BranchPrefix {
153        name: "style",
154        dots: false,
155        nested: false,
156    },
157    BranchPrefix {
158        name: "test",
159        dots: false,
160        nested: false,
161    },
162];
163
164/// Consumed only by the reconciliation test — that IS their job: they are the
165/// record of a decision, and the test is what forces one to exist.
166#[allow(dead_code)]
167/// Commit types deliberately NOT usable as a branch prefix, and why.
168/// Empty today — every type is a legitimate thing to open a branch for.
169pub const COMMIT_ONLY: &[(&str, &str)] = &[];
170
171#[allow(dead_code)]
172/// Branch prefixes deliberately not commit types, and why.
173pub const BRANCH_ONLY: &[(&str, &str)] = &[
174    (
175        "hotfix",
176        "an urgency, not a kind of change — the commits inside are still fix:",
177    ),
178    (
179        "automation",
180        "bot-authored branches; their commits carry their own types",
181    ),
182    (
183        "prog",
184        "a programme ticket's branch, prog/<slug>/<id>; its commits carry their own types",
185    ),
186];
187
188pub fn branch_prefix(name: &str) -> Option<&'static BranchPrefix> {
189    BRANCH_PREFIXES.iter().find(|p| p.name == name)
190}
191
192pub fn emoji_for(commit_type: &str) -> &'static str {
193    COMMIT_TYPES
194        .iter()
195        .find(|t| t.name == commit_type)
196        .map(|t| t.emoji)
197        .unwrap_or("")
198}
199
200/// The type an emoji stands for — [`emoji_for`] read backwards.
201///
202/// This is what makes the `replace` gitmoji placement survive an amend: the
203/// stored subject `✨  add a cart` carries its type only in the emoji, so
204/// re-validating it means recovering `feat` from `✨`. Well defined because
205/// `each_type_has_its_own_emoji` holds the emojis distinct.
206pub fn type_for_emoji(emoji: &str) -> Option<&'static str> {
207    COMMIT_TYPES
208        .iter()
209        .find(|t| t.emoji == emoji)
210        .map(|t| t.name)
211}
212
213/// The branch contract, rendered for the rejection message so what a user is
214/// told always matches what is enforced.
215pub fn branch_contract() -> String {
216    let names = |keep: &dyn Fn(&BranchPrefix) -> bool| -> String {
217        BRANCH_PREFIXES
218            .iter()
219            .filter(|p| keep(p))
220            .map(|p| p.name)
221            .collect::<Vec<_>>()
222            .join("|")
223    };
224    format!(
225        "^(({})/[[:alnum:]_-]+|({})/[[:alnum:]_.-]+|({})/[[:alnum:]_-]+/[[:alnum:]_-]+)$",
226        names(&|p| !p.dots && !p.nested),
227        names(&|p| p.dots),
228        names(&|p| p.nested),
229    )
230}
231
232/// The prefixes as a sentence lists them: a nested one shows its shape.
233pub fn branch_prefix_list() -> String {
234    BRANCH_PREFIXES
235        .iter()
236        .map(|p| {
237            if p.nested {
238                format!("{0} ({0}/<slug>/<id>)", p.name)
239            } else {
240                p.name.to_string()
241            }
242        })
243        .collect::<Vec<_>>()
244        .join(", ")
245}
246
247#[cfg(test)]
248mod tests {
249    use super::*;
250    use std::collections::BTreeSet;
251
252    fn names<T>(v: &[T], f: impl Fn(&T) -> &'static str) -> BTreeSet<&'static str> {
253        v.iter().map(f).collect()
254    }
255
256    /// The point of this module. Every name must be shared, or declared as an
257    /// exception with a reason — so adding a commit type forces a decision
258    /// about whether it is also a branch prefix, instead of silently producing
259    /// a rejected push months later.
260    #[test]
261    fn the_two_vocabularies_are_reconciled() {
262        let types = names(COMMIT_TYPES, |t| t.name);
263        let prefixes = names(BRANCH_PREFIXES, |p| p.name);
264        let commit_only: BTreeSet<&str> = COMMIT_ONLY.iter().map(|(n, _)| *n).collect();
265        let branch_only: BTreeSet<&str> = BRANCH_ONLY.iter().map(|(n, _)| *n).collect();
266
267        let unexplained: Vec<_> = types
268            .difference(&prefixes)
269            .filter(|n| !commit_only.contains(*n))
270            .collect();
271        assert!(
272            unexplained.is_empty(),
273            "commit types that are not branch prefixes and not listed in COMMIT_ONLY: {unexplained:?}"
274        );
275
276        let unexplained: Vec<_> = prefixes
277            .difference(&types)
278            .filter(|n| !branch_only.contains(*n))
279            .collect();
280        assert!(
281            unexplained.is_empty(),
282            "branch prefixes that are not commit types and not listed in BRANCH_ONLY: {unexplained:?}"
283        );
284
285        // An exception must be a real exception, not a stale note.
286        for n in &commit_only {
287            assert!(
288                !prefixes.contains(n),
289                "{n} is listed COMMIT_ONLY but IS a branch prefix"
290            );
291        }
292        for n in &branch_only {
293            assert!(
294                !types.contains(n),
295                "{n} is listed BRANCH_ONLY but IS a commit type"
296            );
297        }
298    }
299
300    #[test]
301    fn no_duplicates() {
302        assert_eq!(names(COMMIT_TYPES, |t| t.name).len(), COMMIT_TYPES.len());
303        assert_eq!(
304            names(BRANCH_PREFIXES, |p| p.name).len(),
305            BRANCH_PREFIXES.len()
306        );
307    }
308
309    /// Two types sharing an emoji would make [`type_for_emoji`] a coin toss,
310    /// and the `replace` gitmoji placement stores the emoji INSTEAD of the type
311    /// — so a duplicate would silently rewrite one type into another on the
312    /// next amend.
313    #[test]
314    fn each_type_has_its_own_emoji() {
315        let emojis = names(COMMIT_TYPES, |t| t.emoji);
316        assert_eq!(
317            emojis.len(),
318            COMMIT_TYPES.len(),
319            "two commit types share an emoji: {emojis:?}"
320        );
321    }
322
323    /// Every type recovers from its own emoji, and nothing else does.
324    #[test]
325    fn an_emoji_names_the_type_it_was_written_for() {
326        for t in COMMIT_TYPES {
327            assert_eq!(type_for_emoji(t.emoji), Some(t.name), "{}", t.name);
328            assert_eq!(emoji_for(t.name), t.emoji);
329        }
330        assert_eq!(type_for_emoji("🚀"), None);
331        assert_eq!(type_for_emoji(""), None);
332    }
333
334    /// Dots are a chore-only affordance for version bumps.
335    #[test]
336    fn only_chore_allows_dots() {
337        let dotted: Vec<&str> = BRANCH_PREFIXES
338            .iter()
339            .filter(|p| p.dots)
340            .map(|p| p.name)
341            .collect();
342        assert_eq!(dotted, vec!["chore"]);
343    }
344
345    /// The message a user is shown must describe what is actually enforced.
346    #[test]
347    fn the_contract_string_lists_every_prefix() {
348        let c = branch_contract();
349        for p in BRANCH_PREFIXES {
350            assert!(c.contains(p.name), "{} missing from the contract", p.name);
351        }
352    }
353}