move-diff 0.3.1

Render a git diff with extra markers for moved and reformatted code
Documentation
//! Shared helpers for safely parsing unified diffs with the `patch` crate.
//!
//! The `patch` crate uses an internal `assert!` rather than returning `Err`
//! when its parser leaves unconsumed input — which happens for file entries
//! it doesn't model at all (binary file diffs, pure mode changes, pure
//! renames with no hunks). [`parse_patches_safely`] catches that panic and
//! turns it into a plain error message.
//!
//! [`split_file_diffs`] splits a multi-file `git diff` into one chunk per
//! file (on `diff --git ` boundaries) so callers can parse each file
//! independently: one unparseable file (binary, mode-only, pure rename)
//! then only costs that file, instead of discarding the whole diff.

use patch::Patch;

/// Splits a multi-file unified diff (as produced by `git diff`) into one
/// chunk per file, each starting at its `diff --git ` header line and
/// running up to (but not including) the next one.
///
/// If `diff_text` contains no `diff --git ` header at all — e.g. a bare
/// `---`/`+++`/`@@` hunk with no git-style preamble, as used by some
/// callers/tests — the whole input is returned as a single chunk.
pub fn split_file_diffs(diff_text: &str) -> Vec<&str> {
    if diff_text.is_empty() {
        return Vec::new();
    }

    let mut starts: Vec<usize> = diff_text
        .match_indices("diff --git ")
        .map(|(idx, _)| idx)
        .filter(|&idx| idx == 0 || diff_text.as_bytes()[idx - 1] == b'\n')
        .collect();
    if starts.first() != Some(&0) {
        starts.insert(0, 0);
    }

    let mut chunks = Vec::with_capacity(starts.len());
    for (i, &start) in starts.iter().enumerate() {
        let end = starts.get(i + 1).copied().unwrap_or(diff_text.len());
        if end > start {
            chunks.push(&diff_text[start..end]);
        }
    }
    chunks
}

/// Parses `diff_text` with `patch::Patch::from_multiple`, converting both
/// `Err` results *and* panics into a plain error message.
///
/// Catching the panic here means a parser limitation degrades to "skip this
/// chunk" for whoever's calling this, instead of crashing the whole
/// command. Deliberately does *not* touch the global panic hook (that
/// would race with concurrent calls, e.g. from tests running in parallel);
/// a panic here still prints its default backtrace to stderr, which is an
/// acceptable amount of noise for a caught-and-recovered error.
pub fn parse_patches_safely(diff_text: &str) -> Result<Vec<Patch<'_>>, String> {
    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        Patch::from_multiple(diff_text)
    }));

    match result {
        Ok(Ok(patches)) => Ok(patches),
        Ok(Err(e)) => Err(format!("failed to parse diff: {e}")),
        Err(_) => Err("diff parser panicked on unexpected input".to_string()),
    }
}

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

    #[test]
    fn split_single_file_without_git_header_is_one_chunk() {
        let diff = "--- a/f\n+++ b/f\n@@ -1,1 +1,1 @@\n-old\n+new\n";
        assert_eq!(split_file_diffs(diff), vec![diff]);
    }

    #[test]
    fn split_multiple_git_style_files() {
        let diff = concat!(
            "diff --git a/f1 b/f1\n",
            "index 111..222 100644\n",
            "--- a/f1\n",
            "+++ b/f1\n",
            "@@ -1,1 +1,1 @@\n",
            "-old\n",
            "+new\n",
            "diff --git a/f2 b/f2\n",
            "index 333..444 100644\n",
            "--- a/f2\n",
            "+++ b/f2\n",
            "@@ -1,1 +1,1 @@\n",
            "-foo\n",
            "+bar\n",
        );
        let chunks = split_file_diffs(diff);
        assert_eq!(chunks.len(), 2);
        assert!(chunks[0].starts_with("diff --git a/f1 b/f1\n"));
        assert!(chunks[0].ends_with("+new\n"));
        assert!(chunks[1].starts_with("diff --git a/f2 b/f2\n"));
        assert!(chunks[1].ends_with("+bar\n"));
    }

    #[test]
    fn split_empty_input() {
        assert_eq!(split_file_diffs(""), Vec::<&str>::new());
    }

    #[test]
    fn parse_patches_safely_returns_err_on_ordinary_parse_failure() {
        let not_a_diff = "this is not a unified diff at all\njust some text\n";
        assert!(parse_patches_safely(not_a_diff).is_err());
    }

    #[test]
    fn parse_patches_safely_catches_parser_panic_on_binary_file_entry() {
        // No `diff --git` separator, so this is parsed as a single chunk:
        // a normal hunk immediately followed by a `Binary files ... differ`
        // marker leaves unconsumed input for the `patch` crate's parser,
        // which panics via an internal `assert!` instead of returning
        // `Err`. This is the exact failure `parse_patches_safely` exists
        // to recover from.
        let diff = concat!(
            "--- a/f\n+++ b/f\n@@ -1,1 +1,1 @@\n-old\n+new\n",
            "Binary files a/img.png and b/img.png differ\n",
        );
        let err = parse_patches_safely(diff).unwrap_err();
        assert_eq!(err, "diff parser panicked on unexpected input");
    }

    #[test]
    fn parse_patches_safely_catches_parser_panic_on_mode_change_entry() {
        // Same shape as the binary-file case above but for a mode-only
        // change glued onto a normal hunk with no `diff --git` separator
        // between them.
        let diff = concat!(
            "--- a/f\n+++ b/f\n@@ -1,1 +1,1 @@\n-old\n+new\n",
            "old mode 100644\nnew mode 100755\n",
        );
        let err = parse_patches_safely(diff).unwrap_err();
        assert_eq!(err, "diff parser panicked on unexpected input");
    }

    #[test]
    fn parse_patches_safely_parses_normal_diff() {
        let diff = "--- a/f\n+++ b/f\n@@ -1,1 +1,1 @@\n-old\n+new\n";
        let patches = parse_patches_safely(diff).unwrap();
        assert_eq!(patches.len(), 1);
    }
}