Reject export filenames that already exist in the destination

An export that collides with a file already in the destination currently overwrites it without warning, losing the existing file. Rejecting the collision before writing protects existing files and makes the failure explicit.

Check every target path in the destination directory before creating or writing any output, and return a file.export error naming the colliding filename if one already exists. Add a regression test that places a sentinel file at an output name, runs file.export with unique identifiers, and asserts the export fails and the sentinel is unchanged.

Test: export_rejects_existing_file_in_destination_before_writing failed before the change and passes after.
This commit is contained in:
eliets2 committed 2026-11-06 17:51:19 +02:00
1 parent 047afaaa5c
commit d01a28bb20
2 files changed
+22

No files matched your search

+5
View File
@@ -282,6 +282,11 @@ fn export(s: &mut Session, p: &J) -> Result<J> {
let (gi, ext, pattern, depth, size) = export_params(s, p)?;
let files = export_outputs(s, gi, &ext, &pattern, depth, size)?;
std::fs::create_dir_all(dir).map_err(|e| bad("file.export", format!("{dir}: {e}")))?;
for f in &files {
if std::path::Path::new(dir).join(&f.file).exists() {
return Err(bad("file.export", format!("duplicate export filename `{}`: use unique output identifiers or a different filename pattern", f.file)));
}
}
let mut written = Vec::new();
for f in files {
let path = std::path::Path::new(dir).join(&f.file);
+17
View File
@@ -78,6 +78,23 @@ fn colliding_export_preserves_existing_files_and_writes_no_partial_outputs() {
);
}
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn export_rejects_existing_file_in_destination_before_writing() {
let (mut s, _) = session();
let dir = TempDir::new("existing");
let sentinel = b"existing file must survive a rejected export";
std::fs::write(dir.0.join("first.png"), sentinel).unwrap();
let result = execute(&mut s, "file.export", &json!({"dir": dir.0, "pattern": "$(identifier)"}));
let existing = std::fs::read(dir.0.join("first.png")).unwrap();
let files = std::fs::read_dir(&dir.0).unwrap().count();
assert!(
result.is_err() && existing == sentinel && files == 1,
"export overwrote an existing destination file: response={result:?}, files={files}, sentinel preserved={}",
existing == sentinel
);
}
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn unique_export_writes_both_maps_with_their_expected_pixels() {