resumark 0.1.1

ATS-safe resume typesetting from Markdown — extraction order as a verified contract
Documentation
use std::path::PathBuf;
use std::process::ExitCode;

use anyhow::{Context, Result};
use clap::Parser;

use resumark::fit::MIN_SCALE;
use resumark::fonts::FontBook;
use resumark::layout::PageGeom;
use resumark::verify::{Mode, OrderCheck, verify};
use resumark::{A4, LETTER, parse, render_bytes};

/// Render a Markdown resume to an ATS-safe PDF.
///
/// The text layer of the output is a contract: it reads in the document's
/// declared order, and --verify proves it by round-tripping the PDF through
/// pdftotext.
#[derive(Parser)]
#[command(name = "resumark", version, about)]
struct Cli {
    /// Markdown source file
    #[arg(default_value = "resume.md")]
    source: PathBuf,

    /// Output PDF path (default: source with .pdf extension)
    #[arg(short, long)]
    out: Option<PathBuf>,

    /// Directory holding the five Montserrat TTFs (default: fonts embedded
    /// in the binary)
    #[arg(long)]
    fonts: Option<PathBuf>,

    /// Max pages before the auto-fit loop starts shrinking type
    #[arg(long, default_value_t = 1)]
    pages: usize,

    /// Fixed type scale; skips auto-fit
    #[arg(long)]
    scale: Option<f32>,

    /// A4 instead of US Letter
    #[arg(long)]
    a4: bool,

    /// Round-trip the output through pdftotext and assert extraction order
    #[arg(long)]
    verify: bool,

    /// Machine-readable JSON report on stdout (implies no human output)
    #[arg(long)]
    json: bool,
}

fn main() -> ExitCode {
    match run() {
        Ok(code) => code,
        Err(e) => {
            // Keep the error machine-readable for --json callers.
            if std::env::args().any(|a| a == "--json") {
                println!("{}", serde_json::json!({ "error": format!("{e:#}") }));
            }
            eprintln!("error: {e:#}");
            ExitCode::FAILURE
        }
    }
}

fn run() -> Result<ExitCode> {
    let cli = Cli::parse();

    let book = match &cli.fonts {
        Some(dir) => FontBook::from_dir(dir).context("loading fonts")?,
        None => FontBook::embedded()?,
    };
    let md = std::fs::read_to_string(&cli.source)
        .with_context(|| format!("reading {}", cli.source.display()))?;
    let geom = PageGeom::new(if cli.a4 { A4 } else { LETTER });

    let (bytes, layout) = render_bytes(&md, &book, geom, cli.pages.max(1), cli.scale)?;
    let out = cli
        .out
        .clone()
        .unwrap_or_else(|| cli.source.with_extension("pdf"));
    std::fs::write(&out, &bytes).with_context(|| format!("writing {}", out.display()))?;

    let doc = parse(&md);
    let page_budget = cli.pages.max(1);
    let fits = !layout.overflow && layout.pages.len() <= page_budget;
    let mut warnings: Vec<String> = Vec::new();
    if doc.name.is_empty() && doc.sections.is_empty() {
        warnings.push(
            "parsed document has no name and no sections; check the source against the dialect"
                .to_string(),
        );
    }
    if !fits {
        if cli.scale.is_some() {
            warnings.push(format!(
                "content does not fit {page_budget} page(s) at fixed scale {:.2}",
                layout.scale
            ));
        } else {
            warnings.push(format!(
                "content is too long even at minimum scale {MIN_SCALE}; cut a bullet"
            ));
        }
    }
    if layout.overflow_x {
        warnings.push(
            "a line is wider than its column (unbreakable token); text may run past the page edge"
                .to_string(),
        );
    }
    for page in &layout.pages {
        for t in &page.texts {
            for c in book.missing_chars(t.role, &t.text) {
                let w = format!(
                    "'{c}' (U+{:04X}) is not in the font; it will render as a box",
                    c as u32
                );
                if !warnings.contains(&w) {
                    warnings.push(w);
                }
            }
        }
    }

    let verification = if cli.verify {
        match verify(&out, &doc) {
            Some(pair) => Some(pair),
            None => {
                warnings.push(
                    "pdftotext not found; extraction-order verification skipped \
                     (install poppler)"
                        .to_string(),
                );
                None
            }
        }
    } else {
        None
    };

    let verify_failed = verification
        .as_ref()
        .map(|(raw, reading)| !raw.ok || !reading.ok)
        .unwrap_or(false);

    if cli.json {
        let report = serde_json::json!({
            "out": out.display().to_string(),
            "pages": layout.pages.len(),
            "scale": ((layout.scale as f64) * 100.0).round() / 100.0,
            "fits": fits,
            "warnings": warnings,
            "verify": verification.as_ref().map(|(raw, reading)| {
                serde_json::json!({
                    "raw": check_json(raw),
                    "reading": check_json(reading),
                    "ok": raw.ok && reading.ok,
                })
            }),
        });
        println!("{}", serde_json::to_string_pretty(&report)?);
    } else {
        println!(
            "wrote {} ({} page{}, scale {:.2})",
            out.display(),
            layout.pages.len(),
            if layout.pages.len() == 1 { "" } else { "s" },
            layout.scale
        );
        for w in &warnings {
            eprintln!("warning: {w}");
        }
        if let Some((raw, reading)) = &verification {
            print_check(raw);
            print_check(reading);
        }
    }

    Ok(if verify_failed {
        ExitCode::from(2)
    } else {
        ExitCode::SUCCESS
    })
}

fn mode_name(mode: Mode) -> &'static str {
    match mode {
        Mode::Raw => "stream order (pdftotext -raw)",
        Mode::Reading => "reading order (pdftotext)",
    }
}

fn print_check(c: &OrderCheck) {
    if c.ok {
        println!(
            "verify: {} OK — {}/{} strings in declared order",
            mode_name(c.mode),
            c.matched,
            c.total
        );
    } else {
        let miss = c.first_miss.as_ref().unwrap();
        println!(
            "verify: {} FAILED at {}/{} — {} \"{}\" not found in order",
            mode_name(c.mode),
            c.matched,
            c.total,
            miss.what,
            miss.text
        );
    }
}

fn check_json(c: &OrderCheck) -> serde_json::Value {
    serde_json::json!({
        "ok": c.ok,
        "matched": c.matched,
        "total": c.total,
        "first_miss": c.first_miss.as_ref().map(|m| {
            serde_json::json!({ "what": m.what, "text": m.text })
        }),
    })
}