Guard Batch outputs and preserve partial results

This commit is contained in:
Fabio Lissi committed 2026-11-01 23:56:10 -06:00
1 parent 4eba6bd2e9
commit 85cb54025c
10 files changed
+243 -69

No files matched your search

+4 -2
View File
@@ -66,8 +66,10 @@ pub(crate) fn batch(a: &BatchArgs, out: &mut dyn Write, err: &mut dyn Write) ->
} else {
std::fs::read_dir(in_dir)
.map_err(|source| CliError::ReadDir { path: in_dir.to_path_buf(), source })?
.flatten()
.map(|entry| entry.path())
.map(|entry| entry.map(|entry| entry.path()))
.collect::<std::io::Result<Vec<_>>>()
.map_err(|source| CliError::ReadDir { path: in_dir.to_path_buf(), source })?
.into_iter()
.filter(|path| is_input(path))
.map(|path| photocraft_engine::file_cmds::BatchInput { path: path.to_string_lossy().into_owned(), rel_dir: String::new() })
.collect()
+27
View File
@@ -847,6 +847,33 @@ fn batch_refuses_to_write_over_its_inputs() {
assert!(after.iter().zip(&before).all(|(a, b)| a.0 == b.0 && a.1 != b.1), "both inputs replaced");
}
#[test]
fn batch_naming_rejects_unread_input_alias_through_a_missing_directory() {
let d = tmp("batch-missing-directory-alias");
let input = d.join("in");
std::fs::create_dir_all(&input).unwrap();
write_png(&input.join("a.png"), 8, 4, 3);
write_png(&input.join("b.png"), 8, 4, 7);
let original = std::fs::read(input.join("b.png")).unwrap();
let actions = d.join("actions.json");
std::fs::write(&actions, r#"[{"command":"image.adjustments.invert"}]"#).unwrap();
let output = bin()
.arg("batch")
.arg("--actions")
.arg(&actions)
.arg("--in")
.arg(&input)
.arg("--out")
.arg(input.join("missing/.."))
.args(["--in-place", "--naming", "b.{ext}"])
.output()
.unwrap();
assert!(!output.status.success(), "{}", String::from_utf8_lossy(&output.stdout));
assert!(String::from_utf8_lossy(&output.stderr).contains("replace an input"));
assert_eq!(std::fs::read(input.join("b.png")).unwrap(), original);
assert!(!input.join("missing").exists());
}
/// #7437: `convert` to its own input file, however the output is spelt, is refused before
/// anything is read or written, unless `--in-place` asks for it (as `batch` does, #492).
#[test]
@@ -183,7 +183,9 @@ pub fn plan(inputs: &[BatchInput], output: &str, format: &str, params: &Value) -
{
let sources: std::collections::HashSet<_> = inputs.iter().filter_map(|i| std::fs::canonicalize(&i.path).ok()).collect();
for output in &outputs {
if std::fs::canonicalize(output).ok().is_some_and(|p| sources.contains(&p)) {
let identity = super::paths::destination_identity(std::path::Path::new(output))
.ok_or_else(|| bad(format!("naming output path cannot be resolved safely: {output}")))?;
if sources.contains(&identity) {
return Err(bad(format!("naming would replace an input file: {output}; choose a different destination or template")));
}
}
+32 -32
View File
@@ -49,7 +49,7 @@ pub(crate) fn batch_inputs_tree(p: &Value, cmd: &str, output: &str) -> Result<Ve
/// The images under `dir` and its subfolders: each folder's files sorted by name, then its
/// subfolders in name order (depth first). Bounded by [`MAX_SUBFOLDER_DEPTH`] and
/// [`MAX_SUBFOLDER_FILES`]; a folder reached twice (a symlink loop) is walked once, and `skip`
/// (the output folder) is left out.
/// (the output folder) is left out. An unreadable reached folder is an error.
#[cfg(not(target_arch = "wasm32"))]
pub fn list_images_tree(dir: &str, skip: &str, cmd: &str) -> Result<Vec<BatchInput>> {
use std::path::{Path, PathBuf};
@@ -64,12 +64,8 @@ pub fn list_images_tree(dir: &str, skip: &str, cmd: &str) -> Result<Vec<BatchInp
let mut stack: Vec<(PathBuf, String, usize)> = vec![(root.to_path_buf(), String::new(), 0)];
while let Some((folder, rel, depth)) = stack.pop() {
let shown = folder.to_string_lossy().into_owned();
// The top folder must be readable; a subfolder that isn't is skipped.
let files = match list_images(&shown) {
Ok(f) => f,
Err(e) if depth == 0 => return Err(e),
Err(_) => continue,
};
// Fail before writing any output if a reached input folder cannot be read.
let files = list_images(&shown)?;
if out.len().saturating_add(files.len()) > MAX_SUBFOLDER_FILES {
return Err(EngineError::BadParams { cmd: cmd.into(), msg: format!("{dir} holds more than {MAX_SUBFOLDER_FILES} images with its subfolders") });
}
@@ -77,17 +73,14 @@ pub fn list_images_tree(dir: &str, skip: &str, cmd: &str) -> Result<Vec<BatchInp
if depth >= MAX_SUBFOLDER_DEPTH {
continue;
}
let Ok(rd) = std::fs::read_dir(&folder) else { continue };
let mut subs: Vec<(String, PathBuf)> = rd
.filter_map(|e| e.ok())
.map(|e| e.path())
.filter(|p| p.is_dir())
.filter_map(|p| Some((p.file_name()?.to_string_lossy().into_owned(), p)))
.collect();
let rd = std::fs::read_dir(&folder).map_err(|e| EngineError::Other(format!("{shown}: {e}")))?;
let entries = rd.collect::<std::io::Result<Vec<_>>>().map_err(|e| EngineError::Other(format!("{shown}: {e}")))?;
let mut subs: Vec<(String, PathBuf)> =
entries.into_iter().map(|e| e.path()).filter(|p| p.is_dir()).filter_map(|p| Some((p.file_name()?.to_string_lossy().into_owned(), p))).collect();
subs.sort();
// Pushed in reverse so the stack pops them in name order.
for (name, sub) in subs.into_iter().rev() {
let Some(c) = canon(&sub) else { continue };
let c = canon(&sub).ok_or_else(|| EngineError::Other(format!("{}: cannot resolve the subfolder", sub.display())))?;
if skip.as_ref() == Some(&c) || !seen.insert(c) {
continue;
}
@@ -249,6 +242,10 @@ fn write_error_log(path: &str, errors: &[Value]) -> Result<()> {
super::paths::write_file(path, body.as_bytes()).map_err(|error| EngineError::Other(format!("error log: {error}")))
}
fn error_log_failure(path: Option<&str>, errors: &[Value]) -> Option<String> {
path.filter(|_| !errors.is_empty()).and_then(|path| write_error_log(path, errors).err().map(|error| error.to_string()))
}
fn batch_outcome(files: Vec<String>, errors: Vec<Value>, stopped: Option<(String, Vec<String>)>, error_log: Option<&str>) -> Value {
let logged = !errors.is_empty();
let mut result = json!({"files": files, "errors": errors});
@@ -306,17 +303,21 @@ fn process_batch_outputs(
}
}
}
if let Some(path) = &policy.error_log
&& !errors.is_empty()
{
write_error_log(path, &errors)?;
let log_failure = error_log_failure(policy.error_log.as_deref(), &errors);
let cancelled = ctx.cancelled();
if !cancelled {
ctx.progress(1.0, "");
}
if ctx.cancelled() {
return Err(EngineError::Cancelled);
}
ctx.progress(1.0, "");
let skipped = outputs.iter().skip(done).map(|(path, _)| path.clone()).collect();
Ok(batch_outcome(files, errors, stopped.map(|at| (at, skipped)), policy.error_log.as_deref()))
let mut result = batch_outcome(files, errors, stopped.map(|at| (at, skipped)), policy.error_log.as_deref().filter(|_| log_failure.is_none()));
if cancelled {
result["cancelled"] = json!(true);
result["skipped"] = json!(outputs.iter().skip(done).map(|(path, _)| path).collect::<Vec<_>>());
}
if let Some(error) = log_failure {
result["errorLogError"] = json!(error);
}
Ok(result)
}
/// The output paths a batch run has written, so a later input whose output name matches an
@@ -554,8 +555,8 @@ fn batch_open_documents(
let out = paths.get(index).ok_or_else(|| EngineError::Other("batch output plan is incomplete".into()))?;
claims.check(out).map_err(EngineError::Other)?;
let doc = match saved {
Some(saved) if s.active().is_none_or(|active| active.doc.id != saved.id) => saved,
_ => s.documents().iter().find(|state| state.doc.id.0 == *id).ok_or(EngineError::NoDocument)?.doc.clone(),
Some(saved) => saved,
None => s.documents().iter().find(|state| state.doc.id.0 == *id).ok_or(EngineError::NoDocument)?.doc.clone(),
};
save_doc(&doc, out, save)?;
claims.record(out, name);
@@ -576,13 +577,12 @@ fn batch_open_documents(
{
s.set_active(position);
}
if let Some(path) = &policy.error_log
&& !errors.is_empty()
{
write_error_log(path, &errors)?;
}
let log_failure = error_log_failure(policy.error_log.as_deref(), &errors);
let skipped = originals.iter().skip(done).map(|(_, name, _)| name.clone()).collect();
let mut result = batch_outcome(files, errors, stopped.map(|at| (at, skipped)), policy.error_log.as_deref());
let mut result = batch_outcome(files, errors, stopped.map(|at| (at, skipped)), policy.error_log.as_deref().filter(|_| log_failure.is_none()));
if let Some(error) = log_failure {
result["errorLogError"] = json!(error);
}
result["documents"] = json!(originals.len());
Ok(result)
}
+42 -29
View File
@@ -40,8 +40,9 @@ pub(crate) fn write_file(path: &str, _bytes: &[u8]) -> Result<()> {
#[cfg(not(target_arch = "wasm32"))]
pub fn list_images(dir: &str) -> Result<Vec<String>> {
let rd = std::fs::read_dir(dir).map_err(|e| EngineError::Other(format!("{dir}: {e}")))?;
let mut out: Vec<String> = rd
.filter_map(|e| e.ok())
let entries = rd.collect::<std::io::Result<Vec<_>>>().map_err(|e| EngineError::Other(format!("{dir}: {e}")))?;
let mut out: Vec<String> = entries
.into_iter()
.map(|e| e.path())
.filter(|p| p.is_file() && openable_name(&p.to_string_lossy()))
.map(|p| p.to_string_lossy().into_owned())
@@ -181,6 +182,34 @@ pub fn same_file(a: impl AsRef<std::path::Path>, b: impl AsRef<std::path::Path>)
false
}
/// Resolve a future output path component by component. Existing symlinks are followed before
/// applying a later `..`, while components not created yet are kept so a new `x/../file` still
/// resolves to the file it would reach after `x` is created.
#[cfg(not(target_arch = "wasm32"))]
pub fn destination_identity(path: &std::path::Path) -> Option<std::path::PathBuf> {
use std::path::{Component, PathBuf};
let absolute = if path.is_absolute() { path.to_path_buf() } else { std::env::current_dir().ok()?.join(path) };
let mut resolved = PathBuf::new();
for component in absolute.components() {
match component {
Component::CurDir => {}
Component::ParentDir => {
resolved.pop();
}
Component::Normal(_) => {
resolved.push(component.as_os_str());
match std::fs::symlink_metadata(&resolved) {
Ok(_) => resolved = std::fs::canonicalize(&resolved).ok()?,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(_) => return None,
}
}
Component::Prefix(_) | Component::RootDir => resolved.push(component.as_os_str()),
}
}
Some(resolved)
}
/// Whether two paths would name the same destination even before the file exists. This is used
/// when a batch error log must not be allowed to replace a result that will be written later.
pub fn same_destination(a: impl AsRef<std::path::Path>, b: impl AsRef<std::path::Path>) -> bool {
@@ -190,36 +219,20 @@ pub fn same_destination(a: impl AsRef<std::path::Path>, b: impl AsRef<std::path:
}
#[cfg(not(target_arch = "wasm32"))]
{
use std::path::{Component, Path, PathBuf};
let normalize = |path: &Path| -> Option<PathBuf> {
let absolute = if path.is_absolute() { path.to_path_buf() } else { std::env::current_dir().ok()?.join(path) };
let mut clean = PathBuf::new();
for component in absolute.components() {
match component {
Component::CurDir => {}
Component::ParentDir => {
clean.pop();
match (destination_identity(a), destination_identity(b)) {
(Some(a), Some(b)) => {
#[cfg(any(target_os = "windows", target_os = "macos"))]
{
match (a.to_str(), b.to_str()) {
(Some(a), Some(b)) => a.eq_ignore_ascii_case(b),
_ => a == b,
}
other => clean.push(other.as_os_str()),
}
#[cfg(not(any(target_os = "windows", target_os = "macos")))]
{
a == b
}
}
let mut existing = clean.as_path();
let mut suffix = Vec::new();
while !existing.exists() {
suffix.push(existing.file_name()?.to_os_string());
existing = existing.parent()?;
}
let mut resolved = std::fs::canonicalize(existing).ok()?;
for component in suffix.into_iter().rev() {
resolved.push(component);
}
Some(resolved)
};
match (normalize(a), normalize(b)) {
(Some(a), Some(b)) => match (a.to_str(), b.to_str()) {
(Some(a), Some(b)) => a.eq_ignore_ascii_case(b),
_ => a == b,
},
_ => false,
}
}
+95
View File
@@ -64,6 +64,45 @@ fn batch_error_log_cannot_replace_an_input_or_result() {
}
}
#[test]
fn batch_naming_rejects_an_input_alias_through_a_missing_parent() {
let dir = tmp("batch-missing-parent-alias");
let first = png(&dir, "a.png", 8, 6, "#ff0000");
let second = png(&dir, "b.png", 8, 6, "#00ff00");
let original = std::fs::read(&second).unwrap();
let output = join(&dir, "missing/..");
let error =
Session::new().execute("file.automate.batch", json!({"steps": [], "input": [first, second], "output": output, "naming": "b.{ext}"})).unwrap_err();
assert!(error.to_string().contains("replace an input"), "{error}");
assert_eq!(std::fs::read(&second).unwrap(), original);
assert!(!std::path::Path::new(&join(&dir, "missing")).exists());
}
#[cfg(unix)]
#[test]
fn batch_error_log_rejects_a_symlink_parent_alias() {
use std::os::unix::fs::symlink;
let dir = tmp("batch-symlink-parent-alias");
let source_dir = join(&dir, "in");
std::fs::create_dir_all(&source_dir).unwrap();
let input = png(&source_dir, "result.png", 8, 6, "#ff0000");
let other = join(&dir, "other");
std::fs::create_dir_all(join(&other, "child")).unwrap();
symlink(join(&other, "child"), join(&dir, "link")).unwrap();
let output = other;
let log = join(&dir, "link/../result.png");
let error = Session::new().execute("file.automate.batch", json!({"steps": [], "input": [input], "output": output, "errorLog": log})).unwrap_err();
assert!(error.to_string().contains("errorLog"), "{error}");
assert!(!std::path::Path::new(&join(&output, "result.png")).exists());
}
#[cfg(target_os = "linux")]
#[test]
fn linux_distinct_case_destinations_are_not_the_same_file() {
let dir = tmp("batch-case-sensitive-destinations");
assert!(!same_destination(join(&dir, "Image.png"), join(&dir, "image.png")));
}
#[test]
fn batch_open_source_edits_each_live_document_and_restores_the_active_one() {
let dir = tmp("batch-open-documents");
@@ -87,6 +126,62 @@ fn batch_open_source_edits_each_live_document_and_restores_the_active_one() {
assert!(std::path::Path::new(&join(&dir, "02_SECOND.PNG")).is_file());
}
#[test]
fn batch_open_source_exports_the_document_at_the_save_point() {
let dir = tmp("batch-open-save-point");
let mut session = Session::new();
session.execute("file.new", json!({"name": "First", "width": 8, "height": 6})).unwrap();
session.execute("file.new", json!({"name": "Second", "width": 12, "height": 5})).unwrap();
let result = session
.execute(
"file.automate.batch",
json!({
"source": "open", "steps": [["document.activate", {"document": 1}], ["file.save", {}]],
"output": dir, "format": "png", "naming": "{name}.{ext}"
}),
)
.unwrap();
assert!(result["errors"].as_array().unwrap().is_empty(), "{result}");
let mut opened = Session::new();
opened.execute("file.openAs", json!({"path": join(&dir, "First.png"), "as": "png"})).unwrap();
assert_eq!(doc(&opened).size.width, 12, "the save point selected the second document");
}
#[test]
fn batch_reports_file_failures_even_if_error_log_cannot_be_written() {
let dir = tmp("batch-error-log-write-fails");
let mut session = session(8, 6, 8);
let result = session
.execute(
"file.automate.batch",
json!({
"source": "open", "steps": [["layer.select", {"layer": "does not exist"}]],
"output": dir, "format": "png", "errorLog": dir
}),
)
.unwrap();
assert_eq!(result["files"], json!([]));
assert_eq!(result["errors"].as_array().map(Vec::len), Some(1), "{result}");
assert!(result["errorLogError"].as_str().is_some(), "{result}");
}
#[cfg(unix)]
#[test]
fn recursive_batch_reports_an_unreadable_subfolder() {
use std::os::unix::fs::PermissionsExt;
let dir = tmp("batch-unreadable-subfolder");
let sub = join(&dir, "locked");
std::fs::create_dir_all(&sub).unwrap();
png(&sub, "image.png", 8, 6, "#ff0000");
std::fs::set_permissions(&sub, std::fs::Permissions::from_mode(0o000)).unwrap();
let inaccessible = std::fs::read_dir(&sub).is_err();
let result = list_images_tree(&dir, "", "file.automate.batch");
std::fs::set_permissions(&sub, std::fs::Permissions::from_mode(0o700)).unwrap();
if inaccessible {
assert!(result.is_err(), "an inaccessible input folder must not be omitted");
}
}
#[test]
fn close_all_and_close_others() {
let mut s = session(8, 8, 8);
+10 -3
View File
@@ -693,10 +693,17 @@ impl Session {
}
}
/// Cancel job `id`: it stops at its next check, its result is discarded and the document
/// stays unchanged. The document is unlocked at once. False if no such job is running.
/// Cancel job `id`: ordinary jobs stop at their next check and discard their result.
/// A batch finishes the current input and reports outputs already written. False if no
/// such job is running.
pub fn cancel_job(&mut self, id: JobId) -> bool {
let Some(i) = self.jobs.running.iter().position(|r| r.id == id) else { return false };
// Earlier batch outputs are already on disk. Let the worker stop after its current
// input and return the completed and skipped lists.
if self.jobs.running[i].command == "file.automate.batch" {
self.jobs.running[i].ctx.cancel();
return true;
}
// A print worker can already have handed the job to the OS. Discarding its result
// would falsely report cancellation; removal belongs to the system print queue.
if matches!(self.jobs.running[i].command.as_str(), "file.print" | "file.printOneCopy") {
@@ -977,7 +984,7 @@ impl Session {
let outcome = match r {
Err(EngineError::Cancelled) => JobOutcome::Cancelled,
Err(e) => JobOutcome::Failed(e.to_string()),
Ok(_) if job.ctx.cancelled() => JobOutcome::Cancelled,
Ok(_) if job.ctx.cancelled() && job.command != "file.automate.batch" => JobOutcome::Cancelled,
Ok(payload) => match self.apply_job(&job, apply, payload) {
Ok(v) => JobOutcome::Done(v),
Err(EngineError::Cancelled) => JobOutcome::Cancelled,
+26
View File
@@ -543,6 +543,32 @@ fn open_runs_as_a_job_and_cancel_adds_nothing() {
assert!(matches!(wait_event(&mut s, id).outcome, JobOutcome::Failed(_)));
}
#[test]
fn cancelled_batch_job_returns_its_partial_result() {
let mut s = Session::new();
let id = job(s
.start_job(
"file.automate.batch",
json!({}),
"Batch",
false,
|ctx| {
while !ctx.cancelled() {
std::thread::sleep(Duration::from_millis(2));
}
Ok(json!({"files": ["done.png"], "skipped": ["later.png"], "cancelled": true}))
},
|_, result| Ok(result),
)
.unwrap());
assert!(s.cancel_job(id));
let event = wait_event(&mut s, id);
let JobOutcome::Done(result) = &event.outcome else { panic!("batch result was discarded: {:?}", event.outcome) };
assert_eq!(result["files"], json!(["done.png"]));
assert_eq!(result["skipped"], json!(["later.png"]));
assert_eq!(result["cancelled"], true);
}
/// Ask When Opening: a file whose profile doesn't match is decoded but not added; the shell takes
/// it once the prompt is answered. Without Ask it opens as usual.
#[test]
+3 -1
View File
@@ -21,7 +21,9 @@ keeps its order. Failed inputs consume their position, so later filenames do not
Braces in an input filename are literal text, not additional tokens. Subfolder inputs keep their
relative folders under the output folder. **Stop On Error** leaves later inputs unprocessed;
**Error Log** records failures and their reasons. Folder batches report progress per file and
can be cancelled after the current file.
can be cancelled after the current file. A cancelled batch returns `cancelled: true`, its
completed `files`, and `skipped` inputs. If writing the error log fails, the batch still
returns its per-file results with `errorLogError` instead of `errorLog`.
Unknown tokens, unmatched braces, invalid parameter types, path separators, reserved filename
characters, excessive filename length (255 UTF-8 bytes), and serial overflow are rejected before
+1 -1
View File
@@ -250,7 +250,7 @@ The shape is pinned by a test in `crates/automation/src/rpc.rs` (#3684).
### Background jobs (#210)
Long commands (every `filter.*`, `edit.contentAwareFill`, `edit.contentAwareScale`, `file.automate.photomerge`, `brush.presets.importAbr`), file opens and interactive saves (File › Save, Save As and the TIFF Options continuation, #2017) run as background jobs in the desktop app: the window keeps drawing, the status bar shows progress with a Cancel button, and jobs that lock the active document show a modal progress dialog (Esc cancels). `engine.execute`, `ui.menu.invoke`, `ui.dialog.confirm` and `app.save` still wait for the result by default; pass `"wait": false` to get `{job, pending: true}` at once, then poll `jobs.list` (`state`: running, done, failed, cancelled; `progress` 0–1; the result or error) and stop it with `jobs.cancel {job}`. A cancelled or failed job leaves the document unchanged. While a job runs, commands that would edit its document fail with "… is still running on this document". `ui.inspect` reports `jobs` (running jobs, opening files, saving files). Set `PHOTOCRAFT_INLINE_JOBS=1` to run everything inline.
Long commands (every `filter.*`, `edit.contentAwareFill`, `edit.contentAwareScale`, `file.automate.photomerge`, `brush.presets.importAbr`), file opens and interactive saves (File › Save, Save As and the TIFF Options continuation, #2017) run as background jobs in the desktop app: the window keeps drawing, the status bar shows progress with a Cancel button, and jobs that lock the active document show a modal progress dialog (Esc cancels). `engine.execute`, `ui.menu.invoke`, `ui.dialog.confirm` and `app.save` still wait for the result by default; pass `"wait": false` to get `{job, pending: true}` at once, then poll `jobs.list` (`state`: running, done, failed, cancelled; `progress` 0–1; the result or error) and stop it with `jobs.cancel {job}`. A cancelled or failed job leaves the document unchanged; a folder Batch can already have written earlier output files and reports those paths when cancelled. While a job runs, commands that would edit its document fail with "… is still running on this document". `ui.inspect` reports `jobs` (running jobs, opening files, saving files). Set `PHOTOCRAFT_INLINE_JOBS=1` to run everything inline.
## Preferences