move-diff 0.2.2

Render a git diff with extra markers for moved and reformatted code
Documentation
//! `move-diff` renders a local git diff with extra markers for moved and
//! reformatted code, so large mechanical refactors are easier to review.
//!
//! It is a drop-in replacement for `git diff`: same argument shape, same
//! behaviour on a clean tree (no output, exit 0).

mod git;

use std::io::IsTerminal;
use std::path::PathBuf;
use std::process::ExitCode;

use anyhow::Result;
use clap::Parser;

use move_diff::annotate_diff;
use move_diff::annotate_diff::MoveGap;

#[derive(Parser)]
#[command(
    name = "move-diff",
    version,
    about = "Render a git diff with extra markers for moved and reformatted code",
    long_about = "Render a git diff with extra markers for moved and reformatted code.\n\n\
                  Markers: '+'/'-' for genuine additions/removals (green/red, as in \
                  `git diff`), '>'/'<' for code that moved away from / arrived at a spot \
                  (cyan/blue), and 'x' for code that was only reformatted in place — \
                  reindented, rewrapped, etc. — with no real content change (magenta).\n\n\
                  Behaves like `git diff`: with no reference it diffs the working tree \
                  against the index, and a clean tree produces no output and a zero \
                  exit status."
)]
struct Args {
    /// Git reference to diff against (commit, branch, tag, range, …). Omit it
    /// to diff the working tree against the index, like bare `git diff`.
    reference: Option<String>,

    /// Repository directory (defaults to current directory)
    #[arg(short = 'C', long = "dir", default_value = ".")]
    dir: PathBuf,

    /// How many real content changes are tolerated inside an
    /// otherwise-moved block before move detection gives up on that
    /// block (lines beyond this fall back to plain +/-). Accepts an
    /// absolute count (e.g. `2`), a fraction (e.g. `0.1`), or a
    /// percentage (e.g. `10%`) of the remaining block length in each
    /// direction.
    #[arg(long, default_value = "10%")]
    max_move_gap: MoveGap,

    /// Disable colored output (also respects $NO_COLOR and non-tty stdout)
    #[arg(long)]
    no_color: bool,
}

fn main() -> ExitCode {
    let args = Args::parse();

    // Match `git diff`'s exit-status contract: 0 on success (including an
    // empty diff), 128 for a fatal git error such as an unknown revision.
    let diff = match git::local_diff(&args.dir, args.reference.as_deref()) {
        Ok(diff) => diff,
        Err(e) => {
            eprintln!("move-diff: {e:#}");
            return ExitCode::from(128);
        }
    };

    // A clean tree prints nothing and succeeds, exactly as `git diff` does.
    if diff.is_empty() {
        return ExitCode::SUCCESS;
    }

    let color =
        !args.no_color && std::env::var_os("NO_COLOR").is_none() && std::io::stdout().is_terminal();

    match render(&diff, args.max_move_gap, color) {
        Ok(()) => ExitCode::SUCCESS,
        Err(e) => {
            eprintln!("move-diff: {e:#}");
            ExitCode::FAILURE
        }
    }
}

/// Render `diff`, exiting quietly on a closed pipe.
///
/// `git diff | head` must not spew a Rust panic when the reader goes away, so
/// a broken pipe is treated as a normal end-of-output.
fn render(diff: &str, max_move_gap: MoveGap, color: bool) -> Result<()> {
    use std::io::Write;

    let rendered = annotate_diff::render(diff, max_move_gap, color)?;

    let stdout = std::io::stdout();
    let mut stdout = stdout.lock();
    match stdout
        .write_all(rendered.as_bytes())
        .and_then(|()| stdout.flush())
    {
        Ok(()) => Ok(()),
        Err(e) if e.kind() == std::io::ErrorKind::BrokenPipe => Ok(()),
        Err(e) => Err(e.into()),
    }
}

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

    #[test]
    fn parses_a_bare_reference() {
        let args = Args::try_parse_from(["move-diff", "main"]).unwrap();
        assert_eq!(args.reference.as_deref(), Some("main"));
        assert_eq!(args.dir, PathBuf::from("."));
        assert!(!args.no_color);
    }

    #[test]
    fn reference_is_optional() {
        let args = Args::try_parse_from(["move-diff"]).unwrap();
        assert_eq!(args.reference, None);
    }

    #[test]
    fn range_is_a_single_positional() {
        // Ranges stay in one argv token and are handed to git verbatim, so
        // `move-diff main...feature` needs no special casing.
        let args = Args::try_parse_from(["move-diff", "main...feature"]).unwrap();
        assert_eq!(args.reference.as_deref(), Some("main...feature"));
    }

    #[test]
    fn dir_and_no_color_flags() {
        let args = Args::try_parse_from(["move-diff", "-C", "/tmp", "--no-color"]).unwrap();
        assert_eq!(args.dir, PathBuf::from("/tmp"));
        assert!(args.no_color);
    }

    #[test]
    fn max_move_gap_defaults_to_ten_percent() {
        assert_eq!(
            Args::try_parse_from(["move-diff"]).unwrap().max_move_gap,
            MoveGap::Relative(0.10)
        );
    }

    #[test]
    fn max_move_gap_accepts_absolute_and_relative_forms() {
        assert_eq!(
            Args::try_parse_from(["move-diff", "--max-move-gap", "2"])
                .unwrap()
                .max_move_gap,
            MoveGap::Absolute(2)
        );
        assert_eq!(
            Args::try_parse_from(["move-diff", "--max-move-gap", "0.25"])
                .unwrap()
                .max_move_gap,
            MoveGap::Relative(0.25)
        );
    }

    #[test]
    fn invalid_max_move_gap_is_rejected_by_the_parser() {
        assert!(Args::try_parse_from(["move-diff", "--max-move-gap", "abc"]).is_err());
    }

    #[test]
    fn empty_diff_produces_no_output() {
        // `render` writes straight to stdout; with an empty diff it must write
        // nothing and succeed, mirroring `git diff` on a clean tree.
        assert!(render("", MoveGap::Relative(0.10), false).is_ok());
    }
}