Files
pdfcraft/apps/pdfcraft-cli/src/batch.rs
T
eliets2andeliets2 1f26293482 Save per-file batch log with step status and failure reasons (#6519)
* Save per-file batch log with step status and failure reasons

Users need an honest per-file record after a batch run instead of only opaque JSON, so a failing file and its reason are not lost.

Add a plain-text per-file log to the batch result and an optional CLI log path that writes one section per file with step status, output name and failure reason plus final counts, annotating step errors with the step name.

Test: batch_log_names_failed_file_step_and_reason failed before the change and passes after.

* Address review for pull request 6519

* Batch log: escape backslashes, wire the CLI log option

* Compare the escaped output path in the batch log test

* Address review for pull request 6519

* Repair review branch integration

* Format the files this pull request changes

* Repair review branch integration

* Repair review branch integration

* Keep dry-run output names clear of files that already exist

* Give the dry-run log test its own output folder

* Address review for pull request 6519

* Format the files this pull request changes

* Repair review branch integration

* Tighten the change after a final review

* Tighten the change after a final review

* Repair review branch integration

* Address review for pull request 6519

* Format the files this pull request changes

* Address review for pull request 6519

* Repair review branch integration

* Address review for pull request 6519

* Format the files this pull request changes

* Repair review branch integration

* Address review for pull request 6519

* Format the files this pull request changes

* Address remaining review requests

* Tighten the change after a final review

---------

Co-authored-by: eliets2 <[email protected]>
2026-12-03 15:39:04 +01:00

249 lines
11 KiB
Rust

//! Friendly flags for the same folder-job tool exposed by `run` and MCP.
use serde_json::json;
use std::path::{Path, PathBuf};
use crate::{CliError, OptionSpec, automation, flag, print_output, validate_options};
const OPTIONS: &[OptionSpec] = &[
OptionSpec { name: "--root", takes_value: true },
OptionSpec { name: "--out-dir", takes_value: true },
OptionSpec { name: "--steps", takes_value: true },
OptionSpec { name: "--recursive", takes_value: false },
OptionSpec { name: "--stop-on-error", takes_value: false },
OptionSpec { name: "--ppi", takes_value: true },
OptionSpec { name: "--quality", takes_value: true },
OptionSpec { name: "--dpi", takes_value: true },
OptionSpec { name: "--language", takes_value: true },
OptionSpec { name: "--ocr-all-pages", takes_value: false },
OptionSpec { name: "--log", takes_value: true },
OptionSpec { name: "--dry-run", takes_value: false },
];
pub(super) fn run(args: &[String]) -> Result<(), CliError> {
validate_options("batch", args, OPTIONS)?;
let mut paths = Vec::new();
let mut seen = std::collections::HashSet::new();
let mut i = 0;
while let Some(arg) = args.get(i) {
if let Some(spec) = OPTIONS.iter().find(|s| s.name == arg) {
if !seen.insert(spec.name) {
return Err(format!("batch: {} may only be supplied once", spec.name).into());
}
if spec.takes_value {
if args.get(i + 1).is_none_or(|v| v.is_empty() || v.starts_with("--")) {
return Err(format!("batch: {} needs a value", spec.name).into());
}
i += 1;
}
} else {
paths.push(arg);
}
i += 1;
}
let steps: Vec<_> = flag(args, "--steps").ok_or("batch: missing --steps (convert, ocr, optimize)")?.split(',').collect();
let out = flag(args, "--out-dir").ok_or("batch: missing --out-dir")?;
let mut params = json!({"paths":paths,"steps":steps,"out_dir":out,"recursive":seen.contains("--recursive"),"stop_on_error":seen.contains("--stop-on-error"),"dry_run":seen.contains("--dry-run")});
for (option, key) in [("--ppi", "ppi"), ("--quality", "quality"), ("--dpi", "dpi")] {
if let Some(v) = flag(args, option) {
params[key] = serde_json::from_str(v).map_err(|_| format!("batch: {option} needs a number"))?;
}
}
if let Some(lang) = flag(args, "--language") {
params["language"] = json!(lang);
}
if seen.contains("--ocr-all-pages") {
params["skip_text_pages"] = json!(false);
}
let mut auto = automation(args)?;
let content = auto.call("doc_batch", &params).map_err(|e| e.to_string())?;
let failed = content.iter().any(|c| matches!(c, pdfcraft_automation::Content::Json(v) if v["failed"].as_u64().is_some_and(|n| n > 0)));
let mut log_error: Option<String> = None;
if let Some(path) = flag(args, "--log") {
let log = content.iter().find_map(|c| match c {
pdfcraft_automation::Content::Json(v) => v["log"].as_str().map(str::to_owned),
_ => None,
});
// Never let the log replace a file the batch read or published: collect every
// discovered input and every output this batch wrote, then refuse a match.
let protected: Vec<PathBuf> = content
.iter()
.filter_map(|c| match c {
pdfcraft_automation::Content::Json(v) => v["files"].as_array().map(|files| {
files.iter().flat_map(|f| {
let mut names = Vec::new();
if let Some(p) = f.get("path").and_then(|v| v.as_str()) {
names.push(PathBuf::from(p));
}
if matches!(f.get("status").and_then(|v| v.as_str()), Some("ok") | Some("planned"))
&& let Some(p) = f.get("output").and_then(|v| v.as_str())
{
names.push(PathBuf::from(p));
}
names
})
}),
_ => None,
})
.flatten()
.collect();
match auto.resolve_path(path, true) {
Ok(target) => {
if target.is_dir() {
log_error = Some(format!("batch: --log {path} is a directory"));
} else if protected.iter().any(|p| same_file(&target, p)) {
log_error = Some(format!("batch: --log {path} would overwrite a batch input or output"));
} else if let Err(e) = write_log(&target, log.unwrap_or_default().as_bytes()) {
log_error = Some(format!("batch: cannot write --log {path}: {e}"));
}
}
Err(e) => {
log_error = Some(format!("batch: cannot resolve --log {path}: {e}"));
}
}
}
let print_result = print_output(&auto, content, None);
if let Some(error) = log_error {
return Err(error.into());
}
print_result?;
if failed { Err("batch: one or more files failed; see the JSON report".into()) } else { Ok(()) }
}
/// Write the log atomically by delegating to the shared `craft::atomic::atomic_write` helper.
/// The helper stages the bytes in a non-predictable temporary file in the target's directory and
/// removes the staging file on every error path, so an unrelated file at any fixed staging name
/// is never clobbered and no temporary file is left behind.
fn write_log(target: &Path, bytes: &[u8]) -> std::io::Result<()> {
craft::atomic::atomic_write(target, bytes)
}
/// Whether `a` and `b` name the same file, normalizing `.` and `..` components and resolving
/// existing ancestors even when the final path does not exist yet.
///
/// Case is compared as-is: the compile-time OS no longer decides case folding, so on a
/// case-sensitive volume `GOOD.pdf` and `good.pdf` are different files. The same-file guard still
/// catches exact matches, `..` aliases and symlinks. On a case-insensitive volume `canonicalize`
/// already reports the stored case of an existing file, and on Unix file identity (device/inode)
/// is compared too, so case-distinct names that resolve to one file are still treated as one.
fn same_file(a: &Path, b: &Path) -> bool {
if normalize_path(a) == normalize_path(b) {
return true;
}
match (file_identity(a), file_identity(b)) {
(Some(id_a), Some(id_b)) => id_a == id_b,
_ => false,
}
}
/// File identity of an existing path: `(device, inode)` on Unix. `None` when the path does not
/// exist or the platform exposes no stable identity, so nonexistent case-distinct paths never match.
/// On Windows and macOS `canonicalize` already resolves an existing file's stored case, so the
/// normalized-path comparison covers case-insensitive volumes there without a platform identity.
fn file_identity(path: &Path) -> Option<(u64, u64)> {
let metadata = std::fs::metadata(path).ok()?;
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
Some((metadata.dev(), metadata.ino()))
}
#[cfg(not(unix))]
{
let _ = metadata;
None
}
}
/// Lexically and physically normalize a path, including paths that do not exist yet.
fn normalize_path(path: &Path) -> PathBuf {
// Resolve symlinks in existing components before applying `..`, so an alias such as
// `out/link/../../protected.pdf` cannot hide behind lexical path normalization.
let mut resolved = PathBuf::new();
for component in path.components() {
match component {
std::path::Component::CurDir => {}
std::path::Component::ParentDir => {
if matches!(resolved.components().next_back(), Some(std::path::Component::Normal(_))) {
resolved.pop();
} else {
resolved.push(component.as_os_str());
}
}
_ => {
resolved.push(component.as_os_str());
if let Ok(canonical) = resolved.canonicalize() {
resolved = canonical;
}
}
}
}
if resolved.as_os_str().is_empty() {
resolved = PathBuf::from(".");
}
if let Ok(canonical) = resolved.canonicalize() {
return canonical;
}
// Canonicalize the deepest existing ancestor, then reattach the (possibly nonexistent) tail.
// This also resolves symlinks in the existing portion of the path.
let mut ancestor = resolved.as_path();
let mut tail: Vec<std::ffi::OsString> = Vec::new();
while !ancestor.exists() {
match ancestor.file_name() {
Some(name) => {
tail.push(name.to_os_string());
match ancestor.parent() {
Some(parent) if !parent.as_os_str().is_empty() => ancestor = parent,
_ => break,
}
}
None => break,
}
}
let base = ancestor.canonicalize().unwrap_or_else(|_| ancestor.to_path_buf());
let mut result = base;
for name in tail.into_iter().rev() {
result.push(name);
}
result
}
#[cfg(test)]
mod tests {
#[test]
fn write_log_preserves_an_unrelated_file_at_the_staging_name() {
// Remove the private directory on every exit path, including a failed assertion.
struct TempDir(std::path::PathBuf);
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
// Acquire the directory first, then arm the recursive cleanup guard only after
// create_dir succeeds, so a pre-existing path is never removed if creation fails.
let path = std::env::temp_dir()
.join(format!("pdfcraft-cli-write-log-{}", std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()));
std::fs::create_dir(&path).expect("exclusive temporary directory");
let dir = TempDir(path);
let target = dir.0.join("batch.log");
let staging = dir.0.join(format!("batch.log.{}.tmp", std::process::id()));
std::fs::write(&staging, b"unrelated file").unwrap();
let result = super::write_log(&target, b"log content");
assert!(result.is_ok(), "write_log should write the log: {result:?}");
assert_eq!(std::fs::read_to_string(&target).unwrap(), "log content");
assert_eq!(std::fs::read_to_string(&staging).unwrap(), "unrelated file", "the predictable staging name must not clobber an unrelated file");
// A second write replaces the target's contents; the unrelated staging file survives it too.
let result = super::write_log(&target, b"second content");
assert!(result.is_ok(), "write_log should replace the log: {result:?}");
assert_eq!(std::fs::read_to_string(&target).unwrap(), "second content");
assert_eq!(std::fs::read_to_string(&staging).unwrap(), "unrelated file", "the predictable staging name must not clobber an unrelated file");
}
}