Skip to main content

git_editor/utils/
message_trailers.rs

1/// Rewrite author-related trailers in a commit message when identity changes.
2///
3/// Only the trailer block — the last paragraph of a message that has more
4/// than one paragraph — is considered. `Signed-off-by`, `Co-authored-by` and
5/// `Authored-by` lines there whose email matches `old_email`
6/// (case-insensitive) are rewritten; everything else, including line endings
7/// (`\n` or `\r\n`), is left byte-for-byte unchanged. Does not invent trailers.
8pub fn rewrite_author_trailers(
9    message: &str,
10    old_name: &str,
11    old_email: &str,
12    new_name: &str,
13    new_email: &str,
14) -> String {
15    if old_email == new_email && old_name == new_name {
16        return message.to_string();
17    }
18
19    let lines: Vec<&str> = message.split_inclusive('\n').collect();
20    let Some(block_start) = trailer_block_start(&lines) else {
21        return message.to_string();
22    };
23
24    let mut out = String::with_capacity(message.len());
25    for (i, line) in lines.iter().enumerate() {
26        let (content, ending) = split_line_ending(line);
27        match (i >= block_start)
28            .then(|| rewrite_trailer_line(content, old_email, new_name, new_email))
29            .flatten()
30        {
31            Some(rewritten) => {
32                out.push_str(&rewritten);
33                out.push_str(ending);
34            }
35            None => out.push_str(line),
36        }
37    }
38    out
39}
40
41fn split_line_ending(line: &str) -> (&str, &str) {
42    if let Some(content) = line.strip_suffix("\r\n") {
43        (content, "\r\n")
44    } else if let Some(content) = line.strip_suffix('\n') {
45        (content, "\n")
46    } else {
47        (line, "")
48    }
49}
50
51/// Index of the first line of the trailer block (last paragraph), if the
52/// message has a paragraph before it.
53fn trailer_block_start(lines: &[&str]) -> Option<usize> {
54    let blank = |l: &&str| split_line_ending(l).0.trim().is_empty();
55    let last_content = lines.iter().rposition(|l| !blank(l))?;
56    let separator = lines[..last_content].iter().rposition(blank)?;
57    // There must be a non-blank paragraph (e.g. the subject) before the block.
58    lines[..separator]
59        .iter()
60        .any(|l| !blank(l))
61        .then_some(separator + 1)
62}
63
64fn rewrite_trailer_line(
65    line: &str,
66    old_email: &str,
67    new_name: &str,
68    new_email: &str,
69) -> Option<String> {
70    let trimmed = line.trim_end();
71    let (prefix, rest) = split_trailer(trimmed)?;
72    if !is_author_trailer(prefix) {
73        return None;
74    }
75    if !trailer_email_matches(rest, old_email) {
76        return None;
77    }
78    Some(format!("{prefix}: {new_name} <{new_email}>"))
79}
80
81fn split_trailer(line: &str) -> Option<(&str, &str)> {
82    let colon = line.find(':')?;
83    let prefix = &line[..colon];
84    let rest = line[colon + 1..].trim();
85    if prefix.is_empty() {
86        return None;
87    }
88    Some((prefix, rest))
89}
90
91fn is_author_trailer(prefix: &str) -> bool {
92    matches!(
93        prefix.to_ascii_lowercase().as_str(),
94        "signed-off-by" | "co-authored-by" | "authored-by"
95    )
96}
97
98fn trailer_email_matches(rest: &str, old_email: &str) -> bool {
99    if let Some(email) = extract_angle_email(rest) {
100        return email.eq_ignore_ascii_case(old_email);
101    }
102    // Bare email as the whole value, or trailing token
103    let candidate = rest.trim();
104    if candidate.eq_ignore_ascii_case(old_email) {
105        return true;
106    }
107    candidate
108        .split_whitespace()
109        .next_back()
110        .is_some_and(|tok| tok.eq_ignore_ascii_case(old_email))
111}
112
113fn extract_angle_email(rest: &str) -> Option<&str> {
114    let start = rest.rfind('<')?;
115    let end = rest[start + 1..].find('>')? + start + 1;
116    Some(&rest[start + 1..end])
117}
118
119#[cfg(test)]
120mod tests {
121    use super::*;
122
123    #[test]
124    fn rewrites_signed_off_by_when_email_matches() {
125        let msg = "Fix bug\n\nSigned-off-by: Old Name <old@ex.com>\n";
126        let out = rewrite_author_trailers(msg, "Old Name", "old@ex.com", "New Name", "new@ex.com");
127        assert_eq!(out, "Fix bug\n\nSigned-off-by: New Name <new@ex.com>\n");
128    }
129
130    #[test]
131    fn leaves_other_signoffs_alone() {
132        let msg = "Body\n\nSigned-off-by: Other <other@ex.com>\nSigned-off-by: Me <me@ex.com>\n";
133        let out = rewrite_author_trailers(msg, "Me", "me@ex.com", "New", "new@ex.com");
134        assert!(out.contains("Signed-off-by: Other <other@ex.com>"));
135        assert!(out.contains("Signed-off-by: New <new@ex.com>"));
136        assert!(!out.contains("me@ex.com"));
137    }
138
139    #[test]
140    fn leaves_body_text_alone() {
141        let msg = "Mention old@ex.com in body\n\nSigned-off-by: Old <old@ex.com>\n";
142        let out = rewrite_author_trailers(msg, "Old", "old@ex.com", "New", "new@ex.com");
143        assert!(out.starts_with("Mention old@ex.com in body\n"));
144        assert!(out.contains("Signed-off-by: New <new@ex.com>"));
145    }
146
147    #[test]
148    fn handles_bare_email_and_case() {
149        let msg = "x\n\nsigned-off-by: Someone OLD@EX.COM\n";
150        let out = rewrite_author_trailers(msg, "Someone", "old@ex.com", "New", "new@ex.com");
151        assert!(out.contains("signed-off-by: New <new@ex.com>"));
152    }
153
154    #[test]
155    fn no_change_when_email_differs() {
156        let msg = "x\n\nSigned-off-by: Other <other@ex.com>\n";
157        let out = rewrite_author_trailers(msg, "Me", "me@ex.com", "New", "new@ex.com");
158        assert_eq!(out, msg);
159    }
160
161    #[test]
162    fn rewrites_co_authored_and_authored_by() {
163        let msg = "x\n\nCo-authored-by: Old <old@ex.com>\nAuthored-by: Old <old@ex.com>\n";
164        let out = rewrite_author_trailers(msg, "Old", "old@ex.com", "New", "new@ex.com");
165        assert!(out.contains("Co-authored-by: New <new@ex.com>"));
166        assert!(out.contains("Authored-by: New <new@ex.com>"));
167    }
168
169    #[test]
170    fn ignores_signoff_lines_outside_the_trailer_block() {
171        let msg =
172            "x\n\nAs documented:\nSigned-off-by: old@ex.com\n\nSigned-off-by: Old <old@ex.com>\n";
173        let out = rewrite_author_trailers(msg, "Old", "old@ex.com", "New", "new@ex.com");
174        assert_eq!(
175            out,
176            "x\n\nAs documented:\nSigned-off-by: old@ex.com\n\nSigned-off-by: New <new@ex.com>\n"
177        );
178    }
179
180    #[test]
181    fn subject_only_message_has_no_trailers() {
182        let msg = "Signed-off-by: Old <old@ex.com>\n";
183        assert_eq!(
184            rewrite_author_trailers(msg, "Old", "old@ex.com", "New", "new@ex.com"),
185            msg
186        );
187    }
188
189    #[test]
190    fn preserves_crlf_line_endings() {
191        let msg = "subj\r\n\r\nbody\r\n\r\nSigned-off-by: Old <old@ex.com>\r\n";
192        let out = rewrite_author_trailers(msg, "Old", "old@ex.com", "New", "new@ex.com");
193        assert_eq!(
194            out,
195            "subj\r\n\r\nbody\r\n\r\nSigned-off-by: New <new@ex.com>\r\n"
196        );
197    }
198
199    #[test]
200    fn email_case_change_is_rewritten() {
201        let msg = "x\n\nSigned-off-by: Me <me@ex.com>\n";
202        let out = rewrite_author_trailers(msg, "Me", "me@ex.com", "Me", "Me@Ex.com");
203        assert_eq!(out, "x\n\nSigned-off-by: Me <Me@Ex.com>\n");
204    }
205
206    #[test]
207    fn noop_when_identity_unchanged() {
208        let msg = "x\n\nSigned-off-by: Same <same@ex.com>\n";
209        let out = rewrite_author_trailers(msg, "Same", "same@ex.com", "Same", "same@ex.com");
210        assert_eq!(out, msg);
211    }
212}