PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Batch runs report inputs that share an output name instead of overwriting (#420, #422) (#448)
BFlatc0a7f8e7e4bc
diff --git a/apps/photocraft-cli/src/lib.rs b/apps/photocraft-cli/src/lib.rsindex 72898b389..612f74083 100644--- a/apps/photocraft-cli/src/lib.rs+++ b/apps/photocraft-cli/src/lib.rs@@ -272,11 +272,14 @@ fn batch(a: &Args, out: &mut dyn Write, err: &mut dyn Write) -> R {std::fs::read_dir(&in_dir).map_err(|e| format!("{}: {e}", in_dir.display()))?.flatten().map(|e| e.path()).filter(|p| is_input(p)).collect();inputs.sort();let (mut ok, mut failed) = (0, 0);+ let mut written = photocraft_engine::file_cmds::OutputClaims::default();for input in &inputs {let ext = a.get("--format").map(str::to_owned).or_else(|| input.extension().map(|e| e.to_string_lossy().into_owned())).unwrap_or_else(|| "png".into());let stem = input.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default();let target = out_dir.join(format!("{stem}.{ext}"));+ let target_text = target.to_string_lossy();let r = (|| -> Result<Vec<String>, String> {+ written.check(&target_text)?;let mut h = Headless::trusted_local();h.open(input).map_err(|e| e.to_string())?;for (id, p) in &actions {@@ -288,6 +291,7 @@ fn batch(a: &Args, out: &mut dyn Write, err: &mut dyn Write) -> R {match r {Ok(ws) => {ok += 1;+ written.record(&target_text, &input.to_string_lossy());let _ = writeln!(out, "ok {} -> {}", input.display(), target.display());warn_all(err, &ws);}diff --git a/apps/photocraft-cli/tests/cli.rs b/apps/photocraft-cli/tests/cli.rsindex 47ce1e85a..d5e5c90bf 100644--- a/apps/photocraft-cli/tests/cli.rs+++ b/apps/photocraft-cli/tests/cli.rs@@ -218,6 +218,38 @@ fn mcp_stdio_handshake_and_tool_call() {let _ = child.wait();}+/// `--format` mapping two inputs to one name fails the second instead of overwriting the first (#420).+#[test]+fn batch_fails_inputs_that_share_an_output_name() {+ let d = tmp("batch-collide");+ let input = d.join("in");+ std::fs::create_dir_all(&input).unwrap();+ write_png(&input.join("a.png"), 8, 4, 3);+ // Same stem in other formats; `A.tif` differs only in case.+ let img = photocraft_codecs::Image::from_u8(8, 4, photocraft_codecs::ChannelLayout::Rgb, vec![90; 96]).unwrap();+ for (name, format) in [("a.bmp", photocraft_codecs::Format::Bmp), ("A.tif", photocraft_codecs::Format::Tiff)] {+ std::fs::write(input.join(name), photocraft_codecs::encode(&img, format, &Default::default()).unwrap()).unwrap();+ }+ let actions = d.join("actions.json");+ std::fs::write(&actions, r#"[{"command":"image.adjustments.invert"}]"#).unwrap();+ let out_dir = d.join("out");+ let o = bin().args(["batch", "--actions"]).arg(&actions).arg("--in").arg(&input).arg("--out").arg(&out_dir).args(["--format", "png"]).output().unwrap();+ let (out, err) = (String::from_utf8_lossy(&o.stdout), String::from_utf8_lossy(&o.stderr));+ assert!(+ !o.status.success(),+ "a lost result must fail the run+{out}+{err}"+ );+ assert!(out.contains("1 succeeded, 2 failed"), "{out}");+ assert_eq!(err.matches("not written").count(), 2, "{err}");+ assert_eq!(std::fs::read_dir(&out_dir).unwrap().count(), 1);+ // Keeping each file's format, every input gets its own output.+ let out_dir = d.join("same");+ let (out, _) = ok(bin().args(["batch", "--actions"]).arg(&actions).arg("--in").arg(&input).arg("--out").arg(&out_dir));+ assert!(out.contains("3 succeeded, 0 failed"), "{out}");+}+#[test]fn droplet_runs_an_action_on_files() {let d = tmp("droplet");diff --git a/crates/engine/src/automate_cmds.rs b/crates/engine/src/automate_cmds.rsindex 1a862d4f7..a10a1bad1 100644--- a/crates/engine/src/automate_cmds.rs+++ b/crates/engine/src/automate_cmds.rs@@ -534,7 +534,7 @@ pub fn specs() -> Vec<CommandSpec> {"file.automate.runDroplet","Run Droplet",&[],- r##"{"droplet":path,"input":[files or folders],"output":folder? (default: droplet's, else <input folder>/droplet-output)} → {files, errors}"##,+ r##"{"droplet":path,"input":[files or folders],"output":folder? (default: droplet's, else <input folder>/droplet-output)} → {files, errors} (an input whose output name was already written in the run goes to errors)"##,native,run_droplet),diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rsindex c2e4b9301..cb96c1836 100644--- a/crates/engine/src/file_cmds.rs+++ b/crates/engine/src/file_cmds.rs@@ -616,31 +616,54 @@ pub(crate) fn process_files() -> Value {let mut files = Vec::new();let mut errors = Vec::new();+ let mut written = OutputClaims::default();for path in inputs {- let r = (|| -> Result<String> {+ let ext =+ if format == "same" { path.rsplit('.').next().unwrap_or("png").to_ascii_lowercase() } else { format.trim_start_matches('.').to_ascii_lowercase() };+ let out = join(output, &format!("{}{suffix}.{ext}", stem(path)));+ let r = (|| -> Result<()> {+ written.check(&out).map_err(EngineError::Other)?;let bytes = read_file(path)?;let mut scratch = Session::new();let doc = import(&file_name(path), &bytes)?;scratch.add_document(doc, Some(path.clone()));f(&mut scratch)?;- let ext = if format == "same" {- path.rsplit('.').next().unwrap_or("png").to_ascii_lowercase()- } else {- format.trim_start_matches('.').to_ascii_lowercase()- };- let out = join(output, &format!("{}{suffix}.{ext}", stem(path)));let d = scratch.active().ok_or(EngineError::NoDocument)?;save_doc(&d.doc, &out, quality)?;- Ok(out)+ Ok(())})();match r {- Ok(out) => files.push(out),+ Ok(()) => {+ written.record(&out, path);+ files.push(out);+ }Err(e) => errors.push(json!({"file": path, "error": e.to_string()})),}}json!({"files": files, "errors": errors})}+/// The output paths a batch run has written, so a later input whose output name matches an+/// earlier one's (`a.png` and `a.jpg` saved as JPEG, or the same name in two input folders) is+/// reported instead of silently replacing that result (#420, #422). Names are compared ignoring+/// case, because macOS and Windows file systems do.+#[derive(Default)]+pub struct OutputClaims(std::collections::HashMap<String, String>);++impl OutputClaims {+ /// `Err` (naming the earlier input) when `out` was already written in this run.+ pub fn check(&self, out: &str) -> std::result::Result<(), String> {+ match self.0.get(&out.to_lowercase()) {+ Some(first) => Err(format!("not written: {out} already holds the result of {first} from this run (same output name)")),+ None => Ok(()),+ }+ }+ /// Remember that `input`'s result was written to `out`.+ pub fn record(&mut self, out: &str, input: &str) {+ self.0.insert(out.to_lowercase(), input.to_string());+ }+}+fn batch(_s: &mut Session, p: &Value) -> Result<Value> {let cmd = "file.automate.batch";let steps =@@ -1082,7 +1105,7 @@ pub fn specs() -> Vec<CommandSpec> {"Batch…",&["File", "Automate"],None,- r##"{"steps":[[commandId,params]|{"command":id,"params":{}}…] (a recorded action),"input":folder|[paths],"output":folder,"format":"same|png|jpg|psd|tiff|…"="same","quality":0..12?} → {files, errors}"##,+ r##"{"steps":[[commandId,params]|{"command":id,"params":{}}…] (a recorded action),"input":folder|[paths],"output":folder,"format":"same|png|jpg|psd|tiff|…"="same","quality":0..12?} → {files, errors} (an input whose output name was already written in the run goes to errors)"##,native,batch),@@ -1091,7 +1114,7 @@ pub fn specs() -> Vec<CommandSpec> {"Image Processor…",&["File", "Scripts"],None,- r##"{"input":folder|[paths],"output":folder,"format":"jpg|png|psd|tiff|…"="jpg","quality":0..12=8,"width":px?,"height":px? (fit, never enlarge),"convertToSrgb":bool=false} → {files, errors}"##,+ r##"{"input":folder|[paths],"output":folder,"format":"jpg|png|psd|tiff|…"="jpg","quality":0..12=8,"width":px?,"height":px? (fit, never enlarge),"convertToSrgb":bool=false} → {files, errors} (an input whose output name was already written in the run goes to errors)"##,native,image_processor),diff --git a/crates/engine/src/file_cmds/tests.rs b/crates/engine/src/file_cmds/tests.rsindex 6ed1f819c..4f9e863b0 100644--- a/crates/engine/src/file_cmds/tests.rs+++ b/crates/engine/src/file_cmds/tests.rs@@ -390,3 +390,53 @@ fn only_layered_files_save_in_place() {assert_eq!(extension("dir/Photo.JPEG").as_deref(), Some("jpeg"));assert_eq!(extension("my.dir/name"), None);}++/// Two inputs with one output name: the first result is kept and the second is an error, never+/// a silent overwrite listed as written (#422).+#[test]+fn batch_reports_inputs_that_share_an_output_name() {+ let dir = tmp("collide");+ let input = join(&dir, "in");+ std::fs::create_dir_all(&input).unwrap();+ png(&input, "a.png", 8, 8, "#ff0000");+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 8, "height": 8, "background": "#0000ff"})).unwrap();+ save_doc(doc(&s), &join(&input, "a.jpg"), None).unwrap();+ png(&input, "B.png", 8, 8, "#00ff00");+ png(&input, "b.tif", 8, 8, "#00ff00");+ for (cmd, extra) in [+ ("file.automate.batch", json!({"steps": [], "format": "jpg"})),+ ("file.scripts.imageProcessor", json!({})),+ ("file.automate.lensCorrection", json!({"format": "jpg"})),+ ] {+ let out = join(&dir, cmd);+ let mut p = extra;+ p["input"] = json!(input);+ p["output"] = json!(out);+ let r = s.execute(cmd, p).unwrap();+ let files = r["files"].as_array().unwrap();+ let errors = r["errors"].as_array().unwrap();+ // `a.*` and `B.png`/`b.tif` (names that differ only in case) each collide once.+ assert_eq!((files.len(), errors.len()), (2, 2), "{cmd}: {r}");+ assert!(errors.iter().all(|e| e["error"].as_str().unwrap().contains("not written")), "{r}");+ let mut written: Vec<_> = files.iter().map(|f| f.as_str().unwrap().to_lowercase()).collect();+ written.dedup();+ assert_eq!(written.len(), 2, "each listed file is distinct: {r}");+ }+ // Keeping each file's format, nothing collides.+ let out = join(&dir, "same");+ let r = s.execute("file.automate.batch", json!({"steps": [], "input": input, "output": out})).unwrap();+ assert_eq!((r["files"].as_array().unwrap().len(), r["errors"].as_array().unwrap().len()), (4, 0), "{r}");+ // A droplet over two folders holding the same name.+ let other = join(&dir, "other");+ std::fs::create_dir_all(&other).unwrap();+ png(&other, "a.png", 8, 8, "#ffffff");+ let droplet = join(&dir, "d.pcdroplet");+ std::fs::write(&droplet, json!({"photocraftDroplet": 1, "name": "d", "action": {"steps": []}, "options": {"format": "png"}}).to_string()).unwrap();+ let out = join(&dir, "droplet");+ let r = s.execute("file.automate.runDroplet", json!({"droplet": droplet, "input": [join(&input, "a.png"), other], "output": out})).unwrap();+ assert_eq!((r["files"].as_array().unwrap().len(), r["errors"].as_array().unwrap().len()), (1, 1), "{r}");+ let kept = photocraft_io::import("a.png", &std::fs::read(join(&out, "a.png")).unwrap()).unwrap().document;+ let px = photocraft_compose::render(&kept, Rect::new(1, 1, 2, 2)).px[0];+ assert!(px[0] > 0.99 && px[1] < 0.01, "the first input's result is kept: {px:?}");+}