Skip to main content

gitpoulpi_core/
diff_text.rs

1//! Unified-diff text to [`FileDiff`]s, with no I/O: the one parser behind
2//! the system-git backend (`git diff` output) and the hosting API diffs (a
3//! host's per-file `patch`, which has hunks but no `diff --git` header).
4//!
5//! Lines are split with [`str::lines`], so a `\r\n` terminator is dropped
6//! like a `\n`: a CRLF patch parses as the same lines as an LF one. A
7//! `\ No newline at end of file` marker is not a line of the file and is
8//! skipped.
9
10use std::iter::Peekable;
11use std::path::PathBuf;
12use std::str::Lines;
13
14use crate::domain::{DiffLine, FileDiff, FileStatus, Hunk, HunkId, LineOrigin};
15
16/// Parses a whole `git diff` output: one [`FileDiff`] per `diff --git`
17/// header, its status read from the extended header lines (`new file mode`,
18/// `deleted file mode`, `rename from|to`).
19pub fn parse_unified(raw: &str) -> Vec<FileDiff> {
20    let mut files = Vec::new();
21    let mut lines = raw.lines().peekable();
22
23    while let Some(line) = lines.next() {
24        let Some(header) = line.strip_prefix("diff --git ") else {
25            continue;
26        };
27        let path = extract_path(header);
28        let mut status = FileStatus::Modified;
29        let mut renamed_from: Option<PathBuf> = None;
30        let mut similarity: Option<u8> = None;
31        let mut renamed_to: Option<PathBuf> = None;
32
33        // Consume everything up to (and including) the first hunk header
34        // or the next file's diff header, tracking status markers.
35        while let Some(&peeked) = lines.peek() {
36            if peeked.starts_with("diff --git ") || peeked.starts_with("@@ ") {
37                break;
38            }
39            let l = lines.next().unwrap();
40            if l.starts_with("new file mode") {
41                status = FileStatus::Added;
42            } else if l.starts_with("deleted file mode") {
43                status = FileStatus::Deleted;
44            } else if let Some(from) = l
45                .strip_prefix("rename from ")
46                .or_else(|| l.strip_prefix("copy from "))
47            {
48                status = FileStatus::Renamed;
49                renamed_from = Some(PathBuf::from(from));
50            } else if let Some(to) = l
51                .strip_prefix("rename to ")
52                .or_else(|| l.strip_prefix("copy to "))
53            {
54                status = FileStatus::Renamed;
55                renamed_to = Some(PathBuf::from(to));
56            } else if let Some(pct) = l.strip_prefix("similarity index ") {
57                similarity = pct.trim_end_matches('%').parse().ok();
58            }
59        }
60
61        let hunks = read_hunks(&mut lines);
62        files.push(FileDiff {
63            path: renamed_to.unwrap_or(path),
64            status,
65            hunks,
66            renamed_from,
67            similarity,
68        });
69    }
70
71    files
72}
73
74/// Parses the hunks of one file's `patch` (what a hosting API returns per
75/// file: `@@ -a,b +c,d @@` sections, no `diff --git` / `---` / `+++`
76/// header) into a [`FileDiff`] for `path` with the given `status`. Anything
77/// before the first `@@` line is skipped, so a patch that does carry
78/// `---`/`+++` lines parses the same. An empty patch (a binary file, a
79/// mode change, a rename without edits) has no hunks.
80pub fn parse_hunks(path: impl Into<PathBuf>, status: FileStatus, patch: &str) -> FileDiff {
81    let mut lines = patch.lines().peekable();
82    while lines.next_if(|l| !l.starts_with("@@ ")).is_some() {}
83    FileDiff {
84        renamed_from: None,
85        similarity: None,
86        path: path.into(),
87        status,
88        hunks: read_hunks(&mut lines),
89    }
90}
91
92/// Reads consecutive hunks (`@@ ` header plus body) from `lines`, stopping
93/// at the next file header or when the input ends.
94fn read_hunks(lines: &mut Peekable<Lines<'_>>) -> Vec<Hunk> {
95    let mut hunks = Vec::new();
96    let mut next_hunk_id = 0u32;
97    while let Some(&peeked) = lines.peek() {
98        if !peeked.starts_with("@@ ") {
99            break;
100        }
101        let hunk_header = lines.next().unwrap();
102        let Some((old_start, old_lines, new_start, new_lines)) = parse_hunk_header(hunk_header)
103        else {
104            continue;
105        };
106
107        let mut hunk_lines = Vec::new();
108        while let Some(&peeked) = lines.peek() {
109            if peeked.starts_with("@@ ") || peeked.starts_with("diff --git ") {
110                break;
111            }
112            let l = lines.next().unwrap();
113            if let Some(content) = l.strip_prefix('+') {
114                hunk_lines.push(DiffLine {
115                    origin: LineOrigin::Add,
116                    content: content.to_string(),
117                    staged: false,
118                });
119            } else if let Some(content) = l.strip_prefix('-') {
120                hunk_lines.push(DiffLine {
121                    origin: LineOrigin::Delete,
122                    content: content.to_string(),
123                    staged: false,
124                });
125            } else if let Some(content) = l.strip_prefix(' ') {
126                hunk_lines.push(DiffLine {
127                    origin: LineOrigin::Context,
128                    content: content.to_string(),
129                    staged: false,
130                });
131            }
132            // lines like "\ No newline at end of file" are ignored.
133        }
134
135        hunks.push(Hunk {
136            id: HunkId(next_hunk_id),
137            old_start,
138            old_lines,
139            new_start,
140            new_lines,
141            lines: hunk_lines,
142        });
143        next_hunk_id += 1;
144    }
145    hunks
146}
147
148/// `diff --git a/<path> b/<path>` - paths can contain spaces, so this
149/// trusts the `a/`/`b/` markers rather than splitting on whitespace.
150fn extract_path(header: &str) -> PathBuf {
151    if let Some(b_idx) = header.rfind(" b/") {
152        return PathBuf::from(&header[b_idx + 3..]);
153    }
154    PathBuf::from(header)
155}
156
157fn parse_hunk_header(line: &str) -> Option<(u32, u32, u32, u32)> {
158    let body = line.strip_prefix("@@ -")?;
159    let (ranges, _) = body.split_once(" @@")?;
160    let (old_range, new_range) = ranges.split_once(" +")?;
161    let (old_start, old_lines) = parse_range(old_range);
162    let (new_start, new_lines) = parse_range(new_range);
163    Some((old_start, old_lines, new_start, new_lines))
164}
165
166fn parse_range(range: &str) -> (u32, u32) {
167    match range.split_once(',') {
168        Some((start, len)) => (start.parse().unwrap_or(0), len.parse().unwrap_or(0)),
169        None => (range.parse().unwrap_or(0), 1),
170    }
171}
172
173#[cfg(test)]
174mod tests {
175    use super::*;
176
177    fn contents(file: &FileDiff) -> Vec<(LineOrigin, &str)> {
178        file.hunks
179            .iter()
180            .flat_map(|h| h.lines.iter())
181            .map(|l| (l.origin.clone(), l.content.as_str()))
182            .collect()
183    }
184
185    #[test]
186    fn a_git_diff_gives_one_file_per_header_with_its_status() {
187        let raw = "diff --git a/old name.txt b/new name.txt\nsimilarity index 90%\nrename from old name.txt\nrename to new name.txt\n@@ -1,2 +1,2 @@\n keep\n-a\n+b\ndiff --git a/n.txt b/n.txt\nnew file mode 100644\n--- /dev/null\n+++ b/n.txt\n@@ -0,0 +1 @@\n+x\n";
188        let files = parse_unified(raw);
189        assert_eq!(files.len(), 2);
190        assert_eq!(files[0].path, PathBuf::from("new name.txt"));
191        assert_eq!(files[0].status, FileStatus::Renamed);
192        assert_eq!(files[1].status, FileStatus::Added);
193        assert_eq!(
194            contents(&files[0]),
195            vec![
196                (LineOrigin::Context, "keep"),
197                (LineOrigin::Delete, "a"),
198                (LineOrigin::Add, "b")
199            ]
200        );
201        let h = &files[0].hunks[0];
202        assert_eq!(
203            (h.old_start, h.old_lines, h.new_start, h.new_lines),
204            (1, 2, 1, 2)
205        );
206        // A one-line range has no `,len`: it is 1.
207        let h = &files[1].hunks[0];
208        assert_eq!(
209            (h.old_start, h.old_lines, h.new_start, h.new_lines),
210            (0, 0, 1, 1)
211        );
212    }
213
214    #[test]
215    fn the_no_newline_marker_is_not_a_line() {
216        let patch =
217            "@@ -1 +1 @@\n-old\n\\ No newline at end of file\n+new\n\\ No newline at end of file\n";
218        let file = parse_hunks("a.txt", FileStatus::Modified, patch);
219        assert_eq!(
220            contents(&file),
221            vec![(LineOrigin::Delete, "old"), (LineOrigin::Add, "new")]
222        );
223    }
224
225    #[test]
226    fn a_crlf_patch_parses_like_an_lf_one() {
227        let lf = "@@ -1,2 +1,2 @@\n a\n-b\n+c\n";
228        let crlf = lf.replace('\n', "\r\n");
229        assert_eq!(
230            parse_hunks("a", FileStatus::Modified, &crlf),
231            parse_hunks("a", FileStatus::Modified, lf)
232        );
233    }
234
235    #[test]
236    fn a_host_patch_without_headers_has_its_hunks_numbered() {
237        let patch = "@@ -1,2 +1,3 @@\n a\n+b\n c\n@@ -10 +11,2 @@\n-x\n+y\n+z";
238        let file = parse_hunks("src/x.rs", FileStatus::Modified, patch);
239        assert_eq!(file.path, PathBuf::from("src/x.rs"));
240        assert_eq!(file.hunks.len(), 2);
241        assert_eq!(file.hunks[1].id, HunkId(1));
242        assert_eq!(file.hunks[1].old_start, 10);
243        assert_eq!(file.hunks[1].new_lines, 2);
244        assert_eq!(file.hunks[1].lines.len(), 3);
245    }
246
247    #[test]
248    fn leading_header_lines_and_empty_patches_are_tolerated() {
249        let with_headers = "--- a/x\n+++ b/x\n@@ -1 +1 @@\n-a\n+b\n";
250        assert_eq!(
251            parse_hunks("x", FileStatus::Modified, with_headers)
252                .hunks
253                .len(),
254            1
255        );
256        assert!(parse_hunks("img.png", FileStatus::Modified, "")
257            .hunks
258            .is_empty());
259    }
260}