1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
// Copyright 2015, 2016, 2017, 2018 Martin Pool.

//! Restore from the archive to the filesystem.

use std::fs;
use std::io;
use std::path::{Path, PathBuf};

use super::*;
use super::entry::Entry;


/// Options for Restore operation.
#[derive(Debug)]
pub struct RestoreOptions {
    force_overwrite: bool,
}


impl RestoreOptions {
    pub fn default() -> Self {
        RestoreOptions {
            force_overwrite: false,
        }
    }

    pub fn force_overwrite(self, f: bool) -> RestoreOptions {
        RestoreOptions {
            force_overwrite: f,
            ..self
        }
    }
}


/// A write-only tree on the filesystem, as a restore destination.
#[derive(Debug)]
struct RestoreTree {
    path: PathBuf,
    report: Report,
}


impl RestoreTree {
    pub fn create(path: &Path, report: &Report) -> Result<RestoreTree> {
        require_empty_destination(path)?;
        Self::create_overwrite(path, report)
    }

    pub fn create_overwrite(path: &Path, report: &Report) -> Result<RestoreTree> {
        Ok(RestoreTree {
            path: path.to_path_buf(),
            report: report.clone(),
        })
    }

    fn entry_path(&self, entry: &Entry) -> PathBuf {
        // Remove initial slash so that the apath is relative to the destination.
        self.path.join(&entry.apath().to_string()[1..])
    }
}


impl tree::WriteTree for RestoreTree {
    fn finish(&mut self) -> Result<()> {
        // Live tree doesn't need to be finished.
        Ok(())
    }

    fn write_dir(&mut self, entry: &Entry) -> Result<()> {
        self.report.increment("dir", 1);
        match fs::create_dir(self.entry_path(entry)) {
            Ok(_) => Ok(()),
            Err(ref e) if e.kind() == io::ErrorKind::AlreadyExists => Ok(()),
            Err(e) => Err(e.into()),
        }
    }

    fn write_file(&mut self, entry: &Entry, content: &mut std::io::Read) -> Result<()> {
        // TODO: Restore permissions.
        // TODO: Reset mtime: can probably use lutimes() but it's not in stable yet.
        self.report.increment("file", 1);
        let mut af = AtomicFile::new(&self.entry_path(entry))?;
        std::io::copy(content, &mut af)?;
        af.close(&self.report)
    }

    #[cfg(unix)]
    fn write_symlink(&mut self, entry: &Entry) -> Result<()> {
        use std::os::unix::fs as unix_fs;
        self.report.increment("symlink", 1);
        if let Some(ref target) = entry.symlink_target() {
            unix_fs::symlink(target, self.entry_path(entry))?;
        } else {
            // TODO: Treat as an error.
            warn!("No target in symlink entry {}", entry.apath());
        }
        Ok(())
    }

    #[cfg(not(unix))]
    fn write_symlink(&mut self, entry: &Entry) -> Result<()> {
        // TODO: Add a test with a canned index containing a symlink, and expect
        // it cannot be restored on Windows and can be on Unix.
        warn!("Can't restore symlinks on non-Unix: {}", entry.apath());
        self.report.increment("skipped.unsupported_file_kind", 1);
        Ok(())
    }
}


pub fn restore_tree(stored_tree: &StoredTree, dest: &Path, options: &RestoreOptions)
    -> Result<()> {
    let report = stored_tree.archive().report();
    let mut rt = if options.force_overwrite {
        RestoreTree::create_overwrite(dest, report)
    } else {
        RestoreTree::create(dest, report)
    }?;
    tree::copy_tree(stored_tree, &mut rt)
}


/// The destination must either not exist, or be an empty directory.
fn require_empty_destination(dest: &Path) -> Result<()> {
    match fs::read_dir(&dest) {
        Ok(mut it) => {
            if it.next().is_some() {
                Err(
                    ErrorKind::DestinationNotEmpty(dest.to_path_buf()).into(),
                )
            } else {
                Ok(())
            }
        }
        Err(e) => {
            match e.kind() {
                io::ErrorKind::NotFound => Ok(()),
                _ => Err(e.into()),
            }
        }
    }
}


#[cfg(test)]
mod tests {
    use std::fs;

    use spectral::prelude::*;

    use super::super::*;
    use test_fixtures::{ScratchArchive, TreeFixture};

    #[test]
    pub fn simple_restore() {
        let af = ScratchArchive::new();
        af.store_two_versions();
        let destdir = TreeFixture::new();

        let restore_report = Report::new();
        let restore_archive = Archive::open(af.path(), &restore_report).unwrap();
        let st = StoredTree::open_last(&restore_archive).unwrap();
        restore_tree(&st, destdir.path(), &RestoreOptions::default()).unwrap();

        assert_eq!(3, restore_report.get_count("file"));
        let dest = &destdir.path();
        assert_that(&dest.join("hello").as_path()).is_a_file();
        assert_that(&dest.join("hello2")).is_a_file();
        assert_that(&dest.join("subdir").as_path()).is_a_directory();
        assert_that(&dest.join("subdir").join("subfile").as_path()).is_a_file();
        if SYMLINKS_SUPPORTED {
            let dest = fs::read_link(&dest.join("link")).unwrap();
            assert_eq!(dest.to_string_lossy(), "target");
        }

        // TODO: Test restore empty file.
        // TODO: Test file contents are as expected.
        // TODO: Test restore of larger files.
    }

    #[test]
    fn restore_named_band() {
        let af = ScratchArchive::new();
        af.store_two_versions();
        let destdir = TreeFixture::new();
        let restore_report = Report::new();
        let a = Archive::open(af.path(), &restore_report).unwrap();
        let st = StoredTree::open_version(&a, &BandId::new(&[0])).unwrap();
        let options = RestoreOptions::default();
        restore_tree(&st, destdir.path(), &options).unwrap();
        // Does not have the 'hello2' file added in the second version.
        assert_eq!(2, restore_report.get_count("file"));
    }

    #[test]
    pub fn decline_to_overwrite() {
        let af = ScratchArchive::new();
        af.store_two_versions();
        let destdir = TreeFixture::new();
        destdir.create_file("existing");
        let restore_err_str = restore_tree(
            &StoredTree::open_last(&af).unwrap(),
            destdir.path(),
            &RestoreOptions::default(),
        ).unwrap_err()
            .to_string();
        assert_that(&restore_err_str).contains(&"Destination directory not empty");
    }

    #[test]
    pub fn forced_overwrite() {
        let af = ScratchArchive::new();
        af.store_two_versions();
        let destdir = TreeFixture::new();
        destdir.create_file("existing");

        let restore_report = Report::new();
        let restore_archive = Archive::open(af.path(), &restore_report).unwrap();
        let options = RestoreOptions::default().force_overwrite(true);
        let st = StoredTree::open_last(&restore_archive).unwrap();
        restore_tree(&st, destdir.path(), &options).unwrap();

        assert_eq!(3, restore_report.get_count("file"));
        let dest = &destdir.path();
        assert_that(&dest.join("hello").as_path()).is_a_file();
        assert_that(&dest.join("existing").as_path()).is_a_file();
    }

    #[test]
    pub fn exclude_files() {
        let af = ScratchArchive::new();
        af.store_two_versions();
        let destdir = TreeFixture::new();
        let restore_report = Report::new();
        let restore_archive = Archive::open(af.path(), &restore_report).unwrap();
        let st = StoredTree::open_last(&restore_archive).unwrap()
            .with_excludes(
                excludes::from_strings(&["/**/subfile"]).unwrap());
        let options = RestoreOptions::default();
        restore_tree(&st, destdir.path(), &options).unwrap();

        let dest = &destdir.path();
        assert_that(&dest.join("hello").as_path()).is_a_file();
        assert_that(&dest.join("hello2")).is_a_file();
        assert_that(&dest.join("subdir").as_path()).is_a_directory();
        assert_eq!(2, restore_report.borrow_counts().get_count("file"));
    }
}