1use thiserror::Error;
15
16#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct ChangedHunk {
19 pub path: String,
21 pub added: Vec<AddedLine>,
23 pub removed: Vec<String>,
25}
26
27#[derive(Debug, Clone, PartialEq, Eq)]
29pub struct AddedLine {
30 pub line: u32,
32 pub text: String,
34}
35
36#[derive(Debug, Clone, PartialEq, Eq, Default)]
38pub struct Diff {
39 pub hunks: Vec<ChangedHunk>,
41}
42
43impl Diff {
44 pub fn added_lines(&self) -> impl Iterator<Item = (&str, &AddedLine)> {
46 self.hunks
47 .iter()
48 .flat_map(|h| h.added.iter().map(move |a| (h.path.as_str(), a)))
49 }
50
51 pub fn removed_lines(&self) -> impl Iterator<Item = (&str, &str)> {
53 self.hunks
54 .iter()
55 .flat_map(|h| h.removed.iter().map(move |r| (h.path.as_str(), r.as_str())))
56 }
57}
58
59#[derive(Debug, Error, PartialEq, Eq)]
61pub enum DiffError {
62 #[error("malformed hunk header: {0}")]
64 BadHunkHeader(String),
65 #[error("body line before file header: {0}")]
67 OrphanBody(String),
68}
69
70pub fn parse_unified_diff(input: &str) -> Result<Diff, DiffError> {
76 let mut diff = Diff::default();
77 let mut current_path: Option<String> = None;
78 let mut current_hunk: Option<ChangedHunk> = None;
79 let mut new_line_cursor: u32 = 0;
80
81 for line in input.lines() {
82 if let Some(rest) = line.strip_prefix("+++ ") {
83 flush_hunk(&mut diff, &mut current_hunk);
84 current_path = Some(strip_diff_prefix(rest).to_string());
85 continue;
86 }
87
88 if line.starts_with("--- ") || line.starts_with("diff --git ") || line.starts_with("index ")
89 {
90 continue;
91 }
92
93 if let Some(rest) = line.strip_prefix("@@ ") {
94 flush_hunk(&mut diff, &mut current_hunk);
95 let Some(path) = current_path.clone() else {
96 return Err(DiffError::OrphanBody(line.to_string()));
97 };
98 new_line_cursor = parse_hunk_header(rest)?;
99 current_hunk = Some(ChangedHunk {
100 path,
101 added: Vec::new(),
102 removed: Vec::new(),
103 });
104 continue;
105 }
106
107 let Some(hunk) = current_hunk.as_mut() else {
109 continue;
111 };
112
113 if let Some(added) = line.strip_prefix('+') {
114 hunk.added.push(AddedLine {
115 line: new_line_cursor,
116 text: added.to_string(),
117 });
118 new_line_cursor += 1;
119 } else if let Some(removed) = line.strip_prefix('-') {
120 hunk.removed.push(removed.to_string());
121 } else if let Some(_ctx) = line.strip_prefix(' ') {
122 new_line_cursor += 1;
123 }
124 }
126
127 flush_hunk(&mut diff, &mut current_hunk);
128 Ok(diff)
129}
130
131fn flush_hunk(diff: &mut Diff, current: &mut Option<ChangedHunk>) {
132 if let Some(h) = current.take() {
133 if !h.added.is_empty() || !h.removed.is_empty() {
134 diff.hunks.push(h);
135 }
136 }
137}
138
139fn strip_diff_prefix(header: &str) -> &str {
140 let path = header.split('\t').next().unwrap_or(header).trim();
142 path.strip_prefix("b/").unwrap_or(path)
143}
144
145fn parse_hunk_header(rest: &str) -> Result<u32, DiffError> {
146 let body = rest
148 .split_once("@@")
149 .map_or(rest, |(before, _)| before)
150 .trim();
151
152 for part in body.split_whitespace() {
153 if let Some(new_part) = part.strip_prefix('+') {
154 let start = new_part
155 .split(',')
156 .next()
157 .ok_or_else(|| DiffError::BadHunkHeader(rest.to_string()))?;
158 return start
159 .parse::<u32>()
160 .map_err(|_| DiffError::BadHunkHeader(rest.to_string()));
161 }
162 }
163 Err(DiffError::BadHunkHeader(rest.to_string()))
164}
165
166#[cfg(test)]
167mod tests {
168 use super::*;
169
170 const SIMPLE: &str = "\
171diff --git a/src/lib.rs b/src/lib.rs
172--- a/src/lib.rs
173+++ b/src/lib.rs
174@@ -1,3 +1,4 @@
175 fn a() {}
176-fn b() {}
177+fn b_renamed() {}
178+fn c() {}
179";
180
181 #[test]
182 fn parses_file_path_without_prefix() {
183 let d = parse_unified_diff(SIMPLE).unwrap();
184 assert_eq!(d.hunks.len(), 1);
185 assert_eq!(d.hunks[0].path, "src/lib.rs");
186 }
187
188 #[test]
189 fn tracks_added_line_numbers_in_new_file() {
190 let d = parse_unified_diff(SIMPLE).unwrap();
191 let added = &d.hunks[0].added;
192 assert_eq!(added.len(), 2);
193 assert_eq!(added[0].line, 2);
195 assert_eq!(added[0].text, "fn b_renamed() {}");
196 assert_eq!(added[1].line, 3);
197 }
198
199 #[test]
200 fn collects_removed_lines() {
201 let d = parse_unified_diff(SIMPLE).unwrap();
202 assert_eq!(d.hunks[0].removed, vec!["fn b() {}".to_string()]);
203 }
204
205 #[test]
206 fn single_line_hunk_header_is_accepted() {
207 let input = "\
208--- a/foo.rs
209+++ b/foo.rs
210@@ -1 +1 @@
211-old
212+new
213";
214 let d = parse_unified_diff(input).unwrap();
215 assert_eq!(d.hunks[0].added[0].line, 1);
216 assert_eq!(d.hunks[0].removed, vec!["old".to_string()]);
217 }
218
219 #[test]
220 fn malformed_hunk_header_is_reported() {
221 let input = "\
222+++ b/foo.rs
223@@ not-a-header @@
224+x
225";
226 assert!(matches!(
227 parse_unified_diff(input),
228 Err(DiffError::BadHunkHeader(_))
229 ));
230 }
231
232 #[test]
233 fn empty_diff_is_ok() {
234 let d = parse_unified_diff("").unwrap();
235 assert!(d.hunks.is_empty());
236 }
237
238 #[test]
239 fn multi_file_diff() {
240 let input = "\
241--- a/a.rs
242+++ b/a.rs
243@@ -1 +1 @@
244-a1
245+a2
246--- a/b.rs
247+++ b/b.rs
248@@ -1 +1 @@
249-b1
250+b2
251";
252 let d = parse_unified_diff(input).unwrap();
253 assert_eq!(d.hunks.len(), 2);
254 assert_eq!(d.hunks[0].path, "a.rs");
255 assert_eq!(d.hunks[1].path, "b.rs");
256 }
257}