Skip to main content

steady_fs/
copy.rs

1use std::path::{Path, PathBuf};
2
3use crate::backup::backup_path_for;
4use crate::{Error, Result};
5
6/// Starts a file copy from `from` to `to`.
7///
8/// This helper copies a single file only. It does not recursively copy
9/// directories.
10pub fn copy_file<P, Q>(from: P, to: Q) -> CopyFile
11where
12    P: AsRef<Path>,
13    Q: AsRef<Path>,
14{
15    CopyFile {
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    }
24}
25
26/// Builder for [`copy_file`].
27///
28/// By default, parent directories are not created, existing files may be
29/// overwritten, backups are disabled, and dry-run mode is disabled.
30#[derive(Debug, Clone)]
31pub struct CopyFile {
32    from: PathBuf,
33    to: PathBuf,
34    create_parent_dirs: bool,
35    overwrite: bool,
36    backup_existing: bool,
37    backup_suffix: String,
38    dry_run: bool,
39}
40
41impl CopyFile {
42    /// Sets whether missing parent directories for the destination should be created.
43    pub fn create_parent_dirs(mut self, create_parent_dirs: bool) -> Self {
44        self.create_parent_dirs = create_parent_dirs;
45        self
46    }
47
48    /// Sets whether an existing destination file may be overwritten.
49    pub fn overwrite(mut self, overwrite: bool) -> Self {
50        self.overwrite = overwrite;
51        self
52    }
53
54    /// Sets whether an existing destination file should be backed up first.
55    pub fn backup_existing(mut self, backup_existing: bool) -> Self {
56        self.backup_existing = backup_existing;
57        self
58    }
59
60    /// Sets the suffix appended to the destination path for backups.
61    pub fn backup_suffix(mut self, backup_suffix: impl Into<String>) -> Self {
62        self.backup_suffix = backup_suffix.into();
63        self
64    }
65
66    /// Sets whether the operation should validate policy but skip filesystem writes.
67    pub fn dry_run(mut self, dry_run: bool) -> Self {
68        self.dry_run = dry_run;
69        self
70    }
71
72    /// Copies the source file to the destination and returns the copied byte count.
73    pub fn run(self) -> Result<u64> {
74        if !self.overwrite && self.to.exists() {
75            return Err(Error::AlreadyExists { path: self.to });
76        }
77
78        let parent = self.parent()?;
79
80        if self.dry_run {
81            return Ok(0);
82        }
83
84        if self.create_parent_dirs {
85            std::fs::create_dir_all(parent).map_err(|source| Error::CreateParentDir {
86                path: self.to.clone(),
87                parent: parent.to_path_buf(),
88                source,
89            })?;
90        }
91
92        if self.backup_existing && self.to.exists() {
93            let backup_path = self.backup_path();
94            std::fs::copy(&self.to, &backup_path).map_err(|source| Error::Backup {
95                path: self.to.clone(),
96                backup_path,
97                source,
98            })?;
99        }
100
101        std::fs::copy(&self.from, &self.to).map_err(|source| Error::CopyFile {
102            from: self.from,
103            to: self.to,
104            source,
105        })
106    }
107
108    fn parent(&self) -> Result<&Path> {
109        self.to.parent().ok_or_else(|| Error::MissingParent {
110            path: self.to.clone(),
111        })
112    }
113
114    fn backup_path(&self) -> PathBuf {
115        backup_path_for(&self.to, &self.backup_suffix)
116    }
117}