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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
use rustc_serialize::Encodable;
use rustc_serialize::base64::{URL_SAFE, ToBase64};

use flate2;
use cbor;
use rand;
use chrono;
use chrono::{DateTime, UTC};
use std::path::Path;

use std::io::{Read, BufRead, Write};
use std::fs::{File, metadata};

use std::collections::HashSet;
use std::str::from_utf8;
pub type Flag = u8;

use error::Error;


// Switching to serde is desirable here, as it is arguably faster and
// uses less memory, but there are some custom rustc-serialize
// instances in backend.rs.

#[derive(Debug, Clone, PartialEq, RustcEncodable, RustcDecodable)]
pub enum Value {
    String(String),
}
/// Options are for when this edge is between vertices introduced by the
/// current patch.
#[derive(Debug, Clone, RustcEncodable, RustcDecodable)]
pub struct NewEdge {
    pub from: Key<Option<Hash>>,
    pub to: Key<Option<Hash>>,
    pub introduced_by: Option<Hash>,
}


#[derive(Debug, Clone, RustcEncodable, RustcDecodable)]
pub enum Change {
    NewNodes {
        up_context: Vec<Key<Option<Hash>>>,
        down_context: Vec<Key<Option<Hash>>>,
        flag: EdgeFlags,
        line_num: LineId,
        nodes: Vec<Vec<u8>>,
    },
    NewEdges { flag: EdgeMap, edges: Vec<NewEdge> },
}

#[derive(Debug, Clone, RustcEncodable, RustcDecodable)]
pub enum EdgeMap {
    Map {
        previous: EdgeFlags,
        flag: EdgeFlags,
    },
    Forget { previous: EdgeFlags },
    New { flag: EdgeFlags },
}


#[derive(Debug, RustcEncodable, RustcDecodable)]
pub struct Patch {
    pub authors: Vec<String>,
    pub name: String,
    pub description: Option<String>,

    pub timestamp: DateTime<UTC>,

    pub dependencies: HashSet<Hash>,
    pub changes: Vec<Change>,
}

/// Semantic groups of changes, for interface purposes.
#[derive(Debug, RustcEncodable, RustcDecodable)]
pub enum Record {
    FileMove {
        new_name: String,
        del: Change,
        add: Change,
    },
    FileDel { name: String, del: Change },
    FileAdd { name: String, add: Change },
    Change(Change),
}


pub struct RecordIter<R, C> {
    rec: Option<R>,
    extra: Option<C>,
}

impl IntoIterator for Record {
    type IntoIter = RecordIter<Record, Change>;
    type Item = Change;
    fn into_iter(self) -> Self::IntoIter {
        RecordIter {
            rec: Some(self),
            extra: None,
        }
    }
}

impl Record {
    pub fn iter(&self) -> RecordIter<&Record, &Change> {
        RecordIter {
            rec: Some(self),
            extra: None,
        }
    }
}

impl Iterator for RecordIter<Record, Change> {
    type Item = Change;
    fn next(&mut self) -> Option<Self::Item> {
        if let Some(extra) = self.extra.take() {
            Some(extra)
        } else if let Some(rec) = self.rec.take() {
            match rec {
                Record::FileMove { del, add, .. } => {
                    self.extra = Some(add);
                    Some(del)
                }
                Record::FileDel { del: c, .. } |
                Record::FileAdd { add: c, .. } |
                Record::Change(c) => Some(c),
            }
        } else {
            None
        }
    }
}

impl<'a> Iterator for RecordIter<&'a Record, &'a Change> {
    type Item = &'a Change;
    fn next(&mut self) -> Option<Self::Item> {
        if let Some(extra) = self.extra.take() {
            Some(extra)
        } else if let Some(rec) = self.rec.take() {
            match *rec {
                Record::FileMove { ref del, ref add, .. } => {
                    self.extra = Some(add);
                    Some(del)
                }
                Record::FileDel { del: ref c, .. } |
                Record::FileAdd { add: ref c, .. } |
                Record::Change(ref c) => Some(c),
            }
        } else {
            None
        }
    }
}

impl Patch {
    pub fn empty() -> Patch {
        Patch {
            authors: vec![],
            name: "".to_string(),
            description: None,
            timestamp: chrono::UTC::now(),
            changes: vec![],
            dependencies: HashSet::new(),
        }
    }

    pub fn size_upper_bound(&self) -> usize {
        // General overhead for applying a page; 8 pages.
        let mut size: usize = 1 << 15;
        for c in self.changes.iter() {
            match *c {
                Change::NewNodes { ref nodes, .. } => {
                    size += nodes.iter().map(|x| x.len()).sum();
                    size += nodes.len() * 2048 // + half a page
                },
                Change::NewEdges { ref edges, .. } => {
                    size += edges.len() * 2048
                }
            }
        }
        size
    }

    pub fn from_reader_compressed<R: BufRead>(r: &mut R) -> Result<(Hash, Vec<u8>, Patch), Error> {
        let mut rr = flate2::bufread::GzDecoder::new(r)?;
        let filename = Hash::from_base64(from_utf8(rr.header().filename().unwrap())?).unwrap();

        let mut buf = Vec::new();
        rr.read_to_end(&mut buf)?;

        // Checking the hash.
        let hash = Hash::of_slice(&buf);
        match (&filename, &hash) {
            (&Hash::Sha512(ref filename), &Hash::Sha512(ref hash)) if &filename[..] ==
                                                                      &hash[..] => {}
            _ => return Err(Error::WrongHash),
        }

        let patch = {
            let mut decoder = cbor::Decoder::from_reader(&buf[..]);
            let mut decoder = decoder.decode();
            decoder.next().unwrap()?
        };

        Ok((filename, buf, patch))
    }

    pub fn to_writer(&self, w: &mut Write) -> Result<(), Error> {
        let e = flate2::write::GzEncoder::new(w, flate2::Compression::Best);
        let mut e = cbor::Encoder::from_writer(e);
        try!(self.encode(&mut e));
        Ok(())
    }
    pub fn save<P: AsRef<Path>>(&self, dir: P) -> Result<Hash, Error> {
        // Encoding to a buffer.
        let mut buf = Vec::new();
        {
            let mut e = cbor::Encoder::from_writer(&mut buf);
            try!(self.encode(&mut e));
        }

        // Hashing the buffer.
        let hash = Hash::of_slice(&buf);

        // Writing to the file.
        let h = hash.to_base64(URL_SAFE);
        let mut path = dir.as_ref().join(&h);
        path.set_extension("cbor.gz");
        if metadata(&path).is_err() {
            debug!("save, path {:?}", path);
            let f = try!(File::create(&path));
            debug!("created");
            let mut w = flate2::GzBuilder::new()
                .filename(h.as_bytes())
                .write(f, flate2::Compression::Best);
            try!(w.write_all(&buf));
            try!(w.finish());
            debug!("saved");
        }
        Ok(hash)
    }
}


pub fn write_changes(patches: &HashSet<(Hash, ApplyTimestamp)>,
                     changes_file: &Path)
                     -> Result<(), Error> {
    let mut file = try!(File::create(changes_file));
    let mut e = cbor::Encoder::from_writer(&mut file);
    try!(patches.encode(&mut e));
    Ok(())
}

pub fn read_changes(r: &mut Read) -> Result<HashSet<(Hash, ApplyTimestamp)>, Error> {
    let mut d = cbor::Decoder::from_reader(r);
    if let Some(d) = d.decode().next() {
        Ok(try!(d))
    } else {
        Err(Error::NothingToDecode)
    }
}
pub fn read_changes_from_file<P: AsRef<Path>>(changes_file: P)
                                              -> Result<HashSet<(Hash, ApplyTimestamp)>, Error> {
    let mut file = try!(File::open(changes_file));
    read_changes(&mut file)
}

impl<U: Transaction, R> T<U, R> {
    pub fn new_patch(&self,
                     branch: &Branch,
                     authors: Vec<String>,
                     name: String,
                     description: Option<String>,
                     timestamp: DateTime<UTC>,
                     changes: Vec<Change>)
                     -> Patch {
        let deps = self.dependencies(branch, changes.iter());
        Patch {
            authors: authors,
            name: name,
            description: description,
            timestamp: timestamp,
            changes: changes,
            dependencies: deps,
        }
    }


    pub fn dependencies<'a, I: Iterator<Item = &'a Change>>(&self,
                                                            branch: &Branch,
                                                            changes: I)
                                                            -> HashSet<Hash> {
        let mut deps = HashSet::new();
        for ch in changes {
            match *ch {
                Change::NewNodes { ref up_context,
                                   ref down_context,
                                   line_num: _,
                                   flag: _,
                                   nodes: _ } => {
                    for c in up_context.iter().chain(down_context.iter()) {
                        match c.patch {
                            None | Some(Hash::None) => {}
                            Some(ref dep) => {
                                deps.insert(dep.clone());
                            }
                        }
                    }
                }
                Change::NewEdges { ref edges, ref flag } => {
                    for e in edges {
                        match e.from.patch {
                            None | Some(Hash::None) => {}
                            Some(ref h) => {
                                deps.insert(h.clone());
                                match *flag {
                                    EdgeMap::Map { flag, .. } |
                                    EdgeMap::New { flag }
                                    if flag.contains(DELETED_EDGE|PARENT_EDGE) => {
                                        // Add "known patches" to
                                        // allow identifying missing
                                        // contexts.
                                        let k = Key {
                                            patch: self.get_internal(h.as_ref())
                                                .unwrap().to_owned(),
                                            line: e.from.line.clone(),
                                        };
                                        self.edge_context_deps(branch, &k, &mut deps)
                                    }
                                    _ => {}
                                }
                            }
                        }
                        match e.to.patch {
                            None | Some(Hash::None) => {}
                            Some(ref h) => {
                                deps.insert(h.clone());
                                match *flag {
                                    EdgeMap::Map { flag, .. } |
                                    EdgeMap::New { flag } if flag.contains(DELETED_EDGE) &&
                                                             !flag.contains(PARENT_EDGE) => {
                                        // Add "known patches" to
                                        // allow identifying
                                        // missing contexts.
                                        let k = Key {
                                            patch: self.get_internal(h.as_ref())
                                                .unwrap()
                                                .to_owned(),
                                            line: e.to.line.clone(),
                                        };
                                        self.edge_context_deps(branch, &k, &mut deps)
                                    }
                                    _ => {}
                                }
                            }
                        }
                        match e.introduced_by {
                            None | Some(Hash::None) => {}
                            Some(ref h) => {
                                deps.insert(h.clone());
                            }
                        }
                    }
                }
            }
        }
        deps
    }

    fn edge_context_deps(&self, branch: &Branch, k: &Key<PatchId>, deps: &mut HashSet<Hash>) {
        for (_, edge) in self.iter_nodes(branch, Some((&k, None)))
            .take_while(|&(k_, e_)| k_ == k && e_.flag <= PSEUDO_EDGE) {

            let ext = self.get_external(&edge.dest.patch).unwrap().to_owned();
            deps.insert(ext);
        }
    }
}

use backend::*;
use sanakirja;


impl<A: sanakirja::Transaction, R> T<A, R> {
    /// Gets the external key corresponding to the given key, returning an
    /// owned vector. If the key is just a patch internal hash, it returns the
    /// corresponding external hash.
    pub fn external_key(&self, key: &Key<PatchId>) -> Option<Key<Option<Hash>>> {
        if key.patch == ROOT_PATCH_ID {
            Some(Key {
                line: key.line.clone(),
                patch: Some(Hash::None),
            })
        } else if let Some(patch) = self.get_external(&key.patch) {
            Some(Key {
                line: key.line.clone(),
                patch: Some(patch.to_owned()),
            })
        } else {
            None
        }
    }

    pub fn external_hash(&self, key: &PatchId) -> HashRef {
        // println!("internal key:{:?}",&key[0..HASH_SIZE]);
        if *key == ROOT_PATCH_ID {
            ROOT_HASH.as_ref()
        } else {

            match self.get_external(key) {
                Some(pv) => pv,
                None => {
                    println!("internal key or hash:{:?}", key);
                    panic!("external hash not found {:?} !", key)
                }
            }
        }
    }

    /// Create a new internal patch id, register it in the "external" and
    /// "internal" bases, and write the result in its second argument
    /// ("result").
    pub fn new_internal(&self, ext: HashRef) -> PatchId {
        let mut result = ROOT_PATCH_ID.clone();
        match ext {
            HashRef::None => return result,
            HashRef::Sha512(h) => result.clone_from_slice(&h[..PATCH_ID_SIZE]),
        }
        let mut first_random = PATCH_ID_SIZE;
        loop {
            if self.get_external(&result).is_none() {
                break;
            }
            if first_random > 0 {
                first_random -= 1
            };
            for x in &mut result[first_random..].iter_mut() {
                *x = rand::random()
            }
        }
        result
    }
}