move-diff 0.1.0

Render a git diff with extra markers for moved and reformatted code
Documentation
//! The one piece of git plumbing `move-diff` needs: producing a diff.
//!
//! Everything else this crate does works on an already-materialised unified
//! diff as text, so there's deliberately no remote-URL parsing, branch
//! validation, or provider detection here.

use std::path::Path;

use anyhow::{Context, Result};
use duct::cmd;

/// Run `git diff` in `dir` and return the output as a string. With
/// `reference`, behaves like `git diff <reference>` (changes relative to that
/// commit/branch/tag/range); without one, behaves like plain `git diff`
/// (unstaged changes in the working tree relative to the index), matching the
/// git CLI's own no-argument default.
///
/// `--no-color` is passed through to git as well as being handled on our side:
/// if the user's git config forces color on (`color.diff = always`), the
/// captured text would otherwise arrive pre-wrapped in ANSI escapes and every
/// hunk line would parse as garbage.
pub fn local_diff(dir: &Path, reference: Option<&str>) -> Result<String> {
    let dir_str = dir.to_string_lossy();
    let mut args = vec!["-C", dir_str.as_ref(), "diff", "--no-color"];
    if let Some(reference) = reference {
        args.push(reference);
    }

    cmd("git", args).read().with_context(|| match reference {
        Some(reference) => format!("git diff {reference} failed"),
        None => "git diff failed".to_string(),
    })
}

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

    #[test]
    fn missing_trailing_newline_is_tolerated() {
        // `duct`'s `.read()` behaves like shell `$()` and strips the trailing
        // newline. `annotate_diff::render` restores it before parsing, so a
        // caller must be able to hand us a diff with no trailing newline
        // without it being an error here.
        let dir = Path::new(".");
        let diff = local_diff(dir, None);
        assert!(diff.is_ok());
    }

    #[test]
    fn nonexistent_reference_is_an_error() {
        let err = local_diff(Path::new("."), Some("no-such-ref-abcdef")).unwrap_err();
        assert!(format!("{err:#}").contains("git diff no-such-ref-abcdef failed"));
    }
}