Files
faunosteo/crates/core/src/pdf/compare/run.rs
T

255 lines
7.9 KiB
Rust

//! The command line of the tool (`compare-reports.ts` `main`), without its file system: the
//! arguments, the loop over the entries, what goes to stdout and stderr, the exit code. The
//! caller lists folders and reads files through [`Files`]; a missing or unreadable file is a
//! failed entry, not a crash.
use std::collections::HashSet;
use super::lines::esc;
use super::{CompareOptions, Comparison, Locale, Source, compare_bytes};
use crate::domain::sheet::LoadedSheet;
pub const USAGE: &str = "usage: pnpm report:compare <file.pdf | folder>... [--summary] [--full] [--locale fr|en] [--diff a.pdf b.pdf]";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CliArgs {
pub files: Vec<String>,
pub locale: Locale,
pub full: bool,
pub summary: bool,
pub diff: bool,
}
impl CliArgs {
fn options(&self) -> CompareOptions {
CompareOptions {
locale: self.locale,
full: self.full,
}
}
}
/// `parseArgs`: options anywhere, every other argument an entry; the error is the message
/// the TypeScript threw (printed on stderr, exit 1).
pub fn parse_args(argv: &[String]) -> Result<CliArgs, String> {
let mut args = CliArgs {
files: Vec::new(),
locale: Locale::Fr,
full: false,
summary: false,
diff: false,
};
let mut rest = argv.iter();
while let Some(arg) = rest.next() {
match arg.as_str() {
"--full" => args.full = true,
"--summary" => args.summary = true,
"--diff" => args.diff = true,
"--locale" => {
args.locale = match rest.next().map(String::as_str) {
Some("fr") => Locale::Fr,
Some("en") => Locale::En,
_ => return Err("--locale takes fr or en".to_owned()),
}
}
other if other.starts_with("--") => {
return Err(format!("unknown option {}", esc(other)));
}
_ => args.files.push(arg.clone()),
}
}
Ok(args)
}
/// Why an entry cannot be read, worded as the TypeScript CLI did.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FileFailure {
NotFound,
NotReadable,
NotRegular,
TooLarge,
/// Any other error of the file system, its message.
Other(String),
}
impl FileFailure {
fn reason(&self) -> String {
match self {
Self::NotFound => "file not found".to_owned(),
Self::NotReadable => "file not readable".to_owned(),
Self::NotRegular => "not a regular file".to_owned(),
Self::TooLarge => "file too large".to_owned(),
Self::Other(message) => message.clone(),
}
}
}
/// The file system as the tool uses it. Paths are the caller's: resolved against the folder
/// the command was typed from, printed by their last segment only.
pub trait Files {
/// A folder stands for its PDFs (`.pdf` in any case, sorted); any other argument stays
/// one entry, a missing one included (reported when read).
fn expand(&self, arg: &str) -> Vec<String>;
/// The bytes of one entry: a regular file under the reader's size cap.
fn read(&self, path: &str) -> Result<Vec<u8>, FileFailure>;
}
/// What a run printed and answered.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Run {
pub stdout: String,
pub stderr: String,
pub exit_code: i32,
}
impl Run {
/// `console.log`: the text and a newline.
fn log(&mut self, text: &str) {
self.stdout.push_str(text);
self.stdout.push('\n');
}
fn fail(message: &str) -> Self {
Self {
stdout: String::new(),
stderr: format!("{message}\n"),
exit_code: 1,
}
}
}
/// The last path segment, as `basename` printed it.
fn name_of(path: &str) -> String {
let name = std::path::Path::new(path)
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| path.to_owned());
esc(&name)
}
pub fn render_comparison(name: &str, c: &Comparison) -> Vec<String> {
let mut lines = vec![format!("== {name}")];
lines.extend(c.header.iter().map(|l| format!(" {l}")));
for observation in &c.observations {
for (i, line) in observation.iter().enumerate() {
let indent = if i == 0 { " " } else { " " };
lines.push(format!("{indent}{line}"));
}
}
lines.extend(c.footer.iter().map(|l| format!(" {l}")));
lines
}
pub fn render_summary(name: &str, c: &Comparison) -> String {
let n = c.counts;
let source = match c.source {
Source::V2 => "v2→v3",
Source::V3 => "v3",
};
format!(
"{name} · {source} · {} obs · zones {}/{} unresolved · findings {}/{} unresolved",
n.observations, n.zones, n.unresolved_zones, n.findings, n.unresolved_findings
)
}
/// Lines of A absent from B and lines of B absent from A, in order.
pub fn diff_lines(a: &[String], b: &[String]) -> Vec<String> {
let in_a: HashSet<&String> = a.iter().collect();
let in_b: HashSet<&String> = b.iter().collect();
let mut out: Vec<String> = a
.iter()
.filter(|l| !in_b.contains(l))
.map(|l| format!("- {l}"))
.collect();
out.extend(
b.iter()
.filter(|l| !in_a.contains(l))
.map(|l| format!("+ {l}")),
);
out
}
fn compare_entry(
sheet: &LoadedSheet,
files: &dyn Files,
path: &str,
opts: CompareOptions,
) -> Result<Comparison, String> {
let bytes = files.read(path).map_err(|f| f.reason())?;
compare_bytes(sheet, &bytes, opts).map_err(|f| f.reason())
}
fn print_entry(run: &mut Run, name: &str, c: &Comparison, args: &CliArgs) {
if args.diff {
return;
}
if args.summary {
run.log(&render_summary(name, c));
} else {
let mut lines = render_comparison(name, c);
lines.push(String::new());
run.log(&lines.join("\n"));
}
}
/// Every entry compared and printed, a failure printed as `!! <name>: <reason>`: the
/// comparisons, and how many entries failed.
fn compare_entries(
sheet: &LoadedSheet,
files: &dyn Files,
entries: &[String],
args: &CliArgs,
run: &mut Run,
) -> (Vec<Comparison>, usize) {
let mut results = Vec::new();
let mut failures = 0;
for path in entries {
let name = name_of(path);
match compare_entry(sheet, files, path, args.options()) {
Ok(c) => {
print_entry(run, &name, &c, args);
results.push(c);
}
Err(reason) => {
failures += 1;
run.log(&format!("!! {name}: {}", esc(&reason)));
}
}
}
(results, failures)
}
/// `--diff`: the lines one of the two comparisons has and the other lacks, or that they are
/// identical; nothing when one of the two entries failed.
fn print_diff(run: &mut Run, results: &[Comparison]) {
let [a, b] = results else {
return;
};
let diff = diff_lines(&a.normalized, &b.normalized);
if diff.is_empty() {
run.log("identical v3 content");
} else {
run.log(&diff.join("\n"));
}
}
/// `main`: usage on stderr (exit 1) without an entry or with `--diff` and not two; the
/// entries compared and printed (exit 2 when any failed); the diff of the two printed last.
pub fn run(sheet: &LoadedSheet, argv: &[String], files: &dyn Files) -> Run {
let args = match parse_args(argv) {
Ok(args) => args,
Err(message) => return Run::fail(&message),
};
let entries: Vec<String> = args.files.iter().flat_map(|a| files.expand(a)).collect();
if entries.is_empty() || (args.diff && entries.len() != 2) {
return Run::fail(USAGE);
}
let mut run = Run::default();
let (results, failures) = compare_entries(sheet, files, &entries, &args, &mut run);
if args.diff {
print_diff(&mut run, &results);
}
run.exit_code = if failures > 0 { 2 } else { 0 };
run
}