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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
#[macro_use]
extern crate log;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate bitflags;
#[macro_use]
extern crate pijul_macros;
#[macro_use]
extern crate thiserror;
#[macro_use]
extern crate lazy_static;

pub mod alive;
mod apply;
pub mod change;
pub mod changestore;
mod diff;
mod find_alive;
#[doc(hidden)]
pub mod fs;
mod missing_context;
pub mod output;
pub mod path;
pub mod pristine;
pub mod record;
pub mod small_string;
mod unrecord;
mod vector2;
pub mod vertex_buffer;
pub mod working_copy;

#[cfg(test)]
mod tests;

pub const DOT_DIR: &'static str = ".pijul";

#[derive(Debug, Error)]
pub enum Error {
    #[error("File {:?} already in repository", path)]
    FileAlreadyInRepo { path: String },
    #[error("File {:?} not in repository", path)]
    FileNotInRepo { path: String },
    #[error("Cannot record from unrecorded prefix {:?}", path)]
    UnrecordedPath { path: String },
    #[error("File {:?} not found", path)]
    FileNotFound { path: String },
    #[error("Change not on channel {:?}", change_id)]
    ChangeNotOnChannel { change_id: pristine::ChangeId },
    #[error("Change is depended upon {:?}", change_id)]
    ChangeIsDependedUpon { change_id: pristine::ChangeId },
    #[error("Change not found: {:?}", hash)]
    ChangeNotFound { hash: String },
    #[error("State not found: {:?}", state)]
    StateNotFound { state: pristine::Merkle },
    #[error("Change hash mismatch: {:?} != {:?}", claimed, computed)]
    ChangeHashMismatch {
        claimed: pristine::Hash,
        computed: pristine::Hash,
    },
    #[error("Contents hash mismatch: {:?} != {:?}", claimed, computed)]
    ContentsHashMismatch {
        claimed: pristine::Hash,
        computed: pristine::Hash,
    },
    #[error("Change already on channel: {:?}", hash)]
    ChangeAlreadyOnChannel { hash: pristine::Hash },
    #[error("Dependency missing: {:?}", hash)]
    DependencyMissing { hash: pristine::Hash },
    #[error("Channel name already taken: {:?}", name)]
    ChannelNameExists { name: String },
    #[error("Parse error: {:?}", s)]
    ParseError { s: String },
    #[error("Verify error, public key = {:?}", pk)]
    VerifyError { pk: String },
    #[error("Ambiguous hash prefix: {}", prefix)]
    AmbiguousHashPrefix { prefix: String },
    #[error("Inconsistent references in change")]
    InconsistentChange,
    #[error("Missing change contents: {}", hash)]
    MissingContents { hash: String },
    #[error("Wrong block: {:?}", block)]
    WrongBlock {
        block: pristine::Position<pristine::ChangeId>,
    },
    #[error("Pristine corrupt")]
    PristineCorrupt,
    #[error("Change version mismatch, please run `pijul upgrade`.")]
    VersionMismatch,
    #[error("The repository is locked by another process.")]
    PristineLocked,
}

pub use crate::apply::Workspace as ApplyWorkspace;
pub use crate::fs::WorkingCopyIterator;
pub use crate::output::{Archive, Conflict};
pub use crate::pristine::Vertex;
pub use crate::record::Builder as RecordBuilder;
pub use crate::record::{Algorithm, InodeUpdate};
use std::collections::HashMap;

impl MutTxnTExt for pristine::sanakirja::MutTxn<()> {}
impl TxnTExt for pristine::sanakirja::MutTxn<()> {}
impl TxnTExt for pristine::sanakirja::Txn {}

pub trait MutTxnTExt: pristine::MutTxnT {
    fn apply_change_ws<C: changestore::ChangeStore>(
        &mut self,
        changes: &C,
        channel: &mut pristine::ChannelRef<Self>,
        hash: crate::pristine::Hash,
        workspace: &mut ApplyWorkspace,
    ) -> Result<(u64, pristine::Merkle), anyhow::Error> {
        crate::apply::apply_change_ws(changes, self, channel, hash, workspace)
    }

    fn apply_change_rec_ws<C: changestore::ChangeStore>(
        &mut self,
        changes: &C,
        channel: &mut pristine::ChannelRef<Self>,
        hash: crate::pristine::Hash,
        workspace: &mut ApplyWorkspace,
    ) -> Result<(), anyhow::Error> {
        crate::apply::apply_change_rec_ws(changes, self, channel, hash, workspace, false)
    }

    fn apply_change<C: changestore::ChangeStore>(
        &mut self,
        changes: &C,
        channel: &mut pristine::ChannelRef<Self>,
        hash: pristine::Hash,
    ) -> Result<(u64, pristine::Merkle), anyhow::Error> {
        crate::apply::apply_change(changes, self, channel, hash)
    }

    fn apply_change_rec<C: changestore::ChangeStore>(
        &mut self,
        changes: &C,
        channel: &mut pristine::ChannelRef<Self>,
        hash: pristine::Hash,
    ) -> Result<(), anyhow::Error> {
        crate::apply::apply_change_rec(changes, self, channel, hash, false)
    }

    fn apply_deps_rec<C: changestore::ChangeStore>(
        &mut self,
        changes: &C,
        channel: &mut pristine::ChannelRef<Self>,
        hash: pristine::Hash,
    ) -> Result<(), anyhow::Error> {
        crate::apply::apply_change_rec(changes, self, channel, hash, true)
    }

    fn apply_local_change_ws(
        &mut self,
        channel: &mut pristine::ChannelRef<Self>,
        change: &change::Change,
        hash: pristine::Hash,
        inode_updates: &HashMap<usize, InodeUpdate>,
        workspace: &mut ApplyWorkspace,
    ) -> Result<(u64, pristine::Merkle), anyhow::Error> {
        crate::apply::apply_local_change_ws(self, channel, change, hash, inode_updates, workspace)
    }

    fn apply_local_change(
        &mut self,
        channel: &mut crate::pristine::ChannelRef<Self>,
        change: &crate::change::Change,
        hash: pristine::Hash,
        inode_updates: &HashMap<usize, InodeUpdate>,
    ) -> Result<(u64, pristine::Merkle), anyhow::Error> {
        crate::apply::apply_local_change(self, channel, change, hash, inode_updates)
    }

    fn record<W: crate::working_copy::WorkingCopy, C: crate::changestore::ChangeStore>(
        &mut self,
        builder: &mut RecordBuilder,
        diff_algorithm: Algorithm,
        channel: &mut pristine::ChannelRef<Self>,
        working_copy: &mut W,
        changes: &C,
        prefix: &str,
    ) -> Result<(), anyhow::Error> {
        builder.record(self, diff_algorithm, channel, working_copy, changes, prefix)
    }

    fn record_all<W: crate::working_copy::WorkingCopy, C: crate::changestore::ChangeStore>(
        &mut self,
        diff_algorithm: Algorithm,
        channel: &mut pristine::ChannelRef<Self>,
        working_copy: &mut W,
        changes: &C,
        prefix: &str,
    ) -> Result<record::Recorded, anyhow::Error> {
        let mut builder = crate::record::Builder::new();
        builder.record(self, diff_algorithm, channel, working_copy, changes, prefix)?;
        Ok(builder.finish())
    }

    fn apply_recorded<C: changestore::ChangeStore>(
        &mut self,
        channel: &mut pristine::ChannelRef<Self>,
        recorded: record::Recorded,
        changestore: &C,
    ) -> Result<pristine::Hash, anyhow::Error> {
        use std::collections::BTreeSet;
        let contents_hash = {
            let mut hasher = pristine::Hasher::default();
            hasher.update(&recorded.contents);
            hasher.finish()
        };
        let change = change::LocalChange {
            offsets: change::Offsets::default(),
            hashed: change::Hashed {
                version: change::VERSION,
                contents_hash,
                changes: recorded
                    .actions
                    .into_iter()
                    .map(|rec| rec.globalize(self))
                    .collect(),
                metadata: Vec::new(),
                dependencies: BTreeSet::new(),
                extra_known: BTreeSet::new(),
                header: change::ChangeHeader::default(),
            },
            unhashed: None,
            contents: recorded.contents,
        };
        let hash = changestore.save_change(&change)?;
        apply::apply_local_change(self, channel, &change, hash.clone(), &recorded.updatables)?;
        Ok(hash)
    }

    fn unrecord<C: changestore::ChangeStore>(
        &mut self,
        changes: &C,
        channel: &mut pristine::ChannelRef<Self>,
        hash: &pristine::Hash,
    ) -> Result<bool, anyhow::Error> {
        unrecord::unrecord(self, channel, changes, hash)
    }

    fn output_repository_no_pending<R: working_copy::WorkingCopy, C: changestore::ChangeStore>(
        &mut self,
        repo: &mut R,
        changes: &C,
        channel: &mut pristine::ChannelRef<Self>,
        prefix: &str,
        output_name_conflicts: bool,
    ) -> Result<Vec<output::Conflict>, anyhow::Error> {
        output::output_repository_no_pending(
            repo,
            changes,
            self,
            channel,
            prefix,
            output_name_conflicts,
        )
    }

    /// Register a file in the working copy, where the file is given by
    /// its path from the root of the repository, where the components of
    /// the path are separated by `/` (example path: `a/b/c`).
    fn add_file(&mut self, path: &str) -> Result<(), anyhow::Error> {
        fs::add_inode(self, None, path, false)
    }

    /// Register a directory in the working copy, where the directory is
    /// given by its path from the root of the repository, where the
    /// components of the path are separated by `/` (example path:
    /// `a/b/c`).
    fn add_dir(&mut self, path: &str) -> Result<(), anyhow::Error> {
        fs::add_inode(self, None, path, true)
    }

    /// Register a file or directory in the working copy, given by its
    /// path from the root of the repository, where the components of the
    /// path are separated by `/` (example path: `a/b/c`).
    fn add(&mut self, path: &str, is_dir: bool) -> Result<(), anyhow::Error> {
        fs::add_inode(self, None, path, is_dir)
    }

    fn move_file(&mut self, a: &str, b: &str) -> Result<(), anyhow::Error> {
        fs::move_file(self, a, b)
    }

    fn remove_file(&mut self, a: &str) -> Result<(), anyhow::Error> {
        fs::remove_file(self, a)
    }

    #[cfg(feature = "dump")]
    fn channel_from_dump<'a>(
        &'a mut self,
        name: &str,
    ) -> Result<pristine::channel_dump::ChannelFromDump<'a, Self>, anyhow::Error> {
        if self.load_channel(name).is_none() {
            let channel = self.open_or_create_channel(name)?;
            Ok(pristine::channel_dump::ChannelFromDump::new(self, channel))
        } else {
            Err((Error::ChannelNameExists {
                name: name.to_string(),
            })
            .into())
        }
    }

    fn archive_with_state<'a, P: changestore::ChangeStore, A: Archive>(
        &mut self,
        changes: &P,
        channel: &mut pristine::ChannelRef<Self>,
        state: pristine::Merkle,
        extra: &[pristine::Hash],
        arch: &mut A,
    ) -> Result<Vec<output::Conflict>, anyhow::Error> {
        self.archive_prefix_with_state(
            changes,
            channel,
            state,
            extra,
            &mut std::iter::empty(),
            arch,
        )
    }

    /// Warning: this method unrecords changes until finding the
    /// state. If this is not wanted, please fork the channel before
    /// calling.
    fn archive_prefix_with_state<
        'a,
        P: changestore::ChangeStore,
        A: Archive,
        I: Iterator<Item = &'a str>,
    >(
        &mut self,
        changes: &P,
        channel: &mut pristine::ChannelRef<Self>,
        state: pristine::Merkle,
        extra: &[pristine::Hash],
        prefix: &mut I,
        arch: &mut A,
    ) -> Result<Vec<output::Conflict>, anyhow::Error> {
        let mut unrecord = Vec::new();
        let mut found = false;
        for (_, (h, m)) in self.changeid_rev_log(&channel.borrow(), None) {
            if m == state {
                found = true;
                break;
            } else {
                unrecord.push(h)
            }
        }
        debug!("unrecord = {:?}", unrecord);
        if found {
            for h in unrecord.drain(..) {
                let h = self.get_external(h).unwrap();
                self.unrecord(changes, channel, &h)?;
            }
            for app in extra.iter() {
                self.apply_change_rec(changes, channel, *app)?
            }
            output::archive(changes, self, channel, prefix, arch)
        } else {
            Err((Error::StateNotFound { state }).into())
        }
    }
}

pub trait TxnTExt: pristine::TxnT {
    fn is_directory(&self, inode: pristine::Inode) -> bool {
        fs::is_directory(self, inode)
    }

    fn is_tracked(&self, path: &str) -> bool {
        fs::is_tracked(self, path)
    }

    fn iter_working_copy<'txn>(&'txn self) -> WorkingCopyIterator<'txn, Self> {
        fs::iter_working_copy(self, pristine::Inode::ROOT)
    }

    fn has_change(
        &self,
        channel: &pristine::ChannelRef<Self>,
        hash: pristine::Hash,
    ) -> Option<u64> {
        let cid = if let Some(c) = self.get_internal(hash) {
            c
        } else {
            return None;
        };
        self.get_changeset(&channel.borrow().changes, cid, None)
    }

    fn log<'channel, 'txn>(
        &'txn self,
        channel: &'channel pristine::Channel<Self>,
        from: u64,
    ) -> Log<'txn, Self> {
        Log {
            txn: self,
            iter: self.changeid_log(channel, from),
        }
    }

    fn reverse_log<'channel, 'txn>(
        &'txn self,
        channel: &'channel pristine::Channel<Self>,
        from: Option<u64>,
    ) -> RevLog<'txn, Self> {
        RevLog {
            txn: self,
            iter: self.changeid_rev_log(channel, from),
        }
    }

    fn get_changes(
        &self,
        channel: &pristine::ChannelRef<Self>,
        n: u64,
    ) -> Option<(pristine::Hash, pristine::Merkle)> {
        self.get_revchangeset(&channel.borrow().revchanges, n, None)
            .map(|(h, m)| (self.get_external(h).unwrap(), m))
    }

    fn get_revchanges(
        &self,
        channel: &pristine::ChannelRef<Self>,
        h: pristine::Hash,
    ) -> Option<u64> {
        if let Some(h) = self.get_internal(h) {
            self.get_changeset(&channel.borrow().changes, h, None)
        } else {
            None
        }
    }

    fn touched_files<'txn>(&'txn self, h: pristine::Hash) -> Option<Touched<'txn, Self>> {
        if let Some(id) = self.get_internal(h) {
            Some(Touched {
                txn: self,
                iter: self.iter_rev_touched_files(id, None),
                id,
            })
        } else {
            None
        }
    }

    fn find_oldest_path<C: changestore::ChangeStore>(
        &self,
        changes: &C,
        channel: &pristine::ChannelRef<Self>,
        position: pristine::Position<pristine::Hash>,
    ) -> Result<(String, bool), anyhow::Error> {
        let position = pristine::Position {
            change: self.get_internal(position.change).unwrap(),
            pos: position.pos,
        };
        fs::find_path(changes, self, &channel.borrow(), false, position)
    }

    fn find_youngest_path<C: changestore::ChangeStore>(
        &self,
        changes: &C,
        channel: &pristine::ChannelRef<Self>,
        position: pristine::Position<pristine::Hash>,
    ) -> Result<(String, bool), anyhow::Error> {
        let position = pristine::Position {
            change: self.get_internal(position.change).unwrap(),
            pos: position.pos,
        };
        fs::find_path(changes, self, &channel.borrow(), true, position)
    }

    fn follow_oldest_path<C: changestore::ChangeStore>(
        &self,
        changes: &C,
        channel: &pristine::ChannelRef<Self>,
        path: &str,
    ) -> Result<(pristine::Position<pristine::ChangeId>, bool), anyhow::Error> {
        fs::follow_oldest_path(changes, self, channel, path)
    }

    fn output_file<C: changestore::ChangeStore, V: vertex_buffer::VertexBuffer>(
        &self,
        changes: &C,
        channel: &pristine::ChannelRef<Self>,
        v0: pristine::Position<pristine::ChangeId>,
        out: &mut V,
    ) -> Result<(), anyhow::Error> {
        let mut forward = Vec::new();
        let channel = channel.borrow();
        let mut graph = alive::retrieve(self, &channel, v0);
        alive::output_graph(changes, self, &channel, out, &mut graph, &mut forward)?;
        Ok(())
    }

    fn archive<'a, C: changestore::ChangeStore, A: Archive>(
        &self,
        changes: &C,
        channel: &pristine::ChannelRef<Self>,
        arch: &mut A,
    ) -> Result<Vec<output::Conflict>, anyhow::Error> {
        output::archive(changes, self, channel, &mut std::iter::empty(), arch)
    }

    fn archive_prefix<'a, C: changestore::ChangeStore, I: Iterator<Item = &'a str>, A: Archive>(
        &self,
        changes: &C,
        channel: &pristine::ChannelRef<Self>,
        prefix: &mut I,
        arch: &mut A,
    ) -> Result<Vec<output::Conflict>, anyhow::Error> {
        output::archive(changes, self, channel, prefix, arch)
    }
}

pub struct Log<'txn, T: pristine::TxnT> {
    txn: &'txn T,
    iter: pristine::Cursor<
        T,
        &'txn T,
        T::RevchangesetCursor,
        u64,
        (pristine::ChangeId, pristine::Merkle),
    >,
}

impl<'txn, T: pristine::TxnT> Iterator for Log<'txn, T> {
    type Item = (u64, (pristine::Hash, pristine::Merkle));
    fn next(&mut self) -> Option<Self::Item> {
        self.iter
            .next()
            .map(|(n, (c, m))| (n, (self.txn.get_external(c).unwrap(), m)))
    }
}

pub struct RevLog<'txn, T: pristine::TxnT> {
    txn: &'txn T,
    iter: pristine::RevCursor<
        T,
        &'txn T,
        T::RevchangesetCursor,
        u64,
        (pristine::ChangeId, pristine::Merkle),
    >,
}

impl<'txn, T: pristine::TxnT> Iterator for RevLog<'txn, T> {
    type Item = (u64, (pristine::Hash, pristine::Merkle));
    fn next(&mut self) -> Option<Self::Item> {
        self.iter
            .next()
            .map(|(n, (c, m))| (n, (self.txn.get_external(c).unwrap(), m)))
    }
}

pub struct Touched<'txn, T: pristine::TxnT> {
    txn: &'txn T,
    iter: pristine::Cursor<
        T,
        &'txn T,
        T::Rev_touched_filesCursor,
        pristine::ChangeId,
        pristine::Position<pristine::ChangeId>,
    >,
    id: pristine::ChangeId,
}

impl<'txn, T: pristine::TxnT> Iterator for Touched<'txn, T> {
    type Item = pristine::Position<pristine::Hash>;
    fn next(&mut self) -> Option<Self::Item> {
        while let Some((cid, file)) = self.iter.next() {
            if cid > self.id {
                return None;
            } else if cid == self.id {
                let change = self.txn.get_external(file.change).unwrap();
                return Some(pristine::Position {
                    change,
                    pos: file.pos,
                });
            }
        }
        None
    }
}

#[doc(hidden)]
#[derive(Debug, Default, Clone)]
pub struct Timers {
    pub alive_output: std::time::Duration,
    pub alive_graph: std::time::Duration,
    pub alive_retrieve: std::time::Duration,
    pub alive_contents: std::time::Duration,
    pub alive_write: std::time::Duration,
    pub record: std::time::Duration,
    pub apply: std::time::Duration,
    pub repair_context: std::time::Duration,
    pub check_cyclic_paths: std::time::Duration,
    pub find_alive: std::time::Duration,
}
use std::sync::Mutex;
lazy_static! {
    pub static ref TIMERS: Mutex<Timers> = Mutex::new(Timers {
        alive_output: std::time::Duration::from_secs(0),
        alive_graph: std::time::Duration::from_secs(0),
        alive_retrieve: std::time::Duration::from_secs(0),
        alive_contents: std::time::Duration::from_secs(0),
        alive_write: std::time::Duration::from_secs(0),
        record: std::time::Duration::from_secs(0),
        apply: std::time::Duration::from_secs(0),
        repair_context: std::time::Duration::from_secs(0),
        check_cyclic_paths: std::time::Duration::from_secs(0),
        find_alive: std::time::Duration::from_secs(0),
    });
}
#[doc(hidden)]
pub fn reset_timers() {
    *TIMERS.lock().unwrap() = Timers::default();
}
#[doc(hidden)]
pub fn get_timers() -> Timers {
    TIMERS.lock().unwrap().clone()
}