//! `Co-authored-by:` trailers in a commit message. //! //! Trailers live in the message's last paragraph (the text after its last blank line). use std::collections::HashSet; const KEY: &str = "Co-authored-by"; #[derive(Clone, Debug, PartialEq, Eq)] pub struct CoAuthor { pub name: String, pub email: String, } /// Co-authors from the message's trailer block, in order, deduplicated by lowercase email. pub fn co_authors(message: &str) -> Vec { let lines = lines(message); let mut seen = HashSet::new(); trailer_lines(&lines) .iter() .filter_map(|line| parse(line)) .filter(|author| seen.insert(author.email.to_lowercase())) .collect() } /// The message with every `Co-authored-by:` line removed and trailing blank lines trimmed. pub fn strip_co_authors(message: &str) -> String { let lines = lines(message); let start = last_paragraph_start(&lines); let kept: Vec<&str> = lines[..start] .iter() .copied() .chain(lines[start..].iter().copied().filter(|line| !is_trailer(line))) .collect(); kept.join("\n").trim_end().to_owned() } /// The message's lines with trailing whitespace removed from the end of the whole message. fn lines(message: &str) -> Vec<&str> { message.trim_end().lines().collect() } /// Index of the first line of the last paragraph; 0 when there is no blank line. fn last_paragraph_start(lines: &[&str]) -> usize { lines .iter() .rposition(|line| line.trim().is_empty()) .map_or(0, |i| i + 1) } fn trailer_lines<'a>(lines: &[&'a str]) -> Vec<&'a str> { lines[last_paragraph_start(lines)..].to_vec() } /// Whether a line's key is `Co-authored-by`, in any letter case. fn is_trailer(line: &str) -> bool { line.split_once(':') .is_some_and(|(key, _)| key.trim().eq_ignore_ascii_case(KEY)) } /// Parses `Co-authored-by: Name `. Lines without a non-empty `` give `None`. fn parse(line: &str) -> Option { let (key, value) = line.trim().split_once(':')?; if !key.trim().eq_ignore_ascii_case(KEY) { return None; } let value = value.trim(); let open = value.find('<')?; let close = open + value[open..].find('>')?; let email = value[open + 1..close].trim(); if email.is_empty() { return None; } let name = value[..open].trim(); Some(CoAuthor { name: if name.is_empty() { email } else { name }.to_owned(), email: email.to_owned(), }) } #[cfg(test)] mod tests { use super::*; #[test] fn co_authors_from_the_trailer_block_only() { let msg = "Co-authored-by: Old \n\nSubject\n\nBody\n\n\ co-authored-by: Ann \n\ CO-AUTHORED-BY: Bob \n\ Co-authored-by: Ann Again \n\ Co-authored-by: No Email\n\ Co-authored-by: Empty <>\n"; let got = co_authors(msg); assert_eq!( got, vec![ CoAuthor { name: "Ann".into(), email: "ANN@x.io".into() }, CoAuthor { name: "Bob".into(), email: "bob@x.io".into() }, ] ); } #[test] fn strip_removes_trailers_in_last_paragraph() { let msg = "Subject\n\nCo-authored-by: Mid \nKept\n\nSigned-off-by: Me\nCo-authored-by: Ann \n\n\n"; assert_eq!( strip_co_authors(msg), "Subject\n\nCo-authored-by: Mid \nKept\n\nSigned-off-by: Me" ); } }