forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.09.3 MiBe910f7eTahinli1 hour ago361 commits

trailers.rs103 lines, 2.9 KiBHistoryRawDownload
1use std::collections::HashSet;
2
3const KEY: &str = "Co-authored-by";
4
5#[derive(Clone, Debug, PartialEq, Eq)]
6pub struct CoAuthor {
7 pub name: String,
8 pub email: String,
9}
10
11pub fn co_authors(message: &str) -> Vec<CoAuthor> {
12 let lines = lines(message);
13 let mut seen = HashSet::new();
14 lines[last_paragraph_start(&lines)..]
15 .iter()
16 .filter_map(|line| parse(line))
17 .filter(|author| seen.insert(author.email.to_lowercase()))
18 .collect()
19}
20
21pub fn strip_co_authors(message: &str) -> String {
22 let lines = lines(message);
23 let (head, tail) = lines.split_at(last_paragraph_start(&lines));
24 let kept: Vec<&str> = head
25 .iter()
26 .copied()
27 .chain(
28 tail.iter()
29 .copied()
30 .filter(|line| trailer_value(line).is_none()),
31 )
32 .collect();
33 kept.join("\n").trim_end().to_owned()
34}
35
36fn lines(message: &str) -> Vec<&str> {
37 message.trim_end().lines().collect()
38}
39
40fn last_paragraph_start(lines: &[&str]) -> usize {
41 lines
42 .iter()
43 .rposition(|line| line.trim().is_empty())
44 .map_or(0, |i| i + 1)
45}
46
47fn trailer_value(line: &str) -> Option<&str> {
48 let (key, value) = line.split_once(':')?;
49 key.trim().eq_ignore_ascii_case(KEY).then_some(value)
50}
51
52fn parse(line: &str) -> Option<CoAuthor> {
53 let value = trailer_value(line.trim())?.trim();
54 let open = value.find('<')?;
55 let close = open + value[open..].find('>')?;
56 let email = value[open + 1..close].trim();
57 if email.is_empty() {
58 return None;
59 }
60 let name = value[..open].trim();
61 Some(CoAuthor {
62 name: if name.is_empty() { email } else { name }.to_owned(),
63 email: email.to_owned(),
64 })
65}
66
67#[cfg(test)]
68mod tests {
69 use super::*;
70
71 #[test]
72 fn co_authors_from_the_trailer_block_only() {
73 let msg = "Co-authored-by: Old <old@x.io>\n\nSubject\n\nBody\n\n\
74 co-authored-by: Ann <ANN@x.io>\n\
75 CO-AUTHORED-BY: Bob <bob@x.io> \n\
76 Co-authored-by: Ann Again <ann@x.io>\n\
77 Co-authored-by: No Email\n\
78 Co-authored-by: Empty <>\n";
79 let got = co_authors(msg);
80 assert_eq!(
81 got,
82 vec![
83 CoAuthor {
84 name: "Ann".into(),
85 email: "ANN@x.io".into()
86 },
87 CoAuthor {
88 name: "Bob".into(),
89 email: "bob@x.io".into()
90 },
91 ]
92 );
93 }
94
95 #[test]
96 fn strip_removes_trailers_in_last_paragraph() {
97 let msg = "Subject\n\nCo-authored-by: Mid <mid@x.io>\nKept\n\nSigned-off-by: Me\nCo-authored-by: Ann <ann@x.io>\n\n\n";
98 assert_eq!(
99 strip_co_authors(msg),
100 "Subject\n\nCo-authored-by: Mid <mid@x.io>\nKept\n\nSigned-off-by: Me"
101 );
102 }
103}