move-diff 0.3.1

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.
///
/// `args` are appended to the `git diff --no-color` invocation, and git keeps
/// complete control over how each token is interpreted, exactly as if it had
/// been typed in place of them. With none, it diffs the working tree against
/// the index; with a reference it diffs relative to that; with pathspecs (with
/// or without a reference) it limits the diff to those paths. No `--`
/// separator is inserted, and one the user typed is preserved, so git's own
/// revision-vs-path disambiguation behaves identically to `git diff`.
///
/// `--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, args: &[String]) -> Result<String> {
    let dir_str = dir.to_string_lossy();
    let mut git_args = vec!["-C", dir_str.as_ref(), "diff", "--no-color"];
    git_args.extend(args.iter().map(String::as_str));

    cmd("git", git_args).read().with_context(|| {
        let tail = if args.is_empty() {
            String::new()
        } else {
            format!(" {}", args.join(" "))
        };
        format!("git diff{tail} failed")
    })
}

#[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, &[]);
        assert!(diff.is_ok());
    }

    #[test]
    fn error_message_reproduces_the_git_command() {
        // The context must read like the git command that failed, including
        // any forwarded positionals, so a bad invocation is obvious.
        let err = local_diff(
            Path::new("."),
            &["no-such-ref-abcdef".to_string(), "README.md".to_string()],
        )
        .unwrap_err();
        assert!(format!("{err:#}").contains("git diff no-such-ref-abcdef README.md failed"));
    }

    #[test]
    fn positionals_are_forwarded() {
        // `HEAD <path>` limits to that path, like `git diff HEAD <path>`.
        let diff = local_diff(
            Path::new("."),
            &["HEAD".to_string(), "Cargo.toml".to_string()],
        )
        .unwrap();
        assert!(diff.is_empty() || diff.contains("Cargo.toml"));

        // A nonexistent `HEAD <path>` fails with git's own "ambiguous
        // argument" message naming our forwarded arg — proof it reached git.
        let err = local_diff(
            Path::new("."),
            &["HEAD".to_string(), "no-such-file-abcdef".to_string()],
        )
        .unwrap_err();
        assert!(format!("{err:#}").contains("no-such-file-abcdef"));
    }
}