move-diff 0.3.1

Render a git diff with extra markers for moved and reformatted code
Documentation
//! Regenerates the colored README screenshot straight from this crate's own
//! renderer.
//!
//! GitLab's markdown sanitizer strips the `style` attribute and does not
//! interpret ANSI escapes in fenced code blocks, so there is no way to get
//! `move-diff`'s five marker colors into a rendered `.md` file except as
//! pixels. This binary renders a real diff with [`annotate_diff::render`]
//! (the exact function `move-diff` itself calls) and turns the resulting
//! ANSI text into an SVG, so the picture in the README can never drift from
//! what the tool actually outputs — regenerating it is just rerunning this
//! binary on the same fixture.
//!
//! Not part of the published crate: see the `svg-gen` feature in
//! `Cargo.toml`.
//!
//! Usage: `move-diff-svg <input.diff> <output.svg>`

use std::fmt::Write as _;

use anyhow::{Context, Result, bail};
use move_diff::annotate_diff::{self, MoveGap};

const FONT_SIZE: f64 = 13.0;
const CHAR_WIDTH: f64 = FONT_SIZE * 0.6;
const LINE_HEIGHT: f64 = 19.0;
const PADDING: f64 = 14.0;

fn main() -> Result<()> {
    let mut args = std::env::args().skip(1);
    let (Some(input), Some(output)) = (args.next(), args.next()) else {
        bail!("usage: move-diff-svg <input.diff> <output.svg>");
    };

    let diff = std::fs::read_to_string(&input).with_context(|| format!("reading {input}"))?;
    let rendered = annotate_diff::render(&diff, MoveGap::Relative(0.10), true)
        .with_context(|| format!("annotating {input}"))?;

    let svg = render_svg(&rendered);
    std::fs::write(&output, svg).with_context(|| format!("writing {output}"))?;
    Ok(())
}

/// One line of the ANSI-colored output: a marker's whole line is wrapped in
/// a single `\x1b[{code}m ... \x1b[0m` (see `annotate_diff::render_changed_line`),
/// so each line carries at most one color — no inline-run parsing needed.
fn parse_line(line: &str) -> (Option<&str>, &str) {
    if let Some(rest) = line.strip_prefix("\x1b[")
        && let Some(end) = rest.find('m')
    {
        let code = &rest[..end];
        let content = rest[end + 1..]
            .strip_suffix("\x1b[0m")
            .unwrap_or(&rest[end + 1..]);
        return (Some(code), content);
    }
    (None, line)
}

fn css_class(code: Option<&str>) -> &'static str {
    match code {
        Some("31") => "c31",
        Some("32") => "c32",
        Some("34") => "c34",
        Some("35") => "c35",
        Some("36") => "c36",
        _ => "fg",
    }
}

fn xml_escape(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            _ => out.push(c),
        }
    }
    out
}

fn render_svg(rendered: &str) -> String {
    let lines: Vec<(Option<&str>, &str)> = rendered.lines().map(parse_line).collect();
    let max_chars = lines
        .iter()
        .map(|(_, text)| text.chars().count())
        .max()
        .unwrap_or(0);
    let width = PADDING * 2.0 + max_chars as f64 * CHAR_WIDTH;
    let height = PADDING * 2.0 + lines.len() as f64 * LINE_HEIGHT;

    let mut out = String::new();
    let _ = writeln!(
        out,
        r#"<svg xmlns="http://www.w3.org/2000/svg" width="{width:.0}" height="{height:.0}" viewBox="0 0 {width:.0} {height:.0}" font-family="ui-monospace, SFMono-Regular, Menlo, Consolas, monospace" font-size="{FONT_SIZE}">"#
    );
    out.push_str(
        r#"  <style>
    .bg { fill: #ffffff; }
    .fg { fill: #1f2328; }
    .c31 { fill: #cf222e; } /* remove */
    .c32 { fill: #1a7f37; } /* add */
    .c34 { fill: #0969da; } /* moved in */
    .c35 { fill: #8250df; } /* reformat */
    .c36 { fill: #1b7c83; } /* moved out */
    @media (prefers-color-scheme: dark) {
      .bg { fill: #0d1117; }
      .fg { fill: #c9d1d9; }
      .c31 { fill: #ff7b72; }
      .c32 { fill: #3fb950; }
      .c34 { fill: #58a6ff; }
      .c35 { fill: #d2a8ff; }
      .c36 { fill: #39c5cf; }
    }
  </style>
"#,
    );
    let _ = writeln!(
        out,
        r#"  <rect class="bg" x="0" y="0" width="{width:.0}" height="{height:.0}" />"#
    );

    for (i, (code, text)) in lines.iter().enumerate() {
        if text.is_empty() {
            continue;
        }
        let y = PADDING + FONT_SIZE + i as f64 * LINE_HEIGHT;
        let class = css_class(*code);
        let _ = writeln!(
            out,
            r#"  <text x="{PADDING}" y="{y:.1}" xml:space="preserve"><tspan class="{class}">{}</tspan></text>"#,
            xml_escape(text)
        );
    }

    out.push_str("</svg>\n");
    out
}