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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
#[macro_use]
extern crate log;
extern crate chrono;
#[macro_use]
extern crate bitflags;

extern crate sanakirja;
extern crate byteorder;
extern crate flate2;
extern crate ring;
extern crate untrusted;
extern crate libc;
extern crate rand;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate bincode;
extern crate hex;
extern crate base64;
extern crate tempdir;
#[macro_use]
extern crate error_chain;

use std::path::Path;
use std::collections::HashSet;
use base64::URL_SAFE_NO_PAD;
use std::io::Write;
use std::path::PathBuf;
pub use sanakirja::Transaction;

error_chain! {
    foreign_links {
        IO(std::io::Error);
        Sanakirja(sanakirja::Error);
        Bincode(bincode::Error);
        Utf8(std::str::Utf8Error);
        Ring(ring::error::Unspecified);
    }
    errors {
        AlreadyAdded {}
        FileNotInRepo(path: PathBuf) {}
        NoDb(root: backend::Root) {}
        WrongHash {}
        WrongPatchSignature {}
        BranchNameAlreadyExists {}
    }
}

impl Error {
    pub fn lacks_space(&self) -> bool {
        match self.0 {
            ErrorKind::Sanakirja(sanakirja::Error::NotEnoughSpace) => true,
            _ => false
        }
    }
}

#[macro_use]
mod backend;
pub mod fs_representation;
mod file_operations;

pub mod signature;
pub mod patch;
mod conflict;
pub mod graph;
mod optimal_diff;
mod record;
mod apply;
mod output;
mod unrecord;

pub use backend::{DEFAULT_BRANCH, Repository, MutTxn, LineId, PatchId, FOLDER_EDGE, PARENT_EDGE,
                  DELETED_EDGE, PSEUDO_EDGE, EdgeFlags, Hash, HashRef, Key, Edge, Txn, Branch,
                  Inode, ROOT_INODE, ROOT_KEY, SmallString, SmallStr, ApplyTimestamp};

pub use record::InodeUpdate;
pub use patch::{Patch, PatchHeader};
pub use sanakirja::value::Value;
pub use signature::KeyPair;
use fs_representation::ID_LENGTH;
use std::io::Read;
use rand::Rng;

impl<'env, T: rand::Rng> backend::MutTxn<'env, T> {
    pub fn output_changes_file<P: AsRef<Path>>(&mut self,
                                               branch: &Branch,
                                               path: P)
                                               -> Result<()> {
        let changes_file = fs_representation::branch_changes_file(path.as_ref(),
                                                                  branch.name.as_str());
        let mut branch_id: Vec<u8> = vec![b'\n'; ID_LENGTH + 1];
        {
            if let Ok(mut file) = std::fs::File::open(&changes_file) {
                file.read_exact(&mut branch_id)?;
            }
        }
        let mut branch_id = if let Ok(s) = String::from_utf8(branch_id) {
            s
        } else {
            "\n".to_string()
        };
        if branch_id.as_bytes()[0] == b'\n' {
            branch_id.truncate(0);
            let mut rng = rand::thread_rng();
            branch_id.extend(rng.gen_ascii_chars().take(ID_LENGTH));
            branch_id.push('\n');
        }

        let mut file = std::fs::File::create(&changes_file)?;
        file.write_all(&branch_id.as_bytes())?;
        for (s, hash) in self.iter_applied(&branch, None) {
            let hash_ext = self.get_external(hash).unwrap();
            writeln!(file, "{}:{}", hash_ext.to_base64(URL_SAFE_NO_PAD), s)?
        }
        Ok(())
    }

    pub fn branch_patches(&mut self, branch: &Branch) -> HashSet<(backend::Hash, ApplyTimestamp)> {
        self.iter_patches(branch, None)
            .map(|(patch, time)| (self.external_hash(patch).to_owned(), time))
            .collect()
    }

    pub fn fork(&mut self, branch: &Branch, new_name: &str) -> Result<Branch> {
        if branch.name.as_str() == new_name {
            Err(ErrorKind::BranchNameAlreadyExists.into())
        } else {
            Ok(Branch {
                   db: self.txn.fork(&mut self.rng, &branch.db)?,
                   patches: self.txn.fork(&mut self.rng, &branch.patches)?,
                   revpatches: self.txn.fork(&mut self.rng, &branch.revpatches)?,
                   name: SmallString::from_str(new_name),
                   apply_counter: 0,
               })
        }
    }
    pub fn add_file<P: AsRef<Path>>(&mut self, path: P, is_dir: bool) -> Result<()> {
        self.add_inode(None, path.as_ref(), is_dir)
    }


    fn file_nodes_fold_<A, F: FnMut(A, &Key<PatchId>) -> A>(&self,
                                                            branch: &Branch,
                                                            root: &Key<PatchId>,
                                                            level: usize,
                                                            mut init: A,
                                                            f: &mut F)
                                                            -> Result<A> {

        for (k, v) in self.iter_nodes(&branch, Some((root, None)))
            .take_while(|&(k, v)| k == root && v.flag.contains(FOLDER_EDGE)
                        && !v.flag.contains(PARENT_EDGE)) {

                debug!("file_nodes_fold_: {:?} {:?}", k, v);
                if level & 1 == 0 && level > 0 {
                    init = f(init, k)
                }
                init = self.file_nodes_fold_(branch, &v.dest, level + 1, init, f)?

            }
        Ok(init)
    }

    pub fn file_nodes_fold<A, F: FnMut(A, &Key<PatchId>) -> A>(&self,
                                                               branch: &Branch,
                                                               init: A,
                                                               mut f: F)
                                                               -> Result<A> {

        self.file_nodes_fold_(branch, &ROOT_KEY, 0, init, &mut f)

    }

}

impl<T: Transaction, R> backend::T<T, R> {
    /// Tells whether a `key` is alive in `branch`, i.e. is either the
    /// root, or has at least one alive edge pointing to it.
    fn is_alive(&self, branch: &Branch, key: &Key<PatchId>) -> bool {
        *key == ROOT_KEY || self.has_edge(branch, &key, PARENT_EDGE, false) ||
        self.has_edge(branch, &key, PARENT_EDGE | FOLDER_EDGE, false)
    }

    /// Test whether `key` has a neighbor with flag `flag0`. If
    /// `include_pseudo`, this includes pseudo-neighbors.
    pub fn has_edge(&self,
                    branch: &Branch,
                    key: &Key<PatchId>,
                    flag: EdgeFlags,
                    include_pseudo: bool)
                    -> bool {

        let e = Edge::zero(flag);
        if let Some((k, v)) = self.iter_nodes(&branch, Some((key, Some(&e)))).next() {
            if include_pseudo {
                k == key && (v.flag <= flag | PSEUDO_EDGE)
            } else {
                k == key && v.flag == flag
            }
        } else {
            false
        }
    }
}

fn make_remote<'a, I: Iterator<Item = &'a Hash>>
    (target: &Path,
     remote: I)
     -> Result<(Vec<(Hash, Patch)>, usize)> {
    use fs_representation::*;
    use std::io::BufReader;
    use std::fs::File;
    let mut patches = Vec::new();
    let mut patches_dir = patches_dir(target).to_path_buf();
    let mut size_increase = 0;

    for h in remote {

        patches_dir.push(&patch_file_name(h.as_ref()));

        debug!("opening {:?}", patches_dir);
        let file = try!(File::open(&patches_dir));
        let mut file = BufReader::new(file);
        let (h, _, patch) = Patch::from_reader_compressed(&mut file)?;

        size_increase += patch.size_upper_bound();
        patches.push((h.clone(), patch));

        patches_dir.pop();

    }
    Ok((patches, size_increase))
}

/// Apply a number of patches, guessing the new repository size.  If
/// this fails, the repository size is guaranteed to have been
/// increased by at least some pages, and it is safe to call this
/// function again.
///
/// Also, this function takes a file lock on the repository.
pub fn apply_resize<'a, I: Iterator<Item = &'a Hash>>(target: &Path,
                                                      branch_name: &str,
                                                      remote: I)
                                                      -> Result<()> {
    use fs_representation::*;
    let (patches, size_increase) = make_remote(target, remote)?;
    info!("applying patches with size_increase {:?}", size_increase);
    let pristine_dir = pristine_dir(target).to_path_buf();
    let repo = try!(Repository::open(pristine_dir, Some(size_increase as u64)));
    let mut txn = try!(repo.mut_txn_begin(rand::thread_rng()));
    try!(txn.apply_patches(branch_name, target, &patches));
    try!(txn.commit());
    Ok(())
}

/// Apply a number of patches, guessing the new repository size.  If
/// this fails, the repository size is guaranteed to have been
/// increased by at least some pages, and it is safe to call this
/// function again.
///
/// Also, this function takes a file lock on the repository.
pub fn apply_resize_no_output<'a, I: Iterator<Item = &'a Hash>>(target: &Path,
                                                                branch_name: &str,
                                                                remote: I)
                                                                -> Result<()> {
    use fs_representation::*;
    let (patches, size_increase) = make_remote(target, remote)?;
    let pristine_dir = pristine_dir(target).to_path_buf();
    let repo = try!(Repository::open(pristine_dir, Some(size_increase as u64)));
    let mut txn = try!(repo.mut_txn_begin(rand::thread_rng()));
    let mut branch = txn.open_branch(branch_name)?;
    let mut new_patches_count = 0;
    for &(ref p, ref patch) in patches.iter() {
        debug!("apply_patches: {:?}", p);
        txn.apply_patches_rec(&mut branch, &patches, p, patch, &mut new_patches_count)?
    }
    txn.commit_branch(branch)?;
    txn.commit()?;
    Ok(())
}

/// Open the repository, and unrecord the patch, without increasing
/// the size. If this fails, the repository file is guaranteed to have
/// been increased by `increase` bytes.
pub fn unrecord_no_resize(repo_dir: &Path,
                          repo_root: &Path,
                          branch_name: &str,
                          selected: &mut Vec<(Hash, Patch)>,
                          increase: u64)
                          -> Result<()> {
    debug!("unrecord_no_resize: {:?}", repo_dir);
    let repo = try!(Repository::open(repo_dir, Some(increase)));

    let mut txn = try!(repo.mut_txn_begin(rand::thread_rng()));
    let mut branch = txn.open_branch(branch_name)?;
    let mut timestamps = Vec::new();
    while let Some((hash, patch)) = selected.pop() {
        let internal = txn.get_internal(hash.as_ref()).unwrap().to_owned();
        debug!("Unrecording {:?}", hash);
        if let Some(ts) = txn.get_patch(&branch.patches, &internal) {
            timestamps.push(ts);
        }
        try!(txn.unrecord(&mut branch, &internal, &patch));
        debug!("Done unrecording {:?}", hash);
    }


    if let Err(e) = txn.output_changes_file(&branch, repo_root) {
        error!("no changes file: {:?}", e)
    }
    try!(txn.commit_branch(branch));
    try!(txn.commit());
    Ok(())
}