Skip to main content

steady_fs/
move_file.rs

1use std::path::{Path, PathBuf};
2
3use crate::backup::backup_path_for;
4use crate::{Error, Result};
5
6/// Starts a file move from `from` to `to`.
7///
8/// This helper moves a single file only. It does not recursively move
9/// directories.
10pub fn move_file<P, Q>(from: P, to: Q) -> MoveFile
11where
12    P: AsRef<Path>,
13    Q: AsRef<Path>,
14{
15    MoveFile {
16        from: from.as_ref().to_path_buf(),
17        to: to.as_ref().to_path_buf(),
18        create_parent_dirs: false,
19        overwrite: true,
20        backup_existing: false,
21        backup_suffix: ".bak".to_owned(),
22        dry_run: false,
23        fallback_copy_delete: false,
24    }
25}
26
27/// Builder for [`move_file`].
28///
29/// By default, parent directories are not created, existing files may be
30/// overwritten, backups are disabled, dry-run mode is disabled, and copy-delete
31/// fallback is disabled.
32#[derive(Debug, Clone)]
33pub struct MoveFile {
34    from: PathBuf,
35    to: PathBuf,
36    create_parent_dirs: bool,
37    overwrite: bool,
38    backup_existing: bool,
39    backup_suffix: String,
40    dry_run: bool,
41    fallback_copy_delete: bool,
42}
43
44impl MoveFile {
45    /// Sets whether missing parent directories for the destination should be created.
46    pub fn create_parent_dirs(mut self, create_parent_dirs: bool) -> Self {
47        self.create_parent_dirs = create_parent_dirs;
48        self
49    }
50
51    /// Sets whether an existing destination file may be overwritten.
52    pub fn overwrite(mut self, overwrite: bool) -> Self {
53        self.overwrite = overwrite;
54        self
55    }
56
57    /// Sets whether an existing destination file should be backed up first.
58    pub fn backup_existing(mut self, backup_existing: bool) -> Self {
59        self.backup_existing = backup_existing;
60        self
61    }
62
63    /// Sets the suffix appended to the destination path for backups.
64    pub fn backup_suffix(mut self, backup_suffix: impl Into<String>) -> Self {
65        self.backup_suffix = backup_suffix.into();
66        self
67    }
68
69    /// Sets whether the operation should validate policy but skip filesystem writes.
70    pub fn dry_run(mut self, dry_run: bool) -> Self {
71        self.dry_run = dry_run;
72        self
73    }
74
75    /// Sets whether rename failures may fall back to copy-then-delete.
76    pub fn fallback_copy_delete(mut self, fallback_copy_delete: bool) -> Self {
77        self.fallback_copy_delete = fallback_copy_delete;
78        self
79    }
80
81    /// Moves the source file to the destination path.
82    pub fn run(self) -> Result<()> {
83        if !self.overwrite && self.to.exists() {
84            return Err(Error::AlreadyExists { path: self.to });
85        }
86
87        let parent = self.parent()?;
88
89        if self.dry_run {
90            return Ok(());
91        }
92
93        self.validate_source_is_file()?;
94
95        if self.create_parent_dirs {
96            std::fs::create_dir_all(parent).map_err(|source| Error::CreateParentDir {
97                path: self.to.clone(),
98                parent: parent.to_path_buf(),
99                source,
100            })?;
101        }
102
103        if self.backup_existing && self.to.exists() {
104            let backup_path = self.backup_path();
105            std::fs::copy(&self.to, &backup_path).map_err(|source| Error::Backup {
106                path: self.to.clone(),
107                backup_path,
108                source,
109            })?;
110        }
111
112        if self.to.exists() {
113            std::fs::remove_file(&self.to).map_err(|source| Error::MoveFile {
114                from: self.from.clone(),
115                to: self.to.clone(),
116                source,
117            })?;
118        }
119
120        match std::fs::rename(&self.from, &self.to) {
121            Ok(()) => Ok(()),
122            Err(_) if self.fallback_copy_delete => {
123                self.copy_delete().map_err(|source| Error::MoveFile {
124                    from: self.from,
125                    to: self.to,
126                    source,
127                })
128            }
129            Err(source) => Err(Error::MoveFile {
130                from: self.from,
131                to: self.to,
132                source,
133            }),
134        }
135    }
136
137    fn validate_source_is_file(&self) -> Result<()> {
138        let metadata = std::fs::metadata(&self.from).map_err(|source| Error::MoveFile {
139            from: self.from.clone(),
140            to: self.to.clone(),
141            source,
142        })?;
143
144        if metadata.is_file() {
145            Ok(())
146        } else {
147            let source = std::io::Error::new(
148                std::io::ErrorKind::InvalidInput,
149                "source path is not a file",
150            );
151            Err(Error::MoveFile {
152                from: self.from.clone(),
153                to: self.to.clone(),
154                source,
155            })
156        }
157    }
158
159    fn copy_delete(&self) -> std::io::Result<()> {
160        std::fs::copy(&self.from, &self.to)?;
161        std::fs::remove_file(&self.from)
162    }
163
164    fn parent(&self) -> Result<&Path> {
165        self.to.parent().ok_or_else(|| Error::MissingParent {
166            path: self.to.clone(),
167        })
168    }
169
170    fn backup_path(&self) -> PathBuf {
171        backup_path_for(&self.to, &self.backup_suffix)
172    }
173}