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
// Conserve backup system.
// Copyright 2015, 2016, 2017 Martin Pool.

//! Make a backup by walking a source directory and copying the contents
//! into an archive.

use super::*;


#[derive(Debug)]
pub struct BackupOptions {
}


impl BackupOptions {
    pub fn default() -> Self {
        BackupOptions { }
    }
}


/// Accepts files to write in the archive (in apath order.)
#[derive(Debug)]
struct BackupWriter {
    band: Band,
    block_dir: BlockDir,
    index_builder: IndexBuilder,
    report: Report,
}


/// Make a new backup from a source tree into a band in this archive.
pub fn make_backup(source: &LiveTree, archive: &Archive, _: &BackupOptions) -> Result<()> {
    tree::copy_tree(source, &mut BackupWriter::begin(archive)?)
}


impl BackupWriter {
    /// Create a new BackupWriter.
    ///
    /// This currently makes a new top-level band.
    fn begin(archive: &Archive) -> Result<BackupWriter> {
        let band = Band::create(archive)?;
        let block_dir = band.block_dir();
        let index_builder = band.index_builder();
        Ok(BackupWriter {
            band: band,
            block_dir: block_dir,
            index_builder: index_builder,
            report: archive.report().clone(),
        })
    }

    fn push_entry(&mut self, index_entry: IndexEntry) -> Result<()> {
        self.index_builder.push(index_entry);
        self.index_builder.maybe_flush(&self.report)?;
        Ok(())
    }
}


impl tree::WriteTree for BackupWriter {
    fn finish(&mut self) -> Result<()> {
        self.index_builder.finish_hunk(&self.report)?;
        self.band.close(&self.report)?;
        Ok(())
    }


    fn write_dir(&mut self, source_entry: &Entry) -> Result<()> {
        self.report.increment("dir", 1);
        self.push_entry(IndexEntry {
            apath: source_entry.apath().to_string().clone(),
            mtime: source_entry.unix_mtime(),
            kind: Kind::Dir,
            addrs: vec![],
            blake2b: None,
            target: None,
        })
    }

    fn write_file(&mut self, source_entry: &Entry, content: &mut std::io::Read) -> Result<()> {
        self.report.increment("file", 1);
        // TODO: Cope graciously if the file disappeared after readdir.
        let (addrs, body_hash) = self.block_dir.store(content, &self.report)?;
        self.push_entry(IndexEntry {
            apath: source_entry.apath().to_string().clone(),
            mtime: source_entry.unix_mtime(),
            kind: Kind::File,
            addrs: addrs,
            blake2b: Some(body_hash),
            target: None,
        })
    }

    fn write_symlink(&mut self, source_entry: &Entry) -> Result<()> {
        self.report.increment("symlink", 1);
        let target = source_entry.symlink_target();
        assert!(target.is_some());
        self.push_entry(IndexEntry {
            apath: source_entry.apath().to_string().clone(),
            mtime: source_entry.unix_mtime(),
            kind: Kind::Symlink,
            addrs: vec![],
            blake2b: None,
            target: target,
        })
    }
}


#[cfg(test)]
mod tests {
    use super::super::*;
    use test_fixtures::{ScratchArchive, TreeFixture};

    #[cfg(unix)]
    #[test]
    pub fn symlink() {
        let af = ScratchArchive::new();
        let srcdir = TreeFixture::new();
        srcdir.create_symlink("symlink", "/a/broken/destination");
        make_backup(
            &LiveTree::open(srcdir.path(), &Report::new()).unwrap(),
            &af,
            &BackupOptions::default()).unwrap();
        let report = af.report();
        assert_eq!(0, report.get_count("block.write"));
        assert_eq!(0, report.get_count("file"));
        assert_eq!(1, report.get_count("symlink"));
        assert_eq!(0, report.get_count("skipped.unsupported_file_kind"));

        let band_ids = af.list_bands().unwrap();
        assert_eq!(1, band_ids.len());
        assert_eq!("b0000", band_ids[0].as_string());

        let band = Band::open(&af, &band_ids[0]).unwrap();
        assert!(band.is_closed().unwrap());

        let index_entries = band.index_iter(&excludes::excludes_nothing(), &report)
            .unwrap()
            .filter_map(|i| i.ok())
            .collect::<Vec<IndexEntry>>();
        assert_eq!(2, index_entries.len());

        let e2 = &index_entries[1];
        assert_eq!(e2.kind(), Kind::Symlink);
        assert_eq!(e2.apath, "/symlink");
        assert_eq!(e2.target.as_ref().unwrap(), "/a/broken/destination");
    }

    #[test]
    pub fn excludes() {
        let af = ScratchArchive::new();
        let srcdir = TreeFixture::new();

        srcdir.create_dir("test");
        srcdir.create_dir("foooooo");
        srcdir.create_file("foo");
        srcdir.create_file("fooBar");
        srcdir.create_file("foooooo/test");
        srcdir.create_file("test/baz");
        srcdir.create_file("baz");
        srcdir.create_file("bar");

        let report = af.report();
        let lt = &LiveTree::open(srcdir.path(), &report).unwrap()
            .with_excludes(
                excludes::from_strings(
                    &["/**/foo*", "/**/baz"],
                ).unwrap(),
            );
        make_backup(
            &lt,
            &af,
            &BackupOptions::default()).unwrap();

        assert_eq!(1, report.get_count("block.write"));
        assert_eq!(1, report.get_count("file"));
        assert_eq!(2, report.get_count("dir"));
        assert_eq!(0, report.get_count("symlink"));
        assert_eq!(0, report.get_count("skipped.unsupported_file_kind"));
        assert_eq!(4, report.get_count("skipped.excluded.files"));
        assert_eq!(1, report.get_count("skipped.excluded.directories"));
    }

    #[test]
    pub fn empty_file_uses_zero_blocks() {
        use std::io::Read;

        let af = ScratchArchive::new();
        let srcdir = TreeFixture::new();
        srcdir.create_file_with_contents("empty", &[]);
        make_backup(
            &srcdir.live_tree(),
            &af,
            &BackupOptions::default()).unwrap();
        let report = af.report();

        assert_eq!(0, report.get_count("block.write"));
        assert_eq!(1, report.get_count("file"), "file count");

        // Read back the empty file
        let st = StoredTree::open_last(&af).unwrap();
        let empty_entry = st.iter_entries()
            .unwrap()
            .map(|i| i.unwrap())
            .find(|ref i| i.apath == "/empty")
            .expect("found one entry");
        let mut sf = st.file_contents(&empty_entry).unwrap();
        let mut s = String::new();
        assert_eq!(sf.read_to_string(&mut s).unwrap(), 0);
        assert_eq!(s.len(), 0);
    }
}