mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
`file.automate.batch`, `file.scripts.imageProcessor`, `file.automate.lensCorrection`, droplets (which run batch) and `photocraft-cli batch` named every output `<stem>.<ext>` in one folder. When two inputs mapped to the same name (`a.png` and `a.jpg` saved as JPEG, or the same file name in two input folders), the later save replaced the earlier result while both were listed as written and the run exited 0. `engine::file_cmds::OutputClaims` remembers the outputs written in a run, ignoring case as macOS and Windows file systems do. An input whose output was already written is skipped before any work and reported in `errors` (the CLI prints FAIL and exits non-zero); the first result is kept. Runs whose names don't collide, including the same stem kept in its own formats, are unchanged. The commands' params docs say so. Co-authored-by: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
6119c00962
commit
c0a7f8e7e4
5 files changed
+121
-12
No files matched your search
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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
|
||||
),
|
||||
|
||||
@@ -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
|
||||
),
|
||||
|
||||
@@ -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:?}");
|
||||
}
|
||||
Reference in new issue
Block a user