tauri_api/file/
file_move.rs

1use std::fs;
2use std::path;
3
4/// Moves a file from the given path to the specified destination.
5///
6/// `source` and `dest` must be on the same filesystem.
7/// If `replace_using_temp` is specified, the destination file will be
8/// replaced using the given temporary path.
9///
10/// * Errors:
11///     * Io - copying / renaming
12#[derive(Debug)]
13pub struct Move<'a> {
14  source: &'a path::Path,
15  temp: Option<&'a path::Path>,
16}
17impl<'a> Move<'a> {
18  /// Specify source file
19  pub fn from_source(source: &'a path::Path) -> Move<'a> {
20    Self { source, temp: None }
21  }
22
23  /// If specified and the destination file already exists, the "destination"
24  /// file will be moved to the given temporary location before the "source"
25  /// file is moved to the "destination" file.
26  ///
27  /// In the event of an `io` error while renaming "source" to "destination",
28  /// the temporary file will be moved back to "destination".
29  ///
30  /// The `temp` dir must be explicitly provided since `rename` operations require
31  /// files to live on the same filesystem.
32  pub fn replace_using_temp(&mut self, temp: &'a path::Path) -> &mut Self {
33    self.temp = Some(temp);
34    self
35  }
36
37  /// Move source file to specified destination
38  pub fn to_dest(&self, dest: &path::Path) -> crate::Result<()> {
39    match self.temp {
40      None => {
41        fs::rename(self.source, dest)?;
42      }
43      Some(temp) => {
44        println!("dest {}", dest.to_str().unwrap());
45        println!("temp {}", temp.to_str().unwrap());
46        println!("source {}", self.source.to_str().unwrap());
47        if dest.exists() {
48          fs::rename(dest, temp)?;
49          if let Err(e) = fs::rename(self.source, dest) {
50            fs::rename(temp, dest)?;
51            return Err(e.into());
52          }
53        } else {
54          fs::rename(self.source, dest)?;
55        }
56      }
57    };
58    Ok(())
59  }
60}