feat(domain): R4.7 report-compare on the core: pdf::compare (feature cli, pure lines, runner over a Files trait), report-compare binary on the seed sheet, pnpm report:compare switched to it; O10 230 rows (158 exact, 72 declared A.3 closed lines), 11 cases as ledger targets, binary spawned; rust-check on cli

This commit is contained in:
bchanot committed 2026-10-19 11:13:35 +02:00
1 parent 264c5fa3fc
commit 02ebf05195
17 files changed
+1598 -24

No files matched your search

+160
View File
@@ -0,0 +1,160 @@
//! `pnpm report:compare` (R4.7, plan §B.1.7): the archive check tool on the core. Reads the
//! report attached to one or more Faunosteo PDFs and prints it next to its v3 reading on the
//! reference sheet (the seed draft of the repository).
//!
//! report-compare <file.pdf | folder>... [--summary] [--full] [--locale fr|en]
//! [--diff a.pdf b.pdf]
//!
//! Paths are typed from the folder pnpm was run in (`INIT_CWD`), else the current one. The
//! lines are [`faunosteo_core::pdf::compare`]'s; this file only reads the seed and the
//! entries, and is the one file of the crate allowed the file system and the environment.
#![allow(clippy::disallowed_methods)]
use std::collections::HashMap;
use std::io::{self, ErrorKind, Write};
use std::path::{Path, PathBuf};
use std::{env, fs, process};
use serde::Deserialize;
use faunosteo_core::domain::archive::SheetStatus;
use faunosteo_core::domain::sheet::loaded::BundledRef;
use faunosteo_core::domain::sheet::{BundledSheetData, LoadedSheet};
use faunosteo_core::pdf::compare::{self, FileFailure, Files};
use faunosteo_core::pdf::read::MAX_PDF_BYTES;
/// The seed of the reference sheet, from this crate's manifest folder.
const SEED_DIR: &str = concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../supabase/seed/anatomical-sheets/equine/draft"
);
/// `sheet-ref.json` of the seed.
#[derive(Deserialize)]
struct SeedRef {
sheet_id: String,
version_id: Option<String>,
document_sha256: String,
schema_version: f64,
species_id: String,
}
fn seed_json<T: for<'de> Deserialize<'de>>(name: &str) -> Result<T, String> {
let path = Path::new(SEED_DIR).join(name);
let text = fs::read_to_string(&path).map_err(|e| format!("{}: {e}", path.display()))?;
serde_json::from_str(&text).map_err(|e| format!("{}: {e}", path.display()))
}
/// The seed document and migration map, indexed; no drawing (the comparison needs none).
fn load_sheet() -> Result<LoadedSheet, String> {
let reference: SeedRef = seed_json("sheet-ref.json")?;
let schema_version = faunosteo_core::domain::js::JsInt::new(reference.schema_version)
.ok_or_else(|| "sheet-ref.json: schema_version is not an integer".to_owned())?;
let data = BundledSheetData {
status: SheetStatus::Draft,
reference: BundledRef {
sheet_id: reference.sheet_id,
version_id: reference.version_id,
document_sha256: reference.document_sha256,
schema_version,
species_id: reference.species_id,
},
document: seed_json("document.json")?,
migration_map: seed_json("report-migration-map.json")?,
assets: HashMap::new(),
asset_hashes: HashMap::new(),
};
LoadedSheet::from_bundle(data).map_err(|e| format!("reference sheet: {e:?}"))
}
/// The file system behind the tool: entries resolved against `base`.
struct Disk {
base: PathBuf,
}
fn is_pdf_name(name: &str) -> bool {
name.to_lowercase().ends_with(".pdf")
}
fn failure_of(error: &io::Error) -> FileFailure {
match error.kind() {
ErrorKind::NotFound => FileFailure::NotFound,
ErrorKind::PermissionDenied => FileFailure::NotReadable,
_ => FileFailure::Other(error.to_string()),
}
}
impl Disk {
fn resolve(&self, arg: &str) -> PathBuf {
self.base.join(arg)
}
/// The `.pdf` entries of a folder, by name.
fn pdfs_of(folder: &Path) -> Vec<String> {
let Ok(entries) = fs::read_dir(folder) else {
return vec![folder.to_string_lossy().into_owned()];
};
let mut names: Vec<String> = entries
.filter_map(Result::ok)
.map(|e| e.file_name().to_string_lossy().into_owned())
.filter(|n| is_pdf_name(n))
.collect();
names.sort();
names
.into_iter()
.map(|n| folder.join(n).to_string_lossy().into_owned())
.collect()
}
}
impl Files for Disk {
fn expand(&self, arg: &str) -> Vec<String> {
let path = self.resolve(arg);
match fs::metadata(&path) {
Ok(meta) if meta.is_dir() => Self::pdfs_of(&path),
// A missing entry is reported when read, as a failed entry.
_ => vec![path.to_string_lossy().into_owned()],
}
}
fn read(&self, path: &str) -> Result<Vec<u8>, FileFailure> {
let meta = fs::metadata(path).map_err(|e| failure_of(&e))?;
if !meta.is_file() {
return Err(FileFailure::NotRegular);
}
if meta.len() > MAX_PDF_BYTES as u64 {
return Err(FileFailure::TooLarge);
}
fs::read(path).map_err(|e| failure_of(&e))
}
}
fn base_dir() -> PathBuf {
env::var_os("INIT_CWD")
.map(PathBuf::from)
.or_else(|| env::current_dir().ok())
.unwrap_or_default()
}
fn main() {
let argv: Vec<String> = env::args_os()
.skip(1)
.map(|a| a.to_string_lossy().into_owned())
.collect();
let sheet = match load_sheet() {
Ok(sheet) => sheet,
Err(message) => {
eprintln!("{message}");
process::exit(1);
}
};
let disk = Disk { base: base_dir() };
let run = compare::run(&sheet, &argv, &disk);
let written = io::stdout()
.write_all(run.stdout.as_bytes())
.and_then(|()| io::stderr().write_all(run.stderr.as_bytes()));
if written.is_err() {
process::exit(1);
}
process::exit(run.exit_code);
}