forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.7 MiBe587be7Tahinli13 hours ago323 commits

commit_message.rs210 lines, 7.3 KiBHistoryRawDownload
1//! Splits a commit subject into typed clause groups (`✨ feat: a; 🐛 fix: b`).
2//!
3//! Clauses are separated by `;` followed by whitespace or the end, except inside backticks.
4//! A clause that starts with a known type (after an optional emoji or `:shortcode:`) opens or
5//! extends that type's group. Other clauses join the most recent group.
6//!
7//! Pure string handling, no rendering. Subjects that do not start with a known type are `None`.
8
9/// Commit types recognised at the start of a clause.
10const KINDS: &[&str] = &[
11 "feat", "fix", "style", "ci", "perf", "harden", "refactor", "test", "docs", "ui", "ux", "i18n",
12 "lint", "deps", "db", "chore", "build", "revert",
13];
14
15/// The clauses of one commit type, in the order they appear in the subject.
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub struct ClauseGroup {
18 pub kind: String,
19 pub clauses: Vec<String>,
20}
21
22/// A parsed commit subject, with one group per type in order of first appearance.
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub struct CommitMessage {
25 pub groups: Vec<ClauseGroup>,
26}
27
28impl CommitMessage {
29 /// None unless the subject starts with a known type; such subjects render as today.
30 pub fn parse(subject: &str) -> Option<Self> {
31 let mut groups: Vec<ClauseGroup> = Vec::new();
32 let mut seen_first = false;
33 for segment in split_clauses(subject) {
34 let clause = segment.trim();
35 let clause = clause.strip_suffix('.').unwrap_or(clause);
36 if clause.is_empty() {
37 continue;
38 }
39 let typed = split_type(clause);
40 if !seen_first {
41 seen_first = true;
42 if typed.is_none() {
43 return None;
44 }
45 }
46 match typed {
47 Some((kind, text)) => {
48 if text.is_empty() {
49 continue;
50 }
51 let index = match groups.iter().position(|group| group.kind == kind) {
52 Some(index) => index,
53 None => {
54 groups.push(ClauseGroup {
55 kind: kind.to_string(),
56 clauses: Vec::new(),
57 });
58 groups.len() - 1
59 }
60 };
61 groups[index].clauses.push(text.to_string());
62 }
63 None => {
64 if let Some(group) = groups.last_mut() {
65 group.clauses.push(clause.to_string());
66 }
67 }
68 }
69 }
70 if groups.is_empty() {
71 return None;
72 }
73 Some(Self { groups })
74 }
75
76 /// The first clause, with its first letter uppercased when it is a lowercase letter.
77 pub fn title(&self) -> String {
78 let first = self
79 .groups
80 .first()
81 .and_then(|group| group.clauses.first())
82 .map_or("", String::as_str);
83 let mut chars = first.chars();
84 match chars.next() {
85 Some(c) if c.is_lowercase() => c.to_uppercase().chain(chars).collect(),
86 _ => first.to_string(),
87 }
88 }
89
90 /// The number of clauses after the first.
91 pub fn extra(&self) -> usize {
92 self.groups
93 .iter()
94 .map(|group| group.clauses.len())
95 .sum::<usize>()
96 .saturating_sub(1)
97 }
98}
99
100/// Splits at `;` followed by whitespace or the end, outside backticks.
101fn split_clauses(subject: &str) -> Vec<&str> {
102 let mut out = Vec::new();
103 let mut start = 0;
104 let mut in_ticks = false;
105 let mut chars = subject.char_indices().peekable();
106 while let Some((i, c)) = chars.next() {
107 match c {
108 '`' => in_ticks = !in_ticks,
109 ';' if !in_ticks && chars.peek().is_none_or(|&(_, next)| next.is_whitespace()) => {
110 out.push(&subject[start..i]);
111 start = i + 1;
112 }
113 _ => {}
114 }
115 }
116 out.push(&subject[start..]);
117 out
118}
119
120/// Drops an optional leading `:shortcode:` or emoji (a non-alphanumeric run followed by a space).
121fn strip_marker(clause: &str) -> &str {
122 if let Some(rest) = clause.strip_prefix(':') {
123 if let Some(end) = rest.find(':') {
124 let name = &rest[..end];
125 let valid = !name.is_empty()
126 && name
127 .bytes()
128 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b"_+-".contains(&b));
129 if valid && let Some(after) = rest[end + 1..].strip_prefix(' ') {
130 return after.trim_start();
131 }
132 }
133 return clause;
134 }
135 if let Some(space) = clause.find(' ') {
136 let prefix = &clause[..space];
137 if !prefix.is_empty() && prefix.chars().all(|c| !c.is_alphanumeric()) {
138 return clause[space + 1..].trim_start();
139 }
140 }
141 clause
142}
143
144/// The known type and the clause text, for `type: text`, `type(scope): text` or `type!: text`.
145fn split_type(clause: &str) -> Option<(&'static str, &str)> {
146 let rest = strip_marker(clause);
147 let word_len = rest.bytes().take_while(u8::is_ascii_lowercase).count();
148 let kind = KINDS
149 .iter()
150 .copied()
151 .find(|kind| *kind == &rest[..word_len])?;
152 let mut tail = &rest[word_len..];
153 if let Some(after) = tail.strip_prefix('(') {
154 let close = after.find(')')?;
155 tail = &after[close + 1..];
156 }
157 tail = tail.strip_prefix('!').unwrap_or(tail);
158 let text = tail.strip_prefix(':')?;
159 if !text.is_empty() && !text.starts_with(' ') {
160 return None;
161 }
162 Some((kind, text.trim()))
163}
164
165#[cfg(test)]
166mod tests {
167 use super::*;
168
169 #[test]
170 fn commit_message_splits_multi_group_subject() {
171 let message = CommitMessage::parse(
172 "✨ feat: the tab bar is built from lists, so X; Explore moves to a link; \
173 💄 style: pages fit the window; an overview is redesigned; 🐛 fix: the bell opens once",
174 )
175 .expect("typed subject");
176 assert_eq!(message.extra(), 4);
177 assert_eq!(message.title(), "The tab bar is built from lists, so X");
178 let kinds: Vec<&str> = message.groups.iter().map(|g| g.kind.as_str()).collect();
179 assert_eq!(kinds, ["feat", "style", "fix"]);
180 assert_eq!(message.groups[0].clauses.len(), 2);
181 }
182
183 #[test]
184 fn commit_message_plain_subject_is_none() {
185 assert_eq!(CommitMessage::parse("Update the readme"), None);
186 }
187
188 #[test]
189 fn commit_message_keeps_semicolon_in_backticks() {
190 let message = CommitMessage::parse("🐛 fix: keep `a; b` as one clause; ✨ feat: x")
191 .expect("typed subject");
192 assert_eq!(message.groups[0].kind, "fix");
193 assert_eq!(message.groups[0].clauses[0], "keep `a; b` as one clause");
194 }
195
196 #[test]
197 fn commit_message_knows_chore_build_revert() {
198 for subject in ["chore: a", "build(ci): b", "revert: c"] {
199 assert!(CommitMessage::parse(subject).is_some(), "{subject}");
200 }
201 }
202
203 #[test]
204 fn commit_message_repeated_kind_merges() {
205 let message = CommitMessage::parse("✨ feat: a; fix: b; feat: c.").expect("typed subject");
206 assert_eq!(message.groups.len(), 2);
207 assert_eq!(message.groups[0].clauses, ["a", "c"]);
208 assert_eq!(message.groups[1].clauses, ["b"]);
209 }
210}