move-diff 0.3.1

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. Paths may be given after the reference (or alone) to \
                  limit the diff, exactly as with `git diff`."
)]
struct Args {
    /// Positionals handed to `git diff` unchanged: git references, pathspecs,
    /// ranges — whatever that invocation accepts. git resolves the ambiguity
    /// itself, so `move-diff HEAD README.md` and `move-diff README.md` behave
    /// exactly like their `git diff` equivalents, and with no args it diffs
    /// the working tree against the index.
    args: Vec<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.args) {
        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 positionals_are_collected_verbatim() {
        // `move-diff HEAD README.md` behaves like `git diff HEAD README.md`.
        let args = Args::try_parse_from(["move-diff", "HEAD", "README.md"]).unwrap();
        assert_eq!(args.args, vec!["HEAD", "README.md"]);
        assert_eq!(args.dir, PathBuf::from("."));
        assert!(!args.no_color);
    }

    #[test]
    fn args_are_optional() {
        let args = Args::try_parse_from(["move-diff"]).unwrap();
        assert!(args.args.is_empty());
    }

    #[test]
    fn ranges_stay_verbatim() {
        // 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.args, vec!["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 a_lone_path_is_a_positional() {
        // As with git, a lone path that isn't a ref resolves to a pathspec;
        // git makes that call, not us.
        let args = Args::try_parse_from(["move-diff", "README.md"]).unwrap();
        assert_eq!(args.args, vec!["README.md"]);
    }

    #[test]
    fn leading_double_dash_is_forwarded() {
        // clap normally swallows `--`, but a user typing it expects the tokens
        // after it to reach git, e.g. to disambiguate a `-`-prefixed path.
        // `move-diff -- -weird` must arrive as "["-weird"]".
        let args = Args::try_parse_from(["move-diff", "--", "-weird"]).unwrap();
        assert_eq!(args.args, vec!["-weird"]);
    }

    #[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());
    }
}