Skip to content

Commit 147f985

Browse files
committed
fix: close directory handles during recursive copy
1 parent ef5880c commit 147f985

1 file changed

Lines changed: 33 additions & 5 deletions

File tree

‎src/store/common.rs‎

Lines changed: 33 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,15 @@ pub(crate) fn ensure_dir(path: &Path) -> Result<(), String> {
1616
pub(crate) fn copy_dir_recursive(source: &Path, destination: &Path) -> Result<(), String> {
1717
ensure_dir(destination)?;
1818

19-
let entries = fs::read_dir(source).map_err(|error| error.to_string())?;
20-
for entry in entries {
21-
let entry = entry.map_err(|error| error.to_string())?;
22-
let source_path = entry.path();
23-
let destination_path = destination.join(entry.file_name());
19+
let entries = fs::read_dir(source)
20+
.map_err(|error| error.to_string())?
21+
.map(|entry| {
22+
let entry = entry.map_err(|error| error.to_string())?;
23+
Ok((entry.path(), destination.join(entry.file_name())))
24+
})
25+
.collect::<Result<Vec<_>, String>>()?;
26+
27+
for (source_path, destination_path) in entries {
2428
let metadata = fs::symlink_metadata(&source_path).map_err(|error| error.to_string())?;
2529
let file_type = metadata.file_type();
2630

@@ -176,4 +180,28 @@ mod tests {
176180

177181
fs::remove_dir_all(root).unwrap();
178182
}
183+
184+
#[cfg(unix)]
185+
#[test]
186+
fn copy_dir_recursive_copies_deep_trees_without_retaining_parent_handles() {
187+
let root = temp_root("deep-tree");
188+
let source = root.join("source");
189+
let destination = root.join("destination");
190+
let mut current = source.clone();
191+
for index in 0..128 {
192+
current = current.join(format!("d{index}"));
193+
fs::create_dir_all(&current).unwrap();
194+
fs::write(current.join("note.txt"), format!("level {index}\n")).unwrap();
195+
}
196+
197+
copy_dir_recursive(&source, &destination).unwrap();
198+
199+
let deepest = (0..128).fold(destination, |path, index| path.join(format!("d{index}")));
200+
assert_eq!(
201+
fs::read_to_string(deepest.join("note.txt")).unwrap(),
202+
"level 127\n"
203+
);
204+
205+
let _ = fs::remove_dir_all(root);
206+
}
179207
}

0 commit comments

Comments
 (0)