From 6b18cbda1f81604454fdf4dccb2a4bdae7f7cbd8 Mon Sep 17 00:00:00 2001 From: holger krekel Date: Mon, 4 Nov 2019 14:20:35 +0100 Subject: [PATCH] refine dc_copy along the lines @flub did for blobstore --- src/dc_tools.rs | 51 ++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 44 insertions(+), 7 deletions(-) diff --git a/src/dc_tools.rs b/src/dc_tools.rs index 9154bf17d..35df3fe2c 100644 --- a/src/dc_tools.rs +++ b/src/dc_tools.rs @@ -427,21 +427,55 @@ pub(crate) fn dc_delete_file(context: &Context, path: impl AsRef, - dest: impl AsRef, + src_path: impl AsRef, + dest_path: impl AsRef, ) -> bool { - let src_abs = dc_get_abs_path(context, &src); - let dest_abs = dc_get_abs_path(context, &dest); - match fs::copy(&src_abs, &dest_abs) { + let src_abs = dc_get_abs_path(context, &src_path); + let mut src_file = match fs::File::open(&src_abs) { + Ok(file) => file, + Err(err) => { + warn!( + context, + "failed to open for read '{}': {}", + src_abs.display(), + err + ); + return false; + } + }; + + let dest_abs = dc_get_abs_path(context, &dest_path); + let mut dest_file = match fs::OpenOptions::new() + .create_new(true) + .write(true) + .open(&dest_abs) + { + Ok(file) => file, + Err(err) => { + warn!( + context, + "failed to open for write '{}': {}", + dest_abs.display(), + err + ); + return false; + } + }; + + match std::io::copy(&mut src_file, &mut dest_file) { Ok(_) => true, Err(err) => { error!( context, "Cannot copy \"{}\" to \"{}\": {}", - src.as_ref().display(), - dest.as_ref().display(), + src_abs.display(), + dest_abs.display(), err ); + { + // Attempt to remove the failed file, swallow errors resulting from that. + fs::remove_file(dest_abs).ok(); + } false } } @@ -1283,6 +1317,9 @@ mod tests { assert!(dc_copy_file(context, "$BLOBDIR/foobar", "$BLOBDIR/dada",)); + // attempting to copy a second time should fail + assert!(!dc_copy_file(context, "$BLOBDIR/foobar", "$BLOBDIR/dada",)); + assert_eq!(dc_get_filebytes(context, "$BLOBDIR/dada",), 7); let buf = dc_read_file(context, "$BLOBDIR/dada").unwrap();