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
#[macro_use]
extern crate log;
extern crate chrono;
#[macro_use]
extern crate bitflags;

extern crate sanakirja;
extern crate byteorder;
extern crate cbor;
extern crate flate2;
extern crate ring;
extern crate libc;
extern crate rand;
extern crate rustc_serialize;
use std::path::Path;
use std::collections::{HashMap, HashSet};

pub mod error;
use self::error::*;

pub trait RepositoryEnv<'env, R>: Sized {
    fn open<P: AsRef<Path>>(&self, path: P) -> Result<Self, Error>;
    fn mut_txn_begin(&'env self) -> Result<R, Error>;
}


pub use sanakirja::Transaction;

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

pub mod patch;
pub 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,
    Hash,
    Key, Edge,
    Txn, Branch,
    ROOT_INODE, ROOT_KEY,
    SmallString,
    ApplyTimestamp
};
pub use record::InodeUpdate;
pub use patch::Patch;

impl<'env, T: rand::Rng> backend::MutTxn<'env, T> {

    fn write_changes_file<P: AsRef<Path>>(&mut self, branch: &Branch, path: P) -> Result<(), Error> {

        let patches = self.branch_patches(branch);
        debug!("write_changes_file, patches = {:?}", patches);
        let changes_file = fs_representation::branch_changes_file(path.as_ref(), branch.name.as_str());
        try!(patch::write_changes(&patches, &changes_file));
        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, Error> {
        if branch.name.as_str() == new_name {
            Err(Error::BranchNameAlreadyExists)
        } 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)
            })
        }
    }
}

impl<'env, T: rand::Rng> backend::MutTxn<'env, T> {
    pub fn add_file<P: AsRef<Path>>(&mut self, path: P, is_dir: bool) -> Result<(), Error> {
        self.add_inode(None, path.as_ref(), is_dir)
    }

    /// 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)
    }
}

fn make_remote<'a, I:Iterator<Item = &'a Hash>>(target: &Path, remote: I) -> Result<(HashMap<Hash, Patch>, usize), Error> {
    use fs_representation::*;
    use std::io::BufReader;
    use std::fs::File;
    let mut patches = HashMap::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.insert(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<(), Error> {
    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<(), Error> {
    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 (p, 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(())
}