Skip to main content

eclipse_core/
diff.rs

1//! `#656`: one parse of a unified diff, in core, for three surfaces to draw.
2//!
3//! `patch` already returns a small unified diff (`tools_patch::render_diff`), and every surface
4//! threw that shape away — the TUI by drawing one line per call, the REPL by collapsing whitespace
5//! with `clip`, the dashboard by putting it in a `<pre>`. Each of those is a rendering decision,
6//! and none of them can be checked by a test that lives in a page.
7//!
8//! So the parse lives here, where `cargo test` reaches it, and the renderers only choose colours,
9//! a cap and how many rows to show. Three surfaces that agree by parsing the same rows once is a
10//! weaker guarantee than three that each re-read the text, and it is the difference between a
11//! change that reads at a glance and one that has to be scanned for `+` and `-` by eye.
12//!
13//! Nothing in this module knows what a terminal, a browser or a prompt is. It has no caller until
14//! the renderers land (#656b), which is deliberate: a parse with tests and no consumer is inert,
15//! and it can land beside the audit batch without touching a line of it.
16//!
17//! Two rules are worth stating because they are the ones a page gets wrong:
18//!
19//! * **A file preamble is not a change.** `--- a/x` / `+++ b/x` before the first `@@` are the two
20//!   file names, not a removed and an added line. Read as changes they inflate every count by one
21//!   in each direction, which is the sort of error nobody notices until they trust the number.
22//! * **A partial line is shown as it is.** `render_diff` deliberately emits a `-`/`+` pair whose
23//!   text is a fragment of a line when the match began mid-line. The fragment is what a person
24//!   needs to see; pretending it is a whole line would be a different, wrong edit.
25
26use serde::{Deserialize, Serialize};
27
28/// What one row of a diff is.
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
30#[serde(rename_all = "lowercase")]
31pub enum Kind {
32    /// A line the edit adds. It exists only after the change.
33    Add,
34    /// A line the edit removes. It exists only before it.
35    Remove,
36    /// A line that is in both, kept for context.
37    Context,
38    /// Not a line of the file: a `@@` header, the trailing `… N more` row, a preamble, or a note
39    /// such as `\ No newline at end of file`. Drawn, never counted.
40    Sep,
41}
42
43/// One row, with the line numbers it has on each side.
44///
45/// `old` is the line in the file before the edit, `new` the line after it; an added row has no
46/// `old` and a removed row has no `new`. Numbers start at 1, as a person counts lines, and a
47/// hunk against an empty file legitimately starts the old side at 0 — there is no first line of a
48/// file that has none.
49#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
50pub struct Row {
51    pub kind: Kind,
52    pub old: Option<u32>,
53    pub new: Option<u32>,
54    pub text: String,
55}
56
57/// Read a unified diff into rows.
58///
59/// Anything the format does not describe as a line of the file becomes [`Kind::Sep`] with its text
60/// kept: an unreadable row is a row a person should see, not a row to drop silently. That is also
61/// what makes this safe on a diff written by git, which carries a preamble and `\ No newline`
62/// notes this crate's own renderer never emits.
63pub fn parse(text: &str) -> Vec<Row> {
64    let mut rows = Vec::new();
65    let mut old = 1;
66    let mut new = 1;
67    let mut in_hunk = false;
68
69    for line in text.lines() {
70        if let Some((old_start, new_start)) = hunk_header(line) {
71            in_hunk = true;
72            old = old_start;
73            new = new_start;
74            rows.push(sep(line));
75            continue;
76        }
77        // Before the first hunk, `---`/`+++` are the two file names. After one they are a removed
78        // and an added line, so the same three characters mean different things by position.
79        if !in_hunk && is_preamble(line) {
80            rows.push(sep(line));
81            continue;
82        }
83        let Some(marker) = line.chars().next() else {
84            // An empty line is not a line of any file: a file's empty line is ` ` in a diff.
85            rows.push(sep(line));
86            continue;
87        };
88        // `char_indices` rather than `split_at(1)`: a line can begin with a multi-byte character,
89        // and splitting on a byte boundary panics.
90        let text = &line[marker.len_utf8()..];
91        match marker {
92            '+' => {
93                rows.push(Row {
94                    kind: Kind::Add,
95                    old: None,
96                    new: Some(new),
97                    text: text.to_string(),
98                });
99                new += 1;
100            }
101            '-' => {
102                rows.push(Row {
103                    kind: Kind::Remove,
104                    old: Some(old),
105                    new: None,
106                    text: text.to_string(),
107                });
108                old += 1;
109            }
110            ' ' => {
111                rows.push(Row {
112                    kind: Kind::Context,
113                    old: Some(old),
114                    new: Some(new),
115                    text: text.to_string(),
116                });
117                old += 1;
118                new += 1;
119            }
120            _ => rows.push(sep(line)),
121        }
122    }
123    rows
124}
125
126/// How many lines the edit adds and removes: `(added, removed)`.
127///
128/// The count a surface shows beside the row. Context and separators are not changes, which is the
129/// whole reason this is a function and not `.len()`.
130pub fn change(rows: &[Row]) -> (usize, usize) {
131    let count = |kind| rows.iter().filter(|r| r.kind == kind).count();
132    (count(Kind::Add), count(Kind::Remove))
133}
134
135fn sep(line: &str) -> Row {
136    Row {
137        kind: Kind::Sep,
138        old: None,
139        new: None,
140        text: line.to_string(),
141    }
142}
143
144/// `@@ -12,7 +12,6 @@` → `(12, 12)`.
145///
146/// Only the starting numbers matter: the counts are what a renderer would use to decide how much
147/// to draw, and this module draws everything it was given.
148fn hunk_header(line: &str) -> Option<(u32, u32)> {
149    let rest = line.strip_prefix("@@ -")?;
150    let (old, rest) = rest.split_once(' ')?;
151    let rest = rest.strip_prefix('+')?;
152    let (new, _) = rest.split_once(' ')?;
153    Some((start_of(old)?, start_of(new)?))
154}
155
156/// `7` or `7,3` → `7`. A bare `-0,0` is the empty file on that side, and `0` is honest there.
157fn start_of(range: &str) -> Option<u32> {
158    range.split(',').next()?.parse().ok()
159}
160
161/// The lines git writes above the first hunk: `diff --git a/x b/x`, `index 1b2c…`, `--- a/x`,
162/// `+++ b/x`. Recognising them by their own prefixes is enough — a line of a file cannot be
163/// `diff --git ` and still be inside a hunk, because inside a hunk every line starts with a marker.
164fn is_preamble(line: &str) -> bool {
165    line.starts_with("diff ")
166        || line.starts_with("index ")
167        || line.starts_with("--- ")
168        || line.starts_with("+++ ")
169        || line.starts_with("new file mode ")
170        || line.starts_with("deleted file mode ")
171}
172
173#[cfg(test)]
174mod tests {
175    use super::*;
176
177    fn texts(rows: &[Row]) -> Vec<&str> {
178        rows.iter().map(|r| r.text.as_str()).collect()
179    }
180
181    fn kinds(rows: &[Row]) -> Vec<Kind> {
182        rows.iter().map(|r| r.kind).collect()
183    }
184
185    #[test]
186    fn an_edit_at_the_top_of_a_file() {
187        // `@@ -1,4 +1,4 @@` is what `render_diff` writes for a change on line 2 with one line of
188        // context either side.
189        let text = "@@ -1,4 +1,4 @@\n use std::fmt;\n-let x = 1;\n+let x = 2;\n fn main() {}\n";
190        let rows = parse(text);
191        assert_eq!(
192            kinds(&rows),
193            [
194                Kind::Sep,
195                Kind::Context,
196                Kind::Remove,
197                Kind::Add,
198                Kind::Context
199            ]
200        );
201        assert_eq!(
202            texts(&rows),
203            [
204                "@@ -1,4 +1,4 @@",
205                "use std::fmt;",
206                "let x = 1;",
207                "let x = 2;",
208                "fn main() {}"
209            ]
210        );
211        // A removed line keeps its old number and has no new one; an added line is the other way
212        // round; a context line has both, and they are the same number only at the top of a file.
213        assert_eq!(rows[1].old, Some(1));
214        assert_eq!(rows[1].new, Some(1));
215        assert_eq!(rows[2].old, Some(2));
216        assert_eq!(rows[2].new, None);
217        assert_eq!(rows[3].old, None);
218        assert_eq!(rows[3].new, Some(2));
219        assert_eq!(rows[4].old, Some(3));
220        assert_eq!(rows[4].new, Some(3));
221        assert_eq!(change(&rows), (1, 1));
222    }
223
224    #[test]
225    fn an_edit_at_eof_with_no_trailing_newline() {
226        // The last line of a file without a newline is the last line of the diff without one. It
227        // must not vanish, which is what reading the text with `split('\n')` and skipping the
228        // empty tail would do.
229        let text = "@@ -3,2 +3,2 @@\n keep\n-old last";
230        let rows = parse(text);
231        assert_eq!(kinds(&rows), [Kind::Sep, Kind::Context, Kind::Remove]);
232        assert_eq!(texts(&rows), ["@@ -3,2 +3,2 @@", "keep", "old last"]);
233        assert_eq!(rows[2].old, Some(4));
234        assert_eq!(change(&rows), (0, 1));
235    }
236
237    #[test]
238    fn a_partial_line_match_shows_the_fragment() {
239        // `render_diff` says so in its own words: a match that begins mid-line shows that partial
240        // line as the `-`/`+` row. The fragment is not padded out to look like a whole line — the
241        // marker column is the first character and everything after it is the text, whatever
242        // length it happens to be.
243        let text = "@@ -5,3 +5,3 @@\n context\n-middle\n+MIDDLE\n context\n";
244        let rows = parse(text);
245        assert_eq!(rows[2].kind, Kind::Remove);
246        assert_eq!(rows[2].text, "middle");
247        assert_eq!(rows[2].old, Some(6));
248        assert_eq!(rows[3].text, "MIDDLE");
249        assert_eq!(rows[3].new, Some(6));
250        assert_eq!(change(&rows), (1, 1));
251    }
252
253    #[test]
254    fn three_hunks_with_the_elision_row() {
255        // `render_diff` caps at `MAX_HUNKS` and closes with `… N more edit(s)`. That row is drawn
256        // and must never be counted as a change.
257        let text = "@@ -1,2 +1,2 @@\n-a\n+A\n b\n@@ -20,2 +20,2 @@\n-c\n+C\n d\n@@ -40,2 +40,2 @@\n-e\n+E\n f\n… 2 more edit(s)\n";
258        let rows = parse(text);
259        assert_eq!(change(&rows), (3, 3));
260        assert_eq!(kinds(&rows).iter().filter(|k| **k == Kind::Sep).count(), 4);
261        assert_eq!(rows.last().unwrap().kind, Kind::Sep);
262        assert_eq!(rows.last().unwrap().text, "… 2 more edit(s)");
263        // Line numbers follow each hunk's own header, not the row count before it.
264        let second = rows.iter().find(|r| r.text == "c").unwrap();
265        assert_eq!(second.old, Some(20));
266        let third = rows.iter().find(|r| r.text == "e").unwrap();
267        assert_eq!(third.old, Some(40));
268    }
269
270    #[test]
271    fn a_diff_against_an_empty_file() {
272        // `-0,0` is a file with no lines: every row is an addition, and none of them has an old
273        // number to have.
274        let text = "@@ -0,0 +1,3 @@\n+one\n+two\n+three\n";
275        let rows = parse(text);
276        assert_eq!(kinds(&rows), [Kind::Sep, Kind::Add, Kind::Add, Kind::Add]);
277        assert!(rows[1..].iter().all(|r| r.old.is_none()));
278        assert_eq!(rows[1].new, Some(1));
279        assert_eq!(rows[3].new, Some(3));
280        assert_eq!(change(&rows), (3, 0));
281    }
282
283    #[test]
284    fn a_git_preamble_is_not_a_change() {
285        // The two file names look exactly like a removed and an added line. Read as changes they
286        // add one to each count and put a `--- a/x` row in the middle of the drawing.
287        let text = "diff --git a/src/x.rs b/src/x.rs\nindex 1b2c3d4..5e6f7a8 100644\n--- a/src/x.rs\n+++ b/src/x.rs\n@@ -1,2 +1,2 @@\n-old\n+new\n same\n\\ No newline at end of file\n";
288        let rows = parse(text);
289        assert_eq!(change(&rows), (1, 1));
290        assert!(rows
291            .iter()
292            .any(|r| r.text == "diff --git a/src/x.rs b/src/x.rs"));
293        assert!(rows.iter().any(|r| r.text == "--- a/src/x.rs"));
294        assert!(rows
295            .iter()
296            .any(|r| r.text == "\\ No newline at end of file"));
297        assert_eq!(rows.last().unwrap().kind, Kind::Sep);
298    }
299
300    #[test]
301    fn a_line_that_is_not_a_diff_is_kept_and_not_counted() {
302        // A tool that printed something else must not be summarised as "0 added, 0 removed" with
303        // the text thrown away: text that is not a diff still reaches the person who asked.
304        let rows = parse("the file is not a diff at all\nnor this\n");
305        assert_eq!(rows.len(), 2);
306        assert!(rows.iter().all(|r| r.kind == Kind::Sep));
307        assert_eq!(change(&rows), (0, 0));
308    }
309
310    #[test]
311    fn a_header_with_a_count_but_no_comma_and_one_with_no_count_both_read() {
312        // `@@ -1 +1 @@` is legal when the hunk is a single line, and git writes it.
313        let rows = parse("@@ -1 +1 @@\n-old\n+new\n");
314        assert_eq!(change(&rows), (1, 1));
315        assert_eq!(rows[1].old, Some(1));
316        assert_eq!(rows[2].new, Some(1));
317    }
318
319    #[test]
320    fn a_multibyte_line_does_not_split_inside_a_character() {
321        // The marker is one ASCII byte, but the text after it is not: the split has to be on a
322        // character boundary or the parse panics.
323        let rows = parse("@@ -1,2 +1,2 @@\n-žluťoučký\n+žluťoučký kůň\n same\n");
324        assert_eq!(rows[1].text, "žluťoučký");
325        assert_eq!(rows[2].text, "žluťoučký kůň");
326        assert_eq!(change(&rows), (1, 1));
327    }
328}