diff options
author | Thomas Voss <mail@thomasvoss.com> | 2023-08-12 11:39:52 +0200 |
---|---|---|
committer | Thomas Voss <mail@thomasvoss.com> | 2023-08-12 11:39:52 +0200 |
commit | 162a7ce1f86291d39f3ab2ef8866adeb6439d612 (patch) | |
tree | bf8497909b8e61faac90adbd3ac585c1b157db10 | |
parent | 11367850b9ef7d17f2691fe970c77602fe2b2f31 (diff) |
Backup the files being renamed
-rw-r--r-- | src/main.rs | 31 |
1 files changed, 31 insertions, 0 deletions
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::<PathBuf>(); + 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<Item = &'a PathBuf> +{ + 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<String>, dsts: &mut Vec<String>, |