From 162a7ce1f86291d39f3ab2ef8866adeb6439d612 Mon Sep 17 00:00:00 2001 From: Thomas Voss Date: Sat, 12 Aug 2023 11:39:52 +0200 Subject: Backup the files being renamed --- src/main.rs | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) (limited to 'src') diff --git a/src/main.rs b/src/main.rs index c0121c9..278e530 100644 --- a/src/main.rs +++ b/src/main.rs @@ -131,6 +131,18 @@ fn work() -> Result<(), io::Error> { .sorted_by_key(|s| Reverse(s.0.components().count())) .collect_vec(); + let pid = process::id().to_string(); + let cache_base = env::var("XDG_CACHE_HOME").unwrap_or_else(|_| { + err!("XDG_CACHE_HOME variable must be set"); + }); + let cache_dir = [Path::new(cache_base.as_str()), Path::new("mmv"), Path::new(pid.as_str())].iter().collect::(); + fs::create_dir_all(&cache_dir)?; + + let cwd = require!(env::current_dir()); + require!(env::set_current_dir(cache_dir)); + backup_srcs(ps.iter().map(|(s, _, _)| s))?; + require!(env::set_current_dir(cwd)); + if flags.dryrun { for (s, _, d) in ps { println!("{} -> {}", disp(&s), disp(&d)); @@ -147,6 +159,25 @@ fn work() -> Result<(), io::Error> { Ok(()) } +fn backup_srcs<'a, I>(xs: I) -> Result<(), io::Error> +where + I: Iterator +{ + for x in xs { + let data = require!(fs::metadata(x)); + if data.is_dir() { + fs::create_dir_all(require!(x.strip_prefix("/")))?; + } else { + if let Some(p) = x.parent() { + fs::create_dir_all(require!(p.strip_prefix("/")))?; + } + fs::copy(x, require!(x.strip_prefix("/")))?; + } + } + + Ok(()) +} + fn run_indiv( srcs: &Vec, dsts: &mut Vec, -- cgit v1.2.3