eclipse-core 0.15.1

Core library for eclipse: providers, tools, sessions, config, runtime
Documentation
//! `#656`: one parse of a unified diff, in core, for three surfaces to draw.
//!
//! `patch` already returns a small unified diff (`tools_patch::render_diff`), and every surface
//! threw that shape away — the TUI by drawing one line per call, the REPL by collapsing whitespace
//! with `clip`, the dashboard by putting it in a `<pre>`. Each of those is a rendering decision,
//! and none of them can be checked by a test that lives in a page.
//!
//! So the parse lives here, where `cargo test` reaches it, and the renderers only choose colours,
//! a cap and how many rows to show. Three surfaces that agree by parsing the same rows once is a
//! weaker guarantee than three that each re-read the text, and it is the difference between a
//! change that reads at a glance and one that has to be scanned for `+` and `-` by eye.
//!
//! Nothing in this module knows what a terminal, a browser or a prompt is. It has no caller until
//! the renderers land (#656b), which is deliberate: a parse with tests and no consumer is inert,
//! and it can land beside the audit batch without touching a line of it.
//!
//! Two rules are worth stating because they are the ones a page gets wrong:
//!
//! * **A file preamble is not a change.** `--- a/x` / `+++ b/x` before the first `@@` are the two
//!   file names, not a removed and an added line. Read as changes they inflate every count by one
//!   in each direction, which is the sort of error nobody notices until they trust the number.
//! * **A partial line is shown as it is.** `render_diff` deliberately emits a `-`/`+` pair whose
//!   text is a fragment of a line when the match began mid-line. The fragment is what a person
//!   needs to see; pretending it is a whole line would be a different, wrong edit.

use serde::{Deserialize, Serialize};

/// What one row of a diff is.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Kind {
    /// A line the edit adds. It exists only after the change.
    Add,
    /// A line the edit removes. It exists only before it.
    Remove,
    /// A line that is in both, kept for context.
    Context,
    /// Not a line of the file: a `@@` header, the trailing `… N more` row, a preamble, or a note
    /// such as `\ No newline at end of file`. Drawn, never counted.
    Sep,
}

/// One row, with the line numbers it has on each side.
///
/// `old` is the line in the file before the edit, `new` the line after it; an added row has no
/// `old` and a removed row has no `new`. Numbers start at 1, as a person counts lines, and a
/// hunk against an empty file legitimately starts the old side at 0 — there is no first line of a
/// file that has none.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Row {
    pub kind: Kind,
    pub old: Option<u32>,
    pub new: Option<u32>,
    pub text: String,
}

/// Read a unified diff into rows.
///
/// Anything the format does not describe as a line of the file becomes [`Kind::Sep`] with its text
/// kept: an unreadable row is a row a person should see, not a row to drop silently. That is also
/// what makes this safe on a diff written by git, which carries a preamble and `\ No newline`
/// notes this crate's own renderer never emits.
pub fn parse(text: &str) -> Vec<Row> {
    let mut rows = Vec::new();
    let mut old = 1;
    let mut new = 1;
    let mut in_hunk = false;

    for line in text.lines() {
        if let Some((old_start, new_start)) = hunk_header(line) {
            in_hunk = true;
            old = old_start;
            new = new_start;
            rows.push(sep(line));
            continue;
        }
        // Before the first hunk, `---`/`+++` are the two file names. After one they are a removed
        // and an added line, so the same three characters mean different things by position.
        if !in_hunk && is_preamble(line) {
            rows.push(sep(line));
            continue;
        }
        let Some(marker) = line.chars().next() else {
            // An empty line is not a line of any file: a file's empty line is ` ` in a diff.
            rows.push(sep(line));
            continue;
        };
        // `char_indices` rather than `split_at(1)`: a line can begin with a multi-byte character,
        // and splitting on a byte boundary panics.
        let text = &line[marker.len_utf8()..];
        match marker {
            '+' => {
                rows.push(Row {
                    kind: Kind::Add,
                    old: None,
                    new: Some(new),
                    text: text.to_string(),
                });
                new += 1;
            }
            '-' => {
                rows.push(Row {
                    kind: Kind::Remove,
                    old: Some(old),
                    new: None,
                    text: text.to_string(),
                });
                old += 1;
            }
            ' ' => {
                rows.push(Row {
                    kind: Kind::Context,
                    old: Some(old),
                    new: Some(new),
                    text: text.to_string(),
                });
                old += 1;
                new += 1;
            }
            _ => rows.push(sep(line)),
        }
    }
    rows
}

/// How many lines the edit adds and removes: `(added, removed)`.
///
/// The count a surface shows beside the row. Context and separators are not changes, which is the
/// whole reason this is a function and not `.len()`.
pub fn change(rows: &[Row]) -> (usize, usize) {
    let count = |kind| rows.iter().filter(|r| r.kind == kind).count();
    (count(Kind::Add), count(Kind::Remove))
}

fn sep(line: &str) -> Row {
    Row {
        kind: Kind::Sep,
        old: None,
        new: None,
        text: line.to_string(),
    }
}

/// `@@ -12,7 +12,6 @@` → `(12, 12)`.
///
/// Only the starting numbers matter: the counts are what a renderer would use to decide how much
/// to draw, and this module draws everything it was given.
fn hunk_header(line: &str) -> Option<(u32, u32)> {
    let rest = line.strip_prefix("@@ -")?;
    let (old, rest) = rest.split_once(' ')?;
    let rest = rest.strip_prefix('+')?;
    let (new, _) = rest.split_once(' ')?;
    Some((start_of(old)?, start_of(new)?))
}

/// `7` or `7,3` → `7`. A bare `-0,0` is the empty file on that side, and `0` is honest there.
fn start_of(range: &str) -> Option<u32> {
    range.split(',').next()?.parse().ok()
}

/// The lines git writes above the first hunk: `diff --git a/x b/x`, `index 1b2c…`, `--- a/x`,
/// `+++ b/x`. Recognising them by their own prefixes is enough — a line of a file cannot be
/// `diff --git ` and still be inside a hunk, because inside a hunk every line starts with a marker.
fn is_preamble(line: &str) -> bool {
    line.starts_with("diff ")
        || line.starts_with("index ")
        || line.starts_with("--- ")
        || line.starts_with("+++ ")
        || line.starts_with("new file mode ")
        || line.starts_with("deleted file mode ")
}

#[cfg(test)]
mod tests {
    use super::*;

    fn texts(rows: &[Row]) -> Vec<&str> {
        rows.iter().map(|r| r.text.as_str()).collect()
    }

    fn kinds(rows: &[Row]) -> Vec<Kind> {
        rows.iter().map(|r| r.kind).collect()
    }

    #[test]
    fn an_edit_at_the_top_of_a_file() {
        // `@@ -1,4 +1,4 @@` is what `render_diff` writes for a change on line 2 with one line of
        // context either side.
        let text = "@@ -1,4 +1,4 @@\n use std::fmt;\n-let x = 1;\n+let x = 2;\n fn main() {}\n";
        let rows = parse(text);
        assert_eq!(
            kinds(&rows),
            [
                Kind::Sep,
                Kind::Context,
                Kind::Remove,
                Kind::Add,
                Kind::Context
            ]
        );
        assert_eq!(
            texts(&rows),
            [
                "@@ -1,4 +1,4 @@",
                "use std::fmt;",
                "let x = 1;",
                "let x = 2;",
                "fn main() {}"
            ]
        );
        // A removed line keeps its old number and has no new one; an added line is the other way
        // round; a context line has both, and they are the same number only at the top of a file.
        assert_eq!(rows[1].old, Some(1));
        assert_eq!(rows[1].new, Some(1));
        assert_eq!(rows[2].old, Some(2));
        assert_eq!(rows[2].new, None);
        assert_eq!(rows[3].old, None);
        assert_eq!(rows[3].new, Some(2));
        assert_eq!(rows[4].old, Some(3));
        assert_eq!(rows[4].new, Some(3));
        assert_eq!(change(&rows), (1, 1));
    }

    #[test]
    fn an_edit_at_eof_with_no_trailing_newline() {
        // The last line of a file without a newline is the last line of the diff without one. It
        // must not vanish, which is what reading the text with `split('\n')` and skipping the
        // empty tail would do.
        let text = "@@ -3,2 +3,2 @@\n keep\n-old last";
        let rows = parse(text);
        assert_eq!(kinds(&rows), [Kind::Sep, Kind::Context, Kind::Remove]);
        assert_eq!(texts(&rows), ["@@ -3,2 +3,2 @@", "keep", "old last"]);
        assert_eq!(rows[2].old, Some(4));
        assert_eq!(change(&rows), (0, 1));
    }

    #[test]
    fn a_partial_line_match_shows_the_fragment() {
        // `render_diff` says so in its own words: a match that begins mid-line shows that partial
        // line as the `-`/`+` row. The fragment is not padded out to look like a whole line — the
        // marker column is the first character and everything after it is the text, whatever
        // length it happens to be.
        let text = "@@ -5,3 +5,3 @@\n context\n-middle\n+MIDDLE\n context\n";
        let rows = parse(text);
        assert_eq!(rows[2].kind, Kind::Remove);
        assert_eq!(rows[2].text, "middle");
        assert_eq!(rows[2].old, Some(6));
        assert_eq!(rows[3].text, "MIDDLE");
        assert_eq!(rows[3].new, Some(6));
        assert_eq!(change(&rows), (1, 1));
    }

    #[test]
    fn three_hunks_with_the_elision_row() {
        // `render_diff` caps at `MAX_HUNKS` and closes with `… N more edit(s)`. That row is drawn
        // and must never be counted as a change.
        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";
        let rows = parse(text);
        assert_eq!(change(&rows), (3, 3));
        assert_eq!(kinds(&rows).iter().filter(|k| **k == Kind::Sep).count(), 4);
        assert_eq!(rows.last().unwrap().kind, Kind::Sep);
        assert_eq!(rows.last().unwrap().text, "… 2 more edit(s)");
        // Line numbers follow each hunk's own header, not the row count before it.
        let second = rows.iter().find(|r| r.text == "c").unwrap();
        assert_eq!(second.old, Some(20));
        let third = rows.iter().find(|r| r.text == "e").unwrap();
        assert_eq!(third.old, Some(40));
    }

    #[test]
    fn a_diff_against_an_empty_file() {
        // `-0,0` is a file with no lines: every row is an addition, and none of them has an old
        // number to have.
        let text = "@@ -0,0 +1,3 @@\n+one\n+two\n+three\n";
        let rows = parse(text);
        assert_eq!(kinds(&rows), [Kind::Sep, Kind::Add, Kind::Add, Kind::Add]);
        assert!(rows[1..].iter().all(|r| r.old.is_none()));
        assert_eq!(rows[1].new, Some(1));
        assert_eq!(rows[3].new, Some(3));
        assert_eq!(change(&rows), (3, 0));
    }

    #[test]
    fn a_git_preamble_is_not_a_change() {
        // The two file names look exactly like a removed and an added line. Read as changes they
        // add one to each count and put a `--- a/x` row in the middle of the drawing.
        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";
        let rows = parse(text);
        assert_eq!(change(&rows), (1, 1));
        assert!(rows
            .iter()
            .any(|r| r.text == "diff --git a/src/x.rs b/src/x.rs"));
        assert!(rows.iter().any(|r| r.text == "--- a/src/x.rs"));
        assert!(rows
            .iter()
            .any(|r| r.text == "\\ No newline at end of file"));
        assert_eq!(rows.last().unwrap().kind, Kind::Sep);
    }

    #[test]
    fn a_line_that_is_not_a_diff_is_kept_and_not_counted() {
        // A tool that printed something else must not be summarised as "0 added, 0 removed" with
        // the text thrown away: text that is not a diff still reaches the person who asked.
        let rows = parse("the file is not a diff at all\nnor this\n");
        assert_eq!(rows.len(), 2);
        assert!(rows.iter().all(|r| r.kind == Kind::Sep));
        assert_eq!(change(&rows), (0, 0));
    }

    #[test]
    fn a_header_with_a_count_but_no_comma_and_one_with_no_count_both_read() {
        // `@@ -1 +1 @@` is legal when the hunk is a single line, and git writes it.
        let rows = parse("@@ -1 +1 @@\n-old\n+new\n");
        assert_eq!(change(&rows), (1, 1));
        assert_eq!(rows[1].old, Some(1));
        assert_eq!(rows[2].new, Some(1));
    }

    #[test]
    fn a_multibyte_line_does_not_split_inside_a_character() {
        // The marker is one ASCII byte, but the text after it is not: the split has to be on a
        // character boundary or the parse panics.
        let rows = parse("@@ -1,2 +1,2 @@\n-žluťoučký\n+žluťoučký kůň\n same\n");
        assert_eq!(rows[1].text, "žluťoučký");
        assert_eq!(rows[2].text, "žluťoučký kůň");
        assert_eq!(change(&rows), (1, 1));
    }
}