//! Splits a commit subject into typed clause groups (`✨ feat: a; 🐛 fix: b`). //! //! Clauses are separated by `;` followed by whitespace or the end, except inside backticks. //! A clause that starts with a known type (after an optional emoji or `:shortcode:`) opens or //! extends that type's group. Other clauses join the most recent group. //! //! Pure string handling, no rendering. Subjects that do not start with a known type are `None`. /// Commit types recognised at the start of a clause. const KINDS: &[&str] = &[ "feat", "fix", "style", "ci", "perf", "harden", "refactor", "test", "docs", "ui", "ux", "i18n", "lint", "deps", "db", "chore", "build", "revert", ]; /// The clauses of one commit type, in the order they appear in the subject. #[derive(Debug, Clone, PartialEq, Eq)] pub struct ClauseGroup { pub kind: String, pub clauses: Vec, } /// A parsed commit subject, with one group per type in order of first appearance. #[derive(Debug, Clone, PartialEq, Eq)] pub struct CommitMessage { pub groups: Vec, } impl CommitMessage { /// None unless the subject starts with a known type; such subjects render as today. pub fn parse(subject: &str) -> Option { let mut groups: Vec = Vec::new(); let mut seen_first = false; for segment in split_clauses(subject) { let clause = segment.trim(); let clause = clause.strip_suffix('.').unwrap_or(clause); if clause.is_empty() { continue; } let typed = split_type(clause); if !seen_first { seen_first = true; if typed.is_none() { return None; } } match typed { Some((kind, text)) => { if text.is_empty() { continue; } let index = match groups.iter().position(|group| group.kind == kind) { Some(index) => index, None => { groups.push(ClauseGroup { kind: kind.to_string(), clauses: Vec::new(), }); groups.len() - 1 } }; groups[index].clauses.push(text.to_string()); } None => { if let Some(group) = groups.last_mut() { group.clauses.push(clause.to_string()); } } } } if groups.is_empty() { return None; } Some(Self { groups }) } /// The first clause, with its first letter uppercased when it is a lowercase letter. pub fn title(&self) -> String { let first = self .groups .first() .and_then(|group| group.clauses.first()) .map_or("", String::as_str); let mut chars = first.chars(); match chars.next() { Some(c) if c.is_lowercase() => c.to_uppercase().chain(chars).collect(), _ => first.to_string(), } } /// The number of clauses after the first. pub fn extra(&self) -> usize { self.groups .iter() .map(|group| group.clauses.len()) .sum::() .saturating_sub(1) } } /// Splits at `;` followed by whitespace or the end, outside backticks. fn split_clauses(subject: &str) -> Vec<&str> { let mut out = Vec::new(); let mut start = 0; let mut in_ticks = false; let mut chars = subject.char_indices().peekable(); while let Some((i, c)) = chars.next() { match c { '`' => in_ticks = !in_ticks, ';' if !in_ticks && chars.peek().is_none_or(|&(_, next)| next.is_whitespace()) => { out.push(&subject[start..i]); start = i + 1; } _ => {} } } out.push(&subject[start..]); out } /// Drops an optional leading `:shortcode:` or emoji (a non-alphanumeric run followed by a space). fn strip_marker(clause: &str) -> &str { if let Some(rest) = clause.strip_prefix(':') { if let Some(end) = rest.find(':') { let name = &rest[..end]; let valid = !name.is_empty() && name .bytes() .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b"_+-".contains(&b)); if valid && let Some(after) = rest[end + 1..].strip_prefix(' ') { return after.trim_start(); } } return clause; } if let Some(space) = clause.find(' ') { let prefix = &clause[..space]; if !prefix.is_empty() && prefix.chars().all(|c| !c.is_alphanumeric()) { return clause[space + 1..].trim_start(); } } clause } /// The known type and the clause text, for `type: text`, `type(scope): text` or `type!: text`. fn split_type(clause: &str) -> Option<(&'static str, &str)> { let rest = strip_marker(clause); let word_len = rest.bytes().take_while(u8::is_ascii_lowercase).count(); let kind = KINDS .iter() .copied() .find(|kind| *kind == &rest[..word_len])?; let mut tail = &rest[word_len..]; if let Some(after) = tail.strip_prefix('(') { let close = after.find(')')?; tail = &after[close + 1..]; } tail = tail.strip_prefix('!').unwrap_or(tail); let text = tail.strip_prefix(':')?; if !text.is_empty() && !text.starts_with(' ') { return None; } Some((kind, text.trim())) } #[cfg(test)] mod tests { use super::*; #[test] fn commit_message_splits_multi_group_subject() { let message = CommitMessage::parse( "✨ feat: the tab bar is built from lists, so X; Explore moves to a link; \ 💄 style: pages fit the window; an overview is redesigned; 🐛 fix: the bell opens once", ) .expect("typed subject"); assert_eq!(message.extra(), 4); assert_eq!(message.title(), "The tab bar is built from lists, so X"); let kinds: Vec<&str> = message.groups.iter().map(|g| g.kind.as_str()).collect(); assert_eq!(kinds, ["feat", "style", "fix"]); assert_eq!(message.groups[0].clauses.len(), 2); } #[test] fn commit_message_plain_subject_is_none() { assert_eq!(CommitMessage::parse("Update the readme"), None); } #[test] fn commit_message_keeps_semicolon_in_backticks() { let message = CommitMessage::parse("🐛 fix: keep `a; b` as one clause; ✨ feat: x") .expect("typed subject"); assert_eq!(message.groups[0].kind, "fix"); assert_eq!(message.groups[0].clauses[0], "keep `a; b` as one clause"); } #[test] fn commit_message_knows_chore_build_revert() { for subject in ["chore: a", "build(ci): b", "revert: c"] { assert!(CommitMessage::parse(subject).is_some(), "{subject}"); } } #[test] fn commit_message_repeated_kind_merges() { let message = CommitMessage::parse("✨ feat: a; fix: b; feat: c.").expect("typed subject"); assert_eq!(message.groups.len(), 2); assert_eq!(message.groups[0].clauses, ["a", "c"]); assert_eq!(message.groups[1].clauses, ["b"]); } }