pijul_org / pijul

Fixing the current conflict, plus the code that allowed to create this patch

By blabla on February 23, 2019
This patch is not signed.
6dqTtH4M157Uh1RP2zVZ8YqKRqT3DQ761iMhdpAuyuEJary5sLSpMzJsAfM5EJzGULPzJip16baQSgrGeVpy4ocU
This patch is in the following branches:
latest
master
testing








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
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698

699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799



            for i in old .. (old+len) {
                return
            debug!("status of {:?}: {:?}", old+i, diff.status.get(&(old + i)));
                debug!("up_context_idx = {:?} ({:?})", up_context_idx, diff.lines_a[up_context_idx]);
            debug!("down_context_idx = {:?} ({:?})", down_context_idx, diff.lines_a[down_context_idx]);
use backend::*;
use graph;
use graph::Graph;
use patch;
use patch::{Change, ChangeContext, Record};
use {GenericTxn, Result};
use fs_representation::RepoPath;

use conflict;
use diffs;
use rand;
use record::is_text;
use sanakirja::value::Value;
use std;
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use std::rc::Rc;

#[derive(Debug, PartialEq, Eq, Hash)]
struct Line<'a>(&'a [u8]);

struct Contents<'a, T: Transaction + 'a> {
    key: Key<PatchId>,
    contents: Value<'a, T>,
    before_conflict_line: bool,
}

impl<'a, T: Transaction + 'a> std::fmt::Debug for Contents<'a, T> {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(
            f,
            "Contents {{ key: {:?}, before_conflict_line: {:?}, {:?} }}",
            self.key,
            self.before_conflict_line,
            self.contents.into_cow()
        )
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
enum Status {
    Begin,
    Next,
    End,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Algorithm {
    Myers,
    Patience,
}

impl Default for Algorithm {
    fn default() -> Self {
        Algorithm::Myers
    }
}

struct Diff<'a, 'b, T: Transaction + 'a> {
    conflicts_a: Vec<(usize, usize, bool)>,
    lines_a: Vec<Key<PatchId>>,
    contents_a: Vec<Contents<'a, T>>,
    lines_b: &'b [Line<'b>],
    conflict_starts: HashMap<usize, usize>,
    conflict_ends: HashMap<usize, usize>,
    conflict_down_contexts: HashMap<usize, Vec<LineId>>,
    status: HashMap<usize, Status>,
    conflict_stack: Vec<(usize, usize, bool)>,
    conflict_counter: usize,
    solved_conflicts: HashSet<usize>,
}

impl<'a, 'b, T: Transaction + 'a> graph::LineBuffer<'a, T> for Diff<'a, 'b, T> {
    fn output_line(&mut self, k: &Key<PatchId>, c: Value<'a, T>) -> Result<()> {
        if c.len() != 0 {
            self.conflicts_a.push(*self.conflict_stack.last().unwrap());
            self.lines_a.push(*k);
            self.contents_a.push(Contents {
                key: *k,
                contents: c,
                before_conflict_line: false,
            });
        }
        Ok(())
    }

    fn begin_conflict(&mut self) -> Result<()> {
        let len = self.contents_a.len();
        self.conflict_counter += 1;
        self.conflict_stack.push((self.conflict_counter, 0, false));
        self.conflict_starts.insert(self.conflict_counter, len);
        self.status.insert(len, Status::Begin);
        self.output_conflict_marker(conflict::START_MARKER)
    }

    fn begin_zombie_conflict(&mut self) -> Result<()> {
        let len = self.contents_a.len();
        self.conflict_counter += 1;
        self.conflict_stack.push((self.conflict_counter, 0, true));
        self.conflict_starts.insert(self.conflict_counter, len);
        self.status.insert(len, Status::Begin);
        self.output_conflict_marker(conflict::START_MARKER)
    }

    fn end_conflict(&mut self) -> Result<()> {
        let len = self.contents_a.len();
        self.output_conflict_marker(conflict::END_MARKER)?;
        self.status.insert(len, Status::End);
        let (conflict, _, _) = self.conflict_stack.pop().unwrap();
        self.conflict_ends.insert(conflict, len);
        Ok(())
    }

    fn conflict_next(&mut self) -> Result<()> {
        self.status.insert(self.contents_a.len(), Status::Next);
        if let Some((_, ref mut side, _)) = self.conflict_stack.last_mut() {
            *side += 1
        }
        self.output_conflict_marker(conflict::SEPARATOR)
    }

    fn output_conflict_marker(&mut self, marker: &'a str) -> Result<()> {
        let mut ends_with_newline = true;
        if self.contents_a.len() > 1 {
            for chunk in self.contents_a[self.contents_a.len() - 1].contents.clone() {
                debug!(
                    "chunk {:?} {:?}",
                    std::str::from_utf8(chunk),
                    chunk.ends_with(b"\n")
                );
                ends_with_newline = chunk.ends_with(b"\n")
            }
        };
        debug!("ends_with_newline {:?}", ends_with_newline);
        let (conflict, _, is_zombie) = *self.conflict_stack.last().unwrap();
        self.conflicts_a.push((conflict, 0, is_zombie));
        if let Some(l) = self.contents_a.last_mut() {
            l.before_conflict_line = true
        }
        if ends_with_newline {
            self.lines_a.push(ROOT_KEY);
            self.contents_a.push(Contents {
                key: ROOT_KEY,
                contents: Value::from_slice(&marker.as_bytes()[1..]),
                before_conflict_line: false,
            })
        } else {
            self.lines_a.push(ROOT_KEY);
            self.contents_a.push(Contents {
                key: ROOT_KEY,
                contents: Value::from_slice(marker.as_bytes()),
                before_conflict_line: false,
            });
        }
        Ok(())
    }
}

impl<'a, 'b, T: Transaction + 'b> PartialEq<Contents<'b, T>> for Line<'a> {
    fn eq(&self, b: &Contents<T>) -> bool {
        debug!("comparing {:?} {:?}", self, b);
        if self.0.last() == Some(&0xa) {
            if b.key.is_root() {
                // Conflict
                let b = b.contents.into_cow();
                if b[0] == 0xa {
                    (&self.0[..]).eq(&b[1..])
                } else {
                    (&self.0[..]).eq(&b[..])
                }
            } else if b.before_conflict_line {
                // We might have added an artificial line at the end
                // of a when we output it. Fix this.
                if self.0.len() as u64 - 1 == b.contents.len() {
                    (&self.0[..self.0.len() - 1]).eq(&b.contents)
                } else {
                    self.0.eq(&b.contents)
                }
            } else {
                self.0.eq(&b.contents)
            }
        } else {
            self.0.eq(&b.contents)
        }
    }
}

impl<'b, T: Transaction + 'b> PartialEq<Contents<'b, T>> for Contents<'b, T> {
    fn eq(&self, b: &Contents<T>) -> bool {
        self.contents == b.contents
    }
}
impl<'b, T: Transaction + 'b> Eq for Contents<'b, T> {}
impl<'b, T: Transaction + 'b> std::hash::Hash for Contents<'b, T> {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.contents.hash(state)
    }
}

struct Replace {
    old: usize,
    old_len: usize,
    new: usize,
    new_len: usize,
}
struct D {
    r: Vec<Replace>,
    deleted: HashMap<usize, bool>,
}
impl diffs::Diff for D {
    type Error = ();
    fn delete(&mut self, old: usize, old_len: usize) -> std::result::Result<(), ()> {
        for i in old..old + old_len {
            self.deleted.insert(i, false);
        }
        self.r.push(Replace {
            old,
            old_len,
            new: 0,
            new_len: 0,
        });
        Ok(())
    }
    fn insert(&mut self, old: usize, new: usize, new_len: usize) -> std::result::Result<(), ()> {
        self.r.push(Replace {
            old,
            old_len: 0,
            new,
            new_len,
        });
        Ok(())
    }
    fn replace(
        &mut self,
        old: usize,
        old_len: usize,
        new: usize,
        new_len: usize,
    ) -> std::result::Result<(), ()> {
        for i in old..old + old_len {
            self.deleted.insert(i, true);
        }
        self.r.push(Replace {
            old,
            old_len,
            new,
            new_len,
        });
        Ok(())
    }
}

struct DiffProducer<'a> {
    line_num: &'a mut LineId,
    inode: Key<Option<Hash>>,
    inode_internal: Key<Option<PatchId>>,
    file: Rc<RepoPath<PathBuf>>,
    conflict_insertions: HashMap<usize, LineId>,
}

impl<A: Transaction, R: rand::Rng> GenericTxn<A, R> {
    pub fn diff<'a>(
        &'a self,
        algorithm: Algorithm,
        inode: Key<Option<Hash>>,
        branch: &'a Branch,
        file: Rc<RepoPath<PathBuf>>,
        line_num: &mut LineId,
        actions: &mut Vec<Record<ChangeContext<PatchId>>>,
        redundant: &mut Vec<(Key<PatchId>, Edge)>,
        a: &mut Graph,
        lines_b: &[u8],
    ) -> Result<()> {
        // First outputting A
        let inode_internal = Key {
            patch: Some(
                self.get_internal(inode.patch.as_ref().unwrap().as_ref())
                    .unwrap(),
            ),
            line: inode.line,
        };
        let mut lines_b_ = Vec::new();
        let mut d = Diff {
            lines_a: Vec::with_capacity(2 * lines_b.len()),
            contents_a: Vec::with_capacity(2 * lines_b.len()),
            conflicts_a: Vec::with_capacity(2 * lines_b.len()),
            lines_b: &[],
            conflict_starts: HashMap::new(),
            conflict_ends: HashMap::new(),
            conflict_down_contexts: HashMap::new(),
            status: HashMap::new(),
            conflict_counter: 0,
            conflict_stack: vec![(0, 0, false)],
            solved_conflicts: HashSet::new(),
        };
        self.output_file(branch, &mut d, a, redundant)?;

        // Now cutting B
        if is_text(&lines_b) {
            let mut i = 0;
            let mut j = 0;

            while j < lines_b.len() {
                if lines_b[j] == 0xa {
                    lines_b_.push(Line(&lines_b[i..j + 1]));
                    i = j + 1
                }
                j += 1;
            }
            if i < j {
                lines_b_.push(Line(&lines_b[i..]))
            }
        } else {
            lines_b_.push(Line(&lines_b[..]))
        };
        d.lines_b = &lines_b_;

        // And finally diffing
        let contents_a = std::mem::replace(&mut d.contents_a, Vec::new());
        debug!(
        for line in d.lines_a.iter() {
            debug!("line: {:?}", line);
        }

        trace!(
            "contents_a {:?}",
            contents_a.iter().map(|x| &x.contents).collect::<Vec<_>>()
        );
        debug!("contents_b {:?}", lines_b_);
        trace!("contents_b {:?}", lines_b_);
        let mut dd = diffs::Replace::new(D {
            r: Vec::with_capacity(d.lines_a.len() + lines_b_.len()),
            deleted: HashMap::new(),
        });
        match algorithm {
            Algorithm::Patience => {
                let a = contents_a.as_slice();
                diffs::patience::diff(&mut dd, a, 0, a.len(), &lines_b_, 0, lines_b_.len()).unwrap()
            }
            Algorithm::Myers => {
                let a = contents_a.as_slice();
                diffs::myers::diff(&mut dd, a, 0, a.len(), &lines_b_, 0, lines_b_.len()).unwrap()
            }
        }
        let dd = dd.into_inner();
        let mut diffprod = DiffProducer {
            line_num,
            inode,
            inode_internal,
            file,
            conflict_insertions: HashMap::new(),
        };
        for r in 0..dd.r.len() {
            if dd.r[r].new_len == 0 {
                let old = dd.r[r].old;
                let len = dd.r[r].old_len;
                self.diff_delete(branch, &mut diffprod, actions, &mut d, old, len)
            } else {
                self.diff_replace(branch, &mut diffprod, actions, &mut d, &dd, r)
            }
        }
        debug!("Diff ended");
        Ok(())
    }

    /// Insert epsilon-edges if we're deleting conflict markers.
    fn order_conflict_sides(
        &self,
        branch: &Branch,
        dp: &mut DiffProducer,
        actions: &mut Vec<Record<ChangeContext<PatchId>>>,
        diff: &mut Diff<A>,
        old: usize,
        len: usize,
    ) {
        if diff.lines_a[old..old + len].iter().any(|x| x.is_root())
            && !diff.lines_a[old - 1].is_root()
        if !diff.lines_a[old - 1].is_root()
            && !diff.lines_a[old + len].is_root()
            && !self.is_connected(branch, diff.lines_a[old - 1], diff.lines_a[old + len])
        {
            let mut is_conflict = false;
            for i in old..(old + len) {
                match diff.status.get(&i) {
                    Some(&Status::Next) => is_conflict = true,
                    Some(_) => return, // we're not reordering a conflict.
                    _ => {}
                }
            }
            if !is_conflict {
                return;
            }
            let from_patch = diff.lines_a[old - 1];
            let to_patch = diff.lines_a[old + len];
            debug!("Conflict reordering");
            debug!("Conflict reordering {:?} {:?}", from_patch, to_patch);
            actions.push(Record::Change {
                change: Change::NewNodes {
                    up_context: vec![Key {
                        patch: Some(from_patch.patch),
                        line: from_patch.line,
                    }],
                    down_context: vec![Key {
                        patch: Some(to_patch.patch),
                        line: to_patch.line,
                    }],
                    line_num: *dp.line_num,
                    flag: EdgeFlags::EPSILON_EDGE,
                    nodes: vec![Vec::new()],
                    inode: dp.inode.clone(),
                },
                replacement: None,
                old_line: old,
                new_line: 0,
                file: dp.file.clone(),
            });
            *dp.line_num += 1
        }
    }

    /// Actually delete the lines that need to be deleted.
    fn delete_lines(
        &self,
        branch: &Branch,
        dp: &mut DiffProducer,
        actions: &mut Vec<Record<ChangeContext<PatchId>>>,
        diff: &mut Diff<A>,
        old: usize,
        len: usize,
    ) {
        let mut edges = Vec::new();
        let flag0 = EdgeFlags::PARENT_EDGE;
        let flag1 = EdgeFlags::PARENT_EDGE | EdgeFlags::PSEUDO_EDGE | EdgeFlags::EPSILON_EDGE;

        debug!("Delete_lines {:?} {:?}", old, len);
        for (i, &key) in diff.lines_a[old..(old + len)].iter().enumerate() {
            debug!("status of {:?}: {:?}", old + i, diff.status.get(&(old + i)));
            match diff.status.get(&(old + i)) {
                Some(&Status::Begin) => {
                    diff.solved_conflicts.insert(diff.conflicts_a[old + i].0);
                    continue;
                }
                None => {}
                _ => continue,
            }
            let ext_hash = self.external_hash(key.patch);
            for v in self
                .iter_adjacent(&branch, key, flag0, flag1)
                .filter(|v| !v.flag.contains(EdgeFlags::EPSILON_EDGE))
            {
                if v.flag.contains(EdgeFlags::PSEUDO_EDGE) {
                    let edge = Edge {
                        flag: EdgeFlags::DELETED_EDGE | EdgeFlags::PARENT_EDGE,
                        introduced_by: ROOT_PATCH_ID,
                        dest: ROOT_KEY
                    };
                    let mut edges = self.iter_nodes(&branch, Some((key, Some(edge))));
                    match edges.next() {
                        Some((k_, v_)) if k_ == key && v_.flag == edge.flag => {
                            // `key` has at least one deleted edge
                            // pointing to it, so key is a zombie. We
                            // need to confirm that it is actually
                            // deleted by deleting edge `v`.
                            debug!("zombie edge: {:?} {:?}", key, v);
                        }
                        x => {
                            // The target of this edge is not deleted,
                            // and not a zombie vertex.  We can ignore
                            // this pseudo-edge, as deleting all alive
                            // edges to the target will have the same
                            // effect.
                            debug!("not a zombie: {:?}", x);
                            continue;
                        }
                    }
                };
                debug!("delete: {:?} {:?}", key, v);
                debug!("actually deleting");
                edges.push(patch::NewEdge {
                    from: Key {
                        patch: Some(ext_hash.to_owned()),
                        line: key.line.clone(),
                    },
                    to: Key {
                        patch: Some(self.external_hash(v.dest.patch).to_owned()),
                        line: v.dest.line.clone(),
                    },
                    introduced_by: Some(self.external_hash(v.introduced_by).to_owned()),
                });
            }
        }

        if !edges.is_empty() {
            actions.push(Record::Change {
                change: Change::NewEdges {
                    edges,
                    previous: EdgeFlags::PARENT_EDGE,
                    flag: EdgeFlags::PARENT_EDGE | EdgeFlags::DELETED_EDGE,
                    inode: dp.inode.clone(),
                },
                replacement: None,
                old_line: old,
                new_line: 0,
                file: dp.file.clone(),
            })
        }
    }

    fn resurrect_zombies(
        &self,
        branch: &Branch,
        dp: &mut DiffProducer,
        actions: &mut Vec<Record<ChangeContext<PatchId>>>,
        diff: &mut Diff<A>,
        old: usize,
        len: usize,
    ) {
        // If the conflict markers of zombie lines have been deleted,
        // resurect the zombies.
        let mut i = old + len;
        let mut resurrections = Vec::new();
        let mut dead_parents = Vec::new();
        debug!("Resurrect_zombies {:?} {:?}", old, len);
        while i < diff.lines_a.len() {
            let key = diff.lines_a[i];
            let (conflict, _, is_zombie) = diff.conflicts_a[i];
            debug!("resurrecting {:?} {:?}", key, is_zombie);
            debug!("solved ? {:?} {:?}", conflict, diff.solved_conflicts);
            if is_zombie && !key.is_root() && diff.solved_conflicts.contains(&conflict) {
                // Resurect the zombie, i.e. remove its deleted edges.
                let flag0 = EdgeFlags::PARENT_EDGE | EdgeFlags::DELETED_EDGE;
                let ext_hash = self.external_hash(key.patch);
                for v in self.iter_adjacent(&branch, key, flag0, flag0) {
                    debug!("resurrecting {:?}: {:?}", key, v);
                    let v_hash = self.external_hash(v.dest.patch).to_owned();
                    resurrections.push(patch::NewEdge {
                        from: Key {
                            patch: Some(ext_hash.to_owned()),
                            line: key.line.clone(),
                        },
                        to: Key {
                            patch: Some(v_hash.clone()),
                            line: v.dest.line.clone(),
                        },
                        introduced_by: Some(self.external_hash(v.introduced_by).to_owned()),
                    });
                    // We must re-kill the parents to make sure they
                    // don't get context-fixed when we apply this
                    // patch.
                    for w in self.iter_adjacent(&branch, v.dest, flag0, flag0) {
                        dead_parents.push(patch::NewEdge {
                            from: Key {
                                patch: Some(v_hash.clone()),
                                line: v.dest.line.clone(),
                            },
                            to: Key {
                                patch: Some(self.external_hash(w.dest.patch).to_owned()),
                                line: w.dest.line.clone(),
                            },
                            introduced_by: Some(self.external_hash(w.introduced_by).to_owned()),
                        })
                    }
                }
                i += 1
            } else {
                break;
            }
        }
        if !resurrections.is_empty() {
            actions.push(Record::Change {
                change: Change::NewEdges {
                    edges: resurrections,
                    previous: EdgeFlags::PARENT_EDGE | EdgeFlags::DELETED_EDGE,
                    flag: EdgeFlags::PARENT_EDGE,
                    inode: dp.inode.clone(),
                },
                replacement: None,
                file: dp.file.clone(),
                old_line: old,
                new_line: 0,
            });
        }
        if !dead_parents.is_empty() {
            actions.push(Record::Change {
                change: Change::NewEdges {
                    edges: dead_parents,
                    previous: EdgeFlags::PARENT_EDGE | EdgeFlags::DELETED_EDGE,
                    flag: EdgeFlags::PARENT_EDGE | EdgeFlags::DELETED_EDGE,
                    inode: dp.inode.clone(),
                },
                replacement: None,
                file: dp.file.clone(),
                old_line: old,
                new_line: 0,
            });
        }
    }

    fn diff_delete(
        &self,
        branch: &Branch,
        dp: &mut DiffProducer,
        actions: &mut Vec<Record<ChangeContext<PatchId>>>,
        diff: &mut Diff<A>,
        old: usize,
        len: usize,
    ) {
        debug!("delete {:?} {:?}", old, len);
        debug!("diff_delete {:?} {:?}", old, len);
        if old > 0 && old + len < diff.lines_a.len() {
            self.order_conflict_sides(branch, dp, actions, diff, old, len)
        }

        self.delete_lines(branch, dp, actions, diff, old, len);
        self.resurrect_zombies(branch, dp, actions, diff, old, len);
    }

    fn get_up_context(
        &self,
        dp: &mut DiffProducer,
        diff: &mut Diff<A>,
        old: usize,
    ) -> Vec<Key<Option<PatchId>>> {
        if old == 0 {
            vec![dp.inode_internal]
        } else {
            let mut up_context_idx = old - 1;
            loop {
                debug!("up_context_idx = {:?}", up_context_idx);
                debug!(
                    "up_context_idx = {:?} ({:?})",
                    up_context_idx, diff.lines_a[up_context_idx]
                );
                match diff.status.get(&up_context_idx) {
                    None => {
                        break vec![Key {
                            patch: Some(diff.lines_a[up_context_idx].patch),
                            line: diff.lines_a[up_context_idx].line,
                        }];
                    }
                    Some(&Status::Begin) => {
                        let conflict = diff.conflicts_a[up_context_idx].0;
                        if let Some(&line) = dp.conflict_insertions.get(&conflict) {
                            break vec![Key { patch: None, line }];
                        } else if up_context_idx == 0 {
                            break vec![dp.inode_internal];
                        } else {
                            up_context_idx -= 1
                        }
                    }
                    Some(&Status::Next) => {
                        let conflict = diff.conflicts_a[up_context_idx].0;
                        if let Some(&line) = dp.conflict_insertions.get(&conflict) {
                            break vec![Key { patch: None, line }];
                        } else {
                            let conflict = diff.conflicts_a[up_context_idx].0;
                            up_context_idx = *diff.conflict_starts.get(&conflict).unwrap();
                        }
                    }
                    Some(&Status::End) => {
                        // The up context is all the sides above this end marker
                        let conflict = diff.conflicts_a[up_context_idx].0;
                        let conflict_start = *diff.conflict_starts.get(&conflict).unwrap();
                        let mut up_context = Vec::new();

                        if let Some(ref up) = diff.conflict_down_contexts.get(&up_context_idx) {
                            up_context.extend(up.iter().map(|&x| Key {
                                patch: None,
                                line: x,
                            }));
                        }

                        let mut on = true;
                        while up_context_idx > conflict_start {
                            on |= diff.status.get(&up_context_idx).is_some()
                                && diff.conflicts_a[up_context_idx].0 == conflict;
                            if on && diff.status.get(&up_context_idx).is_none() {
                                // This is a real line, add it
                                up_context.push(Key {
                                    patch: Some(diff.lines_a[up_context_idx].patch),
                                    line: diff.lines_a[up_context_idx].line,
                                });
                                on = false
                            }
                            up_context_idx -= 1
                        }
                        assert!(!up_context.is_empty());
                        break up_context;
                    }
                }
            }
        }
    }

    fn get_down_context(
        &self,
        dp: &mut DiffProducer,
        diff: &mut Diff<A>,
        dd: &D,
        old: usize,
        old_len: usize,
        len: usize,
    ) -> Vec<Key<Option<PatchId>>> {
        let mut down_context_idx = old + old_len;
        loop {
            debug!("down_context_idx = {:?}", down_context_idx);
            debug!("down_context_idx = {:?}", down_context_idx);
            if down_context_idx >= diff.lines_a.len() {
                break Vec::new();
            }
            debug!(
                "down_context_idx = {:?} ({:?})",
                down_context_idx, diff.lines_a[down_context_idx]
            );
            match diff.status.get(&down_context_idx) {
                None => {
                    break vec![Key {
                        patch: Some(diff.lines_a[down_context_idx].patch),
                        line: diff.lines_a[down_context_idx].line,
                    }];
                }
                Some(&Status::End) => {
                    let mut e = diff
                        .conflict_down_contexts
                        .entry(down_context_idx)
                        .or_insert(Vec::new());
                    e.push(*dp.line_num + (len - 1));
                    down_context_idx += 1
                }
                Some(&Status::Next) => {
                    let conflict = diff.conflicts_a[down_context_idx].0;
                    down_context_idx = *diff.conflict_ends.get(&conflict).unwrap();
                }
                Some(&Status::Begin) => {
                    // The down context is all the sides below this beginning marker
                    let conflict = diff.conflicts_a[down_context_idx].0;
                    dp.conflict_insertions
                        .insert(conflict, *dp.line_num + (len - 1));
                    let conflict_end = *diff.conflict_ends.get(&conflict).unwrap();
                    let mut down_context = Vec::new();
                    let mut on = true;
                    while down_context_idx < conflict_end {
                        on |= diff.status.get(&down_context_idx).is_some()
                            && diff.conflicts_a[down_context_idx].0 == conflict;
                        if on && diff.status.get(&down_context_idx).is_none() {
                            match dd.deleted.get(&down_context_idx) {
                                Some(true) => {
                                    // If the down context line has
                                    // been replaced, we'll insert the
                                    // edge later (when dealing with
                                    // the replacement).
                                    on = false
                                }
                                Some(false) => {
                                    // If the line has been
                                    // deleted, wait for the next
                                    // appropriate down context
                                    // line.
                                }
                                None => {
                                    // If the down context has not
                                    // been deleted, just add it
                                    // as a down context.
                                    down_context.push(Key {
                                        patch: Some(diff.lines_a[down_context_idx].patch),
                                        line: diff.lines_a[down_context_idx].line,
                                    });
                                    on = false
                                }
                            }
                        }
                        down_context_idx += 1
                    }
                    assert!(!down_context.is_empty());
                    break down_context;
                }
            }
        }
    }

    fn diff_replace(
        &self,
        branch: &Branch,
        dp: &mut DiffProducer,
        actions: &mut Vec<Record<ChangeContext<PatchId>>>,
        diff: &mut Diff<A>,
        dd: &D,
        r: usize,
    ) {
        let old = dd.r[r].old;
        let old_len = dd.r[r].old_len;
        let from_new = dd.r[r].new;
        let len = dd.r[r].new_len;
        debug!("replace {:?} {:?} {:?} {:?}", old, old_len, from_new, len);
        if old_len > 0 {
            self.diff_delete(branch, dp, actions, diff, old, old_len);
        }
        // Inserting between old and old+1. Both might be conflict
        // markers.
        let up_context = self.get_up_context(dp, diff, old);
        let down_context = self.get_down_context(dp, diff, dd, old, old_len, len);

        for i in &diff.lines_b[from_new..(from_new + len)] {
            debug!("{:?}", std::str::from_utf8(&i.0));
        }

        let change = Change::NewNodes {





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

357

358



359


362



366


369


372


375

use backend::{MutTxn, ROOT_INODE};
/*
            }
            Ok(())
*/
//! Layout of a repository (files in `.pijul`) on the disk. This
//! module exports both high-level functions that require no knowledge
//! of the repository, and lower-level constants documented on
//! [pijul.org/documentation/repository](https://pijul.org/documentation/repository),
//! used for instance for downloading files from remote repositories.

use super::Repository;
use backend::DEFAULT_BRANCH;
use backend::{Hash, HashRef};
use backend::{MutTxn, ROOT_INODE};
use bs58;
use flate2;
use ignore::overrides::OverrideBuilder;
use ignore::WalkBuilder;
use patch::{Patch, PatchHeader};
use rand::distributions::Alphanumeric;
use rand::Rng;
use std;
use std::fs::canonicalize;
use std::fs::{create_dir_all, metadata, File};
use std::io::{BufReader, Read, Write};
use std::path::{Path, PathBuf};
use backend::GenericTxn;
use {Result, Error};
use std::ffi::OsStr;

/// Given a Path-like type P, RepoPath<P> is a 'P' relative to some fs_representation::RepoRoot
#[derive(Debug, Clone, PartialEq, Eq, Hash, Copy)]
pub struct RepoPath<P: ?Sized>(pub P);

pub fn in_repo_root() -> RepoPath<&'static Path> {
    RepoPath(Path::new(""))
}

impl RepoPath<std::path::PathBuf> {
    pub fn push(&mut self, x: &str) {
        self.0.push(x)
    }

    pub fn pop(&mut self) -> bool {
        self.0.pop()
    }

    pub fn new() -> Self {
        RepoPath(PathBuf::new())
    }
    
    pub fn as_ref(&self) -> RepoPath<&Path> {
        RepoPath(self.0.as_ref())
    }

    pub fn set_file_name(&mut self, filename: &OsStr) {
        self.0.set_file_name(filename)
    }

    pub fn from_string(path: String) -> Self {
        RepoPath(PathBuf::from(path))
    }
}

    
impl<P: AsRef<Path>> RepoPath<P> {
    pub fn as_path(&self) -> &std::path::Path {
        self.0.as_ref()
    }
}

impl<P: AsRef<Path>> RepoPath<P> {    
    pub fn parent(&self) -> Option<RepoPath<&std::path::Path>> {
        self.as_path().parent().map(RepoPath)
    }

    pub fn file_name(&self) -> Option<&OsStr> {
        self.as_path().file_name()
    }

    pub fn split(&self) -> Option<(RepoPath<&std::path::Path>, &OsStr)> {
        self.parent().map(|p| {(p, self.file_name().expect("file_name and parent should be consistent"))})
    }

    pub fn components(&self) -> std::path::Components {
        self.as_path().components()
    }

    pub fn to_path_buf(&self) -> PathBuf {
        self.as_path().to_path_buf()
    }

    pub fn display(&self) -> std::path::Display {
        self.as_path().display()
    }

    
    pub fn to_owned(&self) -> RepoPath<PathBuf> {
        RepoPath(self.0.as_ref().to_path_buf())
    }    
    
    pub fn join(&self, path: &Path) -> RepoPath<PathBuf> {
        // TODO: check that the joined path is indeed inside the repo
        let joined_path = self.as_path().join(path);
        RepoPath(joined_path)
    }
}

impl<P: AsRef<Path>> RepoPath<P> {
    pub fn empty(&self) -> bool {
        self.as_path() == Path::new("")
    }
}

/// A directory at the root of a pijul repository.
#[derive(Clone, Copy, Debug)]
pub struct RepoRoot<P: AsRef<Path>> {
    pub repo_root: P,
}

/// Name of the root directory, i.e. `.pijul`.
pub const PIJUL_DIR_NAME: &'static str = ".pijul";

/// Basename of the changes file for branch `br`. This file is only
/// used when pulling/pushing over HTTP (where calling remote programs
/// to list patches is impossible).
///
/// The changes file contains the same information as the one returned by `pijul log --hash-only`.
pub fn branch_changes_base_path(b: &str) -> String {
    "changes.".to_string() + &bs58::encode(b.as_bytes()).into_string()
}

/// Basename of the patch corresponding to the given patch hash.
pub fn patch_file_name(hash: HashRef) -> String {
    hash.to_base58() + ".gz"
}

impl<P: AsRef<Path>> RepoRoot<P> {
    /// The subdirectory of `self` with pijul's metadata
    pub fn repo_dir(&self) -> PathBuf {
        self.repo_root.as_ref().join(PIJUL_DIR_NAME)
    }

    /// Directory where the pristine of `self` is.
    /// For instance, if the repository in in `/a/b`,
    /// `self.pristine_dir() is `/a/b/.pijul/pristine`.
    pub fn pristine_dir(&self) -> PathBuf {
        self.repo_dir().join("pristine")
    }

    /// Directory where the patches are. `patches_dir("/a/b") = "/a/b/.pijul/patches"`.
    pub fn patches_dir(&self) -> PathBuf {
        self.repo_dir().join("patches")
    }

    /// The location of the changes file for theb branch `b`.
    ///
    /// The changes file contains the same information as the one returned by `pijul log --hash-only`.
    pub fn branch_changes_file(&self, b: &str) -> PathBuf {
        self.repo_dir().join(branch_changes_base_path(b))
    }

    /// The meta file, where user preferences are stored.
    pub fn meta_file(&self) -> PathBuf {
        self.repo_dir().join("meta.toml")
    }

    /// The id file is used for remote operations, to identify a
    /// repository and save bandwidth when the remote state is partially
    /// known.
    pub fn id_file(&self) -> PathBuf {
        self.repo_dir().join("id")
    }

    /// Read a complete patch.
    pub fn read_patch(&self, hash: HashRef) -> Result<Patch> {
        let patch_dir = self.patches_dir();
        let path = patch_dir.join(&patch_file_name(hash));
        let f = File::open(path)?;
        let mut f = BufReader::new(f);
        let (_, _, patch) = Patch::from_reader_compressed(&mut f)?;
        Ok(patch)
    }

    /// Read a patch, but without the "changes" part, i.e. the actual
    /// contents of the patch.
    pub fn read_patch_nochanges(&self, hash: HashRef) -> Result<PatchHeader> {
        let patch_dir = self.patches_dir();
        let path = patch_dir.join(&patch_file_name(hash));
        let f = File::open(path)?;
        let mut f = flate2::bufread::GzDecoder::new(BufReader::new(f));
        Ok(PatchHeader::from_reader_nochanges(&mut f)?)
    }

    /// Read a patch, but without the "changes" part, i.e. the actual
    /// contents of the patch.
    pub fn read_dependencies(&self, hash: HashRef) -> Result<Vec<Hash>> {
        let patch_dir = self.patches_dir();
        let path = patch_dir.join(&patch_file_name(hash));
        let f = File::open(path)?;
        let mut f = flate2::bufread::GzDecoder::new(BufReader::new(f));
        Ok(Patch::read_dependencies(&mut f)?)
    }

    /// The ignore file that is _not_ tracked by pijul.
    pub fn local_ignore_file(&self) -> PathBuf {
        self.repo_dir().join("local").join("ignore")
    }

    pub fn get_current_branch(&self) -> Result<String> {
        let mut path = self.repo_dir();
        path.push("current_branch");
        if let Ok(mut f) = File::open(&path) {
            let mut s = String::new();
            f.read_to_string(&mut s)?;
            Ok(s.trim().to_string())
        } else {
            Ok(DEFAULT_BRANCH.to_string())
        }
    }

    pub fn set_current_branch(&self, branch: &str) -> Result<()> {
        let mut path = self.repo_dir();
        path.push("current_branch");
        let mut f = File::create(&path)?;
        f.write_all(branch.trim().as_ref())?;
        f.write_all(b"\n")?;
        Ok(())
    }

    pub fn open_repo(&self, increase: Option<u64>) -> Result<Repository> {
        Repository::open(self.pristine_dir(), increase)
    }

    
    pub fn relativize<'a>(&self, path: &'a Path) -> Result<RepoPath<&'a Path>> {
    	match path.strip_prefix(&self.repo_root) {
            Ok(p) => Ok(RepoPath(p)),
            Err(_) => Err(Error::FileNotInRepo(path.to_path_buf()))
        }
    }

    pub fn absolutize<'a>(&self, path: &RepoPath<impl AsRef<Path>>) -> PathBuf {
        self.repo_root.as_ref().join(path.as_path())
    }
}

impl<P: AsRef<Path> + 'static> RepoRoot<P> {
    pub fn untracked_files<T: rand::Rng, Q: AsRef<Path>>(
        &self,
        txn: &MutTxn<T>,
        path: Q,
    ) -> impl Iterator<Item = RepoPath<PathBuf>> + '_ {
        let known_files = txn.list_files(ROOT_INODE).unwrap_or_else(|_| vec![]);

        let o = OverrideBuilder::new(self.repo_root.as_ref())
            .add("!.pijul")
            .unwrap()
            .build()
            .unwrap(); // we can be pretty confident these two calls will
                       // not fail as the glob is hard-coded

        let mut w = WalkBuilder::new(path.as_ref());
        w.git_ignore(false)
            .git_exclude(false)
            .git_global(false)
            .hidden(false)
            .add_custom_ignore_filename(".pijulignore");

        // add .pijul/local/ignore
        w.add_ignore(self.local_ignore_file());
        w.overrides(o);

        w.build().filter_map(move |f| {
            if let Ok(f) = f {
                let p = f.path();
                if p == self.repo_root.as_ref() {
                    return None;
                }

                let p_in_repo = self.relativize(&p).unwrap();
                // ^- cannot fail since p must be within repo_root.
                if known_files.iter().any(|t| t.as_ref() == p_in_repo) {
                    return None
                }
                Some(p_in_repo.to_owned())
            } else {
                None
            }
        })
    }
}

/// Find the repository root from one of its descendant
/// directories. Return `None` iff `dir` is not in a repository.
pub fn find_repo_root<'a>(dir: &'a Path) -> Option<RepoRoot<PathBuf>> {
    let mut p = dir.to_path_buf();
    loop {
        p.push(PIJUL_DIR_NAME);
        match metadata(&p) {
            Ok(ref attr) if attr.is_dir() => {
                p.pop();
                return Some(RepoRoot { repo_root: p });
            }
            _ => {}
        }
        p.pop();

        if !p.pop() {
            return None;
        }
    }
}

#[doc(hidden)]
pub const ID_LENGTH: usize = 100;

/// Create a repository. `dir` must be the repository root (a
/// `".pijul"` directory will be created in `dir`).
pub fn create<R: Rng>(dir: &Path, mut rng: R) -> std::io::Result<RepoRoot<PathBuf>> {
    let r = RepoRoot {
        repo_root: canonicalize(dir)?,
    };

    let mut repo_dir = r.repo_dir();
    create_dir_all(&repo_dir)?;

    repo_dir.push("pristine");
    create_dir_all(&repo_dir)?;
    repo_dir.pop();

    repo_dir.push("patches");
    create_dir_all(&repo_dir)?;
    repo_dir.pop();

    repo_dir.push("id");
    let mut f = std::fs::File::create(&repo_dir)?;
    let mut x = String::new();
    x.extend(rng.sample_iter(&Alphanumeric).take(ID_LENGTH));
    f.write_all(x.as_bytes())?;
    repo_dir.pop();

    repo_dir.push("version");
    let mut f = std::fs::File::create(&repo_dir)?;
    writeln!(f, "{}", env!("CARGO_PKG_VERSION"))?;
    repo_dir.pop();

    repo_dir.push("local");
    create_dir_all(&repo_dir)?;
    repo_dir.pop();

    repo_dir.push("hooks");
    create_dir_all(&repo_dir)?;
    repo_dir.pop();

    repo_dir.push("local");
    repo_dir.push("ignore");
    std::fs::File::create(&repo_dir)?;
    repo_dir.pop();
    repo_dir.pop();

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    Ok(r)
}
}

}

================================

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    Ok(())

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
pub fn open_repo(root: &Path, increase: Option<u64>) -> Result<Repository> {

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    Repository::open(pristine_dir(root), increase)

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
}

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
































































































































































































































































































































































use super::{ConflictLine, VertexId, DFS, Graph};
use backend::*;

#[derive(Debug)]
struct Side {
    next: usize,
    side: Vec<ConflictLine>,
}

#[derive(Debug)]
enum State {
    Init {
        resume_after_conflict: bool,
    },
    EvalConflict {
        start: usize,
        end: usize,
        cur: usize,
        last_visit: usize,
        sides: Vec<Side>,
    },
}
pub(in graph) struct ConflictTree<'a> {
    stack: Vec<(usize, State)>,
    graph: &'a Graph,
    scc: &'a [Vec<VertexId>],
    dfs: &'a mut DFS,
}

impl<'a> ConflictTree<'a> {
    fn new(graph: &'a Graph, scc: &'a [Vec<VertexId>], dfs: &'a mut DFS) -> Self {
        ConflictTree {
            stack: vec![
                (scc.len() - 1,
                 State::EvalConflict {
                     start: scc.len() - 1,
                     end: 0,
                     cur: 1,
                     last_visit: 0,
                     sides: vec![Side {
                         next: scc.len() - 1,
                         side: vec![],
                     }],
                 })
            ],
            graph,
            scc,
            dfs,
        }
    }

    fn begin_conflict(&mut self, i: usize, c: usize) {
        if let Some((
            _,
            State::EvalConflict {
                ref cur,
                ref mut sides,
                ..
            },
        )) = self.stack.last_mut()
        {
            sides[*cur].next = c;
            sides[*cur].side.push(ConflictLine::Line(i))
        }
        debug!("BEGINS CONFLICT {:?}", c);
        let mut sides = Vec::new();
        for cousin in self.scc[i].iter() {
            for &(e, n_child) in self.graph.children(*cousin) {
                debug!("cousin: {:?}", self.graph[n_child].scc);
                let is_ok = match e {
                    Some(e) if e.flag.contains(EdgeFlags::FOLDER_EDGE) => false,
                    _ => true
                };
                if is_ok {
                    let next = self.graph[n_child].scc;
                    sides.push(Side {
                        next,
                        side: Vec::new(),
                    })
                }
            }
        }
        sides.sort_by(|a, b| a.next.cmp(&b.next));
        debug!("sides: {:?}", sides);
        let cur = sides.len();
        self.stack.push((
            i,
            State::EvalConflict {
                sides,
                start: i,
                end: c,
                last_visit: 0,
                cur,
            },
        ));

    }

    fn normal_line(&mut self, i: usize) {
        if let Some((
            _,
            State::EvalConflict {
                ref cur,
                ref mut sides,
                ..
            },
        )) = self.stack.last_mut()
        {
            sides[*cur].side.push(ConflictLine::Line(i))
        } else {
            unimplemented!()
        }
        let mut max_scc = 0;
        for cousin in self.scc[i].iter() {
            for &(e, n_child) in self.graph.children(*cousin) {
                let is_ok = match e {
                    Some(e) if e.flag.contains(EdgeFlags::FOLDER_EDGE) => false,
                    _ => true
                };
                if is_ok {
                    let next = self.graph[n_child].scc;
                    debug!("max_scc {:?} -> {:?}", cousin, n_child);
                    debug!("{:?} {:?}", self.dfs.first_visit(next), self.dfs.first_visit(i));
                    // we want the highest SCC that has been
                    // discovered after i in the DFS.
                    if max_scc == 0 {
                        max_scc = next
                    } else if next > max_scc && self.dfs.first_visit(next) > self.dfs.first_visit(i) {
                        max_scc = next
                    }
                }
            }
        }
        debug!("max_scc = {:?}", max_scc);
        if max_scc > 0 {
            self.stack.push((
                max_scc,
                State::Init {
                    resume_after_conflict: false,
                },
            ))
        }
    }

    fn visit_next_side(&mut self, i: usize, start: usize, end: usize, cur: usize, last_visit: usize, sides: Vec<Side>) {
        let next = sides[cur - 1].next;
        let visit_next = self.dfs.visits[next].first > last_visit;
        self.stack.push((
            i,
            State::EvalConflict {
                start,
                end,
                cur: cur - 1,
                last_visit: if visit_next {
                    self.dfs.visits[next].last
                } else {
                    last_visit
                },
                sides,
            },
        ));
        debug!("visit_next ({:?}): {:?}", next, visit_next);
        if visit_next {
            self.stack.push((
                next,
                State::Init {
                    resume_after_conflict: self.dfs.visits[next].ends_conflict,
                },
            ));
        }
    }

    fn finish_conflict(&mut self, sides: Vec<Side>, next: usize) {
        let mut current: Vec<_> = sides
            .into_iter()
            .filter_map(|x| {
                if x.side.is_empty() {
                    None
                } else {
                    Some(x.side)
                }
            }).collect();
        if let Some((
            _,
            State::EvalConflict {
                ref cur,
                ref mut sides,
                ..
            },
        )) = self.stack.last_mut()
        {
            if current.len() >= 2 {
                // If there are at least two sides, this is a conflict.
                sides[*cur].side.push(ConflictLine::Conflict(current));
                sides[*cur].next = next;
            } else if let Some(current) = current.pop() {
                // Else, it is not a conflict, just extend.
                sides[*cur].side.extend(current.into_iter());
                sides[*cur].next = next;
            }
        }
    }

    fn continue_conflict(&mut self, sides: Vec<Side>) -> Vec<Side> {
        let mut sides_ = Vec::new();
        let mut next = sides[0].next;
        let mut current = Vec::new();
        debug!("sides {:?}", sides);
        for side in sides.into_iter().filter(|x| !x.side.is_empty()) {
            debug!("side {:?}", side);
            if side.next != next {
                let mut cur = std::mem::replace(&mut current, Vec::new());
                if cur.len() >= 2 {
                    sides_.push(Side {
                        next,
                        side: vec![ConflictLine::Conflict(cur)],
                    });
                } else if let Some(side) = cur.pop() {
                    sides_.push(Side {
                        next,
                        side,
                    })
                }
                next = side.next;
            }
            current.push(side.side);
        }
        if current.len() >= 2 {
            sides_.push(Side {
                next,
                side: vec![ConflictLine::Conflict(current)],
            });
        } else if let Some(side) = current.pop() {
            sides_.push(Side {
                next,
                side,
            })
        }
        debug!("conflict reduction {:?}", sides_);
        assert!(sides_.len() > 1);
        sides_
    }
}

pub(in graph) fn conflict_tree(graph: &Graph, scc: &[Vec<VertexId>], dfs: &mut DFS) -> Vec<ConflictLine> {
    debug!("scc = {:?}", scc);
    let mut conflict = ConflictTree::new(graph, scc, dfs);
    debug!("conflict tree starting");

    while let Some((i, state)) = conflict.stack.pop() {
        debug!(">>>>>>>>>>>>> {:?} ({:?}): {:?}, {:?}", i, scc[i], graph[scc[i][0]].key, conflict.dfs.visits[i]);
        debug!("state: {:?}", state);
        debug!("stack: {:?}", conflict.stack);
        match state {
            State::Init { resume_after_conflict } => {
                conflict.dfs.visits[i].output = true;
                if conflict.dfs.visits[i].ends_conflict {
                    debug!("ends conflict, resume = {:?}", resume_after_conflict);
                }
                if conflict.dfs.visits[i].ends_conflict && !resume_after_conflict {
                    // We're not resuming after this conflict, so we
                    // just register where this side of the current
                    // conflict ends (and we already popped the stack).
                    if let Some((
                        _,
                        State::EvalConflict {
                            ref mut sides,
                            ref mut cur,
                            end,
                            ..
                        },
                    )) = conflict.stack.last_mut()
                    {
                        if *end == i {
                            // If we are at the end of the current
                            // conflict, this is really the end of a
                            // conflict, else, it's a normal line (and
                            // might begin a conflict).
                            sides[*cur].next = i;
                            continue
                        }
                    }
                }
                // Else, we are exploring a line normally. If this
                // line starts a conflict, then push the new
                // conflict, else explore the line normally.
                debug!("begins = {:?}", conflict.dfs.visits[i].begins_conflict);
                if let Some(c) = conflict.dfs.visits[i].begins_conflict {
                    conflict.begin_conflict(i, c)
                } else {
                    conflict.normal_line(i)
                }
            }
            State::EvalConflict {
                start,
                end,
                mut cur,
                last_visit,
                mut sides,
            } => {
                debug!("EvalConflict {:?} ({:?})", start, conflict.scc[start]);
                if cur > 0 {
                    // Recurse, i.e. visit the next unvisited
                    // component of this conflict.
                    debug!("Visiting the next unvisited component");
                    conflict.visit_next_side(i, start, end, cur, last_visit, sides)
                } else if conflict.stack.is_empty() {
                    // We're done, return.
                    debug!("Conflict stack empty");
                    assert_eq!(sides.len(), 1);
                    let side = sides.pop().unwrap();
                    assert!(sides.is_empty());
                    return side.side;
                } else {
                    sides.sort_by(|a, b| a.next.cmp(&b.next));
                    // This conflict is over if all its sides have the same `next`.
                    let next = sides.iter().filter(|x| !x.side.is_empty()).next().unwrap().next;
                    let conflict_is_over = {
                        sides.iter().all(|x| x.side.is_empty() || x.next == next)
                    };
                    debug!("Conflict_is_over: {:?}, next = {:?} ({:?}), end = {:?} ({:?})", conflict_is_over, next, conflict.scc[next], end, conflict.scc[end]);
                    if conflict_is_over {
                        // The conflict is over.
                        assert_eq!(end, next);
                        conflict.finish_conflict(sides, next);
                        conflict.stack.push((
                            next,
                            State::Init {
                                resume_after_conflict: true,
                            },
                        ));
                    } else {
                        // The conflict is not over.
                        let sides_ = conflict.continue_conflict(sides);
                        conflict.stack.push((
                            i,
                            State::EvalConflict {
                                start,
                                end,
                                cur: sides_.len(),
                                last_visit: 0,
                                sides: sides_,
                            },
                        ));

                    }
                }
            }
        }
    }
    unreachable!()
}

























































































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
    all_descendants_visited: bool,
    ) {
            all_descendants_visited: false,
        let mut conflict_stack: Vec<(usize, usize)> = Vec::new();
        debug!("dfs starting");

        // The idea of this algorithm is: when all the outgoing edges
        // of a vertex are cross-edges, we believe we've detected the
        // end of a conflict.

                target: "libpijul::graph::dfs",
            let is_first_visit = state.descendants.is_none();
            debug!(
                target: "libpijul::graph::dfs",
                "descendants = {:?}",
                state.descendants
            );

                // After Tarjan's algorithm, the SCC numbers are in reverse
                // topological order.
                //
                // Here, we want to visit the first child in topological
                // order, hence the one with the largest SCC number first.
                //

                            if child_component < state.n_scc {
                                // If this is a child and not a sibling.
                // We want to get the highest components first.
                /*
                // We want to get the unvisited components first.
                descendants.sort_by(|a, b| {
                    let ord = dfs.first_visit(*b).cmp(&dfs.first_visit(*a));
                    if let std::cmp::Ordering::Equal = ord {
                        (*a).cmp(b)
                    } else {
                        ord
                    }
                });
                 */
                debug!("sorted descendants: {:?}", descendants);
                // If all descendants have been visited, then all
                // edges are cross edges (because forward edges have
                // not been discovered yet, since we haven't explored
                // the children, and there are no back edges in a
                // DAG).
                //
                // This is a way to tell whether we have at the end of
                // a conflict or not.
                state.all_descendants_visited =
                    descendants.iter().all(|desc| dfs.first_visit(*desc) > 0);

            // SCCs to which we have forward edges.
                    if !is_first_visit {
                        // If this is not our first visit to SCC `n_scc`,
                        // mark it as the beginning of a conflict.
                        debug!("{:?}: begins conflict", state.n_scc);
                        dfs.has_conflicts = true;
                        dfs.visits[state.n_scc].begins_conflict = Some(state.n_scc);
                        if let Some((scc, end)) = conflict_stack.pop() {
                            conflict_stack.push((scc, end));
                            if scc != state.n_scc {
                                conflict_stack.push((state.n_scc, state.n_scc));
                            }
                        } else {
                            conflict_stack.push((state.n_scc, state.n_scc));
                        }
                    }

                    debug!(
                        "cross edge, stack: {:?}, updating with {:?}",
                        conflict_stack, child
                    );
                    if state.all_descendants_visited {
                        for c in conflict_stack.iter_mut() {
                            // If `child` was discovered after the
                            // beginning of this conflict, then we
                            // might be solving this conflict.
                            if dfs.first_visit(child) > dfs.first_visit(c.0) {
                                c.1 = std::cmp::min(c.1, child);
                            }
                        }
                        dfs.visits[child].ends_conflict = true
                    }
                    all_descendants_visited: false,
                if dfs.visits[state.n_scc].begins_conflict.is_some() {
                    let (begin, end) = conflict_stack.pop().unwrap();
                    assert_eq!(begin, state.n_scc);
                    debug!("begins_conflict {:?}: {:?}", state.n_scc, end);
                    dfs.visits[state.n_scc].begins_conflict = Some(end);
use super::{Graph, VertexId};
use backend::*;
use std::collections::HashSet;

pub(in graph) struct DFS {
    pub visits: Vec<Visits>,
    pub counter: usize,
    pub has_conflicts: bool,
}

#[derive(Clone, Debug)]
pub(in graph) struct Visits {
    pub first: usize,
    pub last: usize,
    /// Does this vertex have incomparable children?
    pub begins_conflict: Option<usize>,
    /// Does this vertex have incoming cross-edges?
    pub ends_conflict: bool,
    /// Has the line been output? (for the second DFS, in
    /// conflict_tree)
    pub output: bool,
}

impl Default for Visits {
    fn default() -> Self {
        Visits {
            first: 0,
            last: 0,
            begins_conflict: None,
            ends_conflict: false,
            output: false,
        }
    }
}

impl DFS {
    pub fn new(n: usize) -> Self {
        DFS {
            visits: vec![Visits::default(); n],
            counter: 1,
            has_conflicts: false,
        }
    }
}

impl DFS {
    fn mark_discovered(&mut self, scc: usize) {
        if self.visits[scc].first == 0 {
            self.visits[scc].first = self.counter;
            self.counter += 1;
        }
    }

    fn mark_last_visit(&mut self, scc: usize) {
        self.mark_discovered(scc);
        self.visits[scc].last = self.counter;
        self.counter += 1;
    }

    pub fn first_visit(&self, scc: usize) -> usize {
        self.visits[scc].first
    }

    pub fn last_visit(&self, scc: usize) -> usize {
        self.visits[scc].last
    }
}

struct State {
    n_scc: usize,
    forward_scc: HashSet<usize>,
    descendants: Option<Vec<usize>>,
    current_path: Path,
    // Length of the current path just when we first visited `n_scc`
    // (including n_scc).
    current_path_len: usize,
    return_values: Vec<Path>,
}

#[derive(Debug)]
pub(in graph) struct Path {
    pub path: Vec<PathElement>,
    pub sccs: HashSet<usize>,
    pub end: usize,
}

#[derive(Debug)]
pub(in graph) enum PathElement {
    Scc { scc: usize },
    Conflict { sides: Vec<Path> },
}

impl Graph {
    /// Run a depth-first search on this graph, assigning the
    /// `first_visit` and `last_visit` numbers to each node.
    pub(in graph) fn dfs<A: Transaction, R>(
        &mut self,
        txn: &GenericTxn<A, R>,
        branch: &Branch,
        scc: &[Vec<VertexId>],
        dfs: &mut DFS,
        forward: &mut Vec<(Key<PatchId>, Edge)>,
    ) -> Path {
        let mut call_stack: Vec<State> = Vec::with_capacity(scc.len());
        call_stack.push(State {
            n_scc: scc.len() - 1,
            forward_scc: HashSet::new(),
            descendants: None,
            current_path: Path {
                path: Vec::new(),
                sccs: HashSet::new(),
                end: 0,
            },
            current_path_len: 0,
            return_values: Vec::new(),
        });
        let mut return_value = None;

        while let Some(mut state) = call_stack.pop() {
            debug!("dfs, n_scc = {:?}", state.n_scc);
            for &VertexId(id) in scc[state.n_scc].iter() {
                debug!("dfs, n_scc: {:?}", self.lines[id].key);
            }
            dfs.mark_discovered(state.n_scc);
            debug!(
                "scc: {:?}, first {} last {}",
                state.n_scc,
                dfs.first_visit(state.n_scc),
                dfs.last_visit(state.n_scc)
            );
            debug!("descendants = {:?}", state.descendants);
            let mut descendants = if let Some(descendants) = state.descendants {
                descendants
            } else {
                // First visit / discovery of SCC n_scc.
                state
                    .current_path
                    .path
                    .push(PathElement::Scc { scc: state.n_scc });
                state.current_path.sccs.insert(state.n_scc);
                state.current_path.end = std::cmp::min(state.current_path.end, state.n_scc);
                // Collect all descendants of this SCC, in order of increasing
                // SCC.
                let mut descendants = Vec::new();
                for cousin in scc[state.n_scc].iter() {
                    for &(e, n_child) in self.children(*cousin) {
                        let is_ok = match e {
                            Some(e) if e.flag.contains(EdgeFlags::FOLDER_EDGE) => false,
                            _ => true,
                        };
                        if is_ok {
                            let child_component = self[n_child].scc;
                            debug!("child_component {:?}", child_component);
                            if child_component < state.n_scc
                                && dfs.first_visit(child_component) == 0
                            {
                                // If this is a child, and we haven't visited it yet.
                                debug!("not yet visited");
                                descendants.push(child_component)
                            } else {
                                // Set the end to the highest descendant.
                                state.current_path.end =
                                    std::cmp::max(state.current_path.end, child_component);
                            }
                        }
                    }
                }
                // After Tarjan's algorithm, the SCC numbers are in
                // reverse topological order. Here, we want to visit
                // the first child in topological order, hence the one
                // with the largest SCC number first.
                descendants.sort();
                descendants
            };

            // Pop descendants until we find one into which we can
            // recurse.
            let mut recursive_call = None;
            while let Some(child) = descendants.pop() {
                debug!(
                    "child {:?}, first {} last {}",
                    child,
                    dfs.first_visit(child),
                    dfs.last_visit(child)
                );
                if dfs.first_visit(state.n_scc) < dfs.first_visit(child) {
                    // This is a forward edge.
                    debug!("last_visit to {:?}: {:?}", child, dfs.last_visit(child));
                    state.forward_scc.insert(child);
                } else if dfs.first_visit(child) == 0 {
                    // SCC `child` has not yet been visited, visit it.
                    recursive_call = Some(child);
                    break;
                } else {
                    // cross edge
                }
            }
            if let Some(child) = recursive_call {
                if let Some(return_value) = return_value.take() {
                    state.return_values.push(return_value)
                }
                // The current path is passed on to the first
                // child. Subsequent children will start with an empty
                // Vec as their current path.
                let current_path = std::mem::replace(
                    &mut state.current_path,
                    Path {
                        path: Vec::new(),
                        sccs: HashSet::new(),
                        end: 0,
                    },
                );
                call_stack.push(State {
                    descendants: Some(descendants),
                    ..state
                });
                call_stack.push(State {
                    n_scc: child,
                    forward_scc: HashSet::new(),
                    descendants: None,
                    current_path_len: current_path.path.len(),
                    current_path,
                    return_values: Vec::new(),
                });
            } else {
                dfs.mark_last_visit(state.n_scc);
                debug!("return value: {:?}", return_value);
                if let Some(return_value_) = return_value.take() {
                    if state.return_values.is_empty() {
                        debug!("passing the return value on");
                        return_value = Some(return_value_)
                    } else {
                        // Conflict, build the conflict
                        debug!(
                            "reducing conflict, current_path_len = {:?}",
                            state.current_path_len
                        );
                        state.return_values.push(return_value_);
                        let mut main_path = state.return_values[0]
                            .path
                            .split_off(state.current_path_len + 1);
                        std::mem::swap(&mut state.return_values[0].path, &mut main_path);

                        // We sort the sides, putting the `end` vertex
                        // that is highest in the graph last.
                        state.return_values.sort_by(|a, b| a.end.cmp(&b.end));
                        debug!("return_values = {:?}", state.return_values);
                        let sccs = state
                            .return_values
                            .iter()
                            .flat_map(|side| side.sccs.iter())
                            .map(|&x| x)
                            .collect();
                        let mut sides = Vec::new();
                        while let Some(side) = state.return_values.pop() {
                            debug!("handling conflict side {:?}", side);
                            // In which of the other sides does this side end?
                            let main_side = if let Some(n) = state
                                .return_values
                                .iter()
                                .position(|side_| {
                                    side_.sccs.contains(&side.end)
                                })
                            {
                                n
                            } else {
                                debug!("no main side found");
                                sides.push(side);
                                continue;
                            };
                            debug!("main_side = {:?}", main_side);

                            // If there is already a conflict started,
                            // just add a side, and continue.
                            if let PathElement::Conflict { ref mut sides, .. } =
                                state.return_values[main_side].path[0]
                            {
                                debug!("there is already a conflict, sides = {:?}", sides);
                                // This conflict already existed.
                                if sides[0].end == side.end {
                                    sides.push(side);
                                    continue;
                                }
                            }

                            // Else, find the last vertex of the conflict.
                            let end = state.return_values[main_side]
                                .path
                                .iter()
                                .position(|v| match v {
                                    PathElement::Scc { scc } => *scc == side.end,
                                    PathElement::Conflict { ref sides } => {
                                        sides.iter().any(|side_| side_.sccs.contains(&side.end))
                                    }
                                })
                                .unwrap();
                            debug!("end = {:?} {:?}", end, state.return_values[main_side].path);
                            let mut v = Vec::new();
                            // Insert empty conflict at the beginning,
                            // we will populate it just after a little
                            // memory trick.
                            v.push(PathElement::Conflict { sides: Vec::new() });
                            v.extend(state.return_values[main_side].path.drain(end..));
                            let side0 =
                                std::mem::replace(&mut state.return_values[main_side].path, v);
                            // Here, side0 contains just a conflicting
                            // side, and
                            // `state.return_values[main_side]` starts
                            // with a PathElement::Conflict, and ends
                            // with the end of the main path.

                            // Clean the SCCS in the return values, populate the SCCS of side0.
                            let mut sccs0 = HashSet::new();
                            for elt in side0.iter() {
                                match *elt {
                                    PathElement::Scc { scc } => {
                                        sccs0.insert(scc);
                                    }
                                    PathElement::Conflict { ref sides } => {
                                        for side in sides {
                                            for &scc in side.sccs.iter() {
                                                sccs0.insert(scc);
                                            }
                                        }
                                    }
                                }
                            }
                            state.return_values[main_side].sccs.extend(
                                side.sccs.iter().map(|&x| x)
                            );
                            state.return_values[main_side].path[0] = PathElement::Conflict {
                                sides: vec![
                                    Path {
                                        path: side0,
                                        sccs: sccs0,
                                        end: side.end,
                                    },
                                    side,
                                ],
                            };
                        }
                        if sides.len() > 1 {
                            main_path.push(PathElement::Conflict { sides })
                        } else {
                            main_path.extend(sides.pop().unwrap().path.into_iter())
                        }
                        return_value = Some(Path {
                            path: main_path,
                            sccs,
                            end: 0,
                        })
                    }
                } else {
                    debug!(
                        "no previous return value, returning current path {:?}",
                        state.current_path
                    );
                    return_value = Some(state.current_path)
                }

                // After this, collect forward edges. Look at all
                // children of this SCC.
                for cousin in scc[state.n_scc].iter() {
                    for &(edge, n_child) in self.children(*cousin) {
                        if let Some(mut edge) = edge {
                            // Is this edge a forward edge of the DAG?
                            if state.forward_scc.contains(&self[n_child].scc)
                                && edge.flag.contains(EdgeFlags::PSEUDO_EDGE)
                                && !txn.test_edge(
                                    branch,
                                    self[*cousin].key,
                                    edge.dest,
                                    EdgeFlags::DELETED_EDGE,
                                    EdgeFlags::DELETED_EDGE,
                                )
                            {
                                debug!("forward: {:?} {:?}", self[*cousin].key, edge);
                                forward.push((self[*cousin].key, edge))
                            } else {
                                // Does this edge have parallel PSEUDO edges? If so, they may not be "forward", but they are redundant.
                                edge.flag = EdgeFlags::PSEUDO_EDGE;
                                edge.introduced_by = ROOT_PATCH_ID;
                                let mut edges = txn
                                    .iter_nodes(branch, Some((self[*cousin].key, Some(edge))))
                                    .take_while(|&(k, v)| {
                                        k == self[*cousin].key
                                            && v.dest == edge.dest
                                            && v.flag
                                                <= EdgeFlags::FOLDER_EDGE | EdgeFlags::PSEUDO_EDGE
                                    });
                                edges.next(); // ignore the first pseudo-edge.
                                forward.extend(edges.map(|(k, v)| (k, v))); // add all parallel edges.
                            }
                        }
                    }
                }
            }
        }
        debug!("DFS done, returning");
        return_value.unwrap_or(Path {
            path: Vec::new(),
            sccs: HashSet::new(),
            end: 0,
        })
    }
}




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
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673



















































































































































































































































































































































674

use self::dfs::DFS;
mod conflict_tree;
use self::conflict_tree::*;
                /*} else if v.flag.contains(EdgeFlags::EPSILON_EDGE) {
//! The data structure of the in-memory version of Pijul's main
//! datastructure, used to edit and organise it (for instance before a
//! record or before outputting a file).
use backend::*;
use conflict;
use std::cmp::min;
use std::collections::{HashMap, HashSet};
use Result;

use rand;
use std;

mod dfs;
use self::dfs::{DFS, Path, PathElement};

bitflags! {
    struct Flags: u8 {
        const LINE_HALF_DELETED = 4;
        const LINE_VISITED = 2;
        const LINE_ONSTACK = 1;
    }
}

/// The elementary datum in the representation of the repository state
/// at any given point in time. We need this structure (as opposed to
/// working directly on a branch) in order to add more data, such as
/// strongly connected component identifier, to each node.
#[derive(Debug)]
pub struct Line {
    /// The internal identifier of the line.
    pub key: Key<PatchId>,

    // The status of the line with respect to a dfs of
    // a graph it appears in. This is 0 or
    // `LINE_HALF_DELETED`.
    flags: Flags,
    children: usize,
    n_children: usize,
    index: usize,
    lowlink: usize,
    scc: usize,
}

impl Line {
    pub fn is_zombie(&self) -> bool {
        self.flags.contains(Flags::LINE_HALF_DELETED)
    }
}

/// A graph, representing the whole content of the repository state at
/// a point in time. The encoding is a "flat adjacency list", where
/// each vertex contains a index `children` and a number of children
/// `n_children`. The children of that vertex are then
/// `&g.children[children .. children + n_children]`.
#[derive(Debug)]
pub struct Graph {
    /// Array of all alive lines in the graph. Line 0 is a dummy line
    /// at the end, so that all nodes have a common successor
    pub lines: Vec<Line>,
    /// Edge + index of the line in the "lines" array above. "None"
    /// means "dummy line at the end", and corresponds to line number
    /// 0.
    children: Vec<(Option<Edge>, VertexId)>,
}

#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
struct VertexId(usize);

const DUMMY_VERTEX: VertexId = VertexId(0);

impl std::ops::Index<VertexId> for Graph {
    type Output = Line;
    fn index(&self, idx: VertexId) -> &Self::Output {
        self.lines.index(idx.0)
    }
}
impl std::ops::IndexMut<VertexId> for Graph {
    fn index_mut(&mut self, idx: VertexId) -> &mut Self::Output {
        self.lines.index_mut(idx.0)
    }
}

use std::io::Write;

impl Graph {
    fn children(&self, i: VertexId) -> &[(Option<Edge>, VertexId)] {
        let ref line = self[i];
        &self.children[line.children..line.children + line.n_children]
    }

    fn child(&self, i: VertexId, j: usize) -> &(Option<Edge>, VertexId) {
        &self.children[self[i].children + j]
    }

    pub fn debug<W: Write, R, A: Transaction>(
        &self,
        txn: &GenericTxn<A, R>,
        branch: &Branch,
        add_others: bool,
        introduced_by: bool,
        mut w: W,
    ) -> std::io::Result<()> {
        writeln!(w, "digraph {{")?;
        let mut cache = HashMap::new();
        if add_others {
            for (line, i) in self.lines.iter().zip(0..) {
                cache.insert(line.key, i);
            }
        }
        let mut others = HashSet::new();
        for (line, i) in self.lines.iter().zip(0..) {
            let contents = {
                if let Some(c) = txn.get_contents(line.key) {
                    let c = c.into_cow();
                    if let Ok(c) = std::str::from_utf8(&c) {
                        c.split_at(std::cmp::min(50, c.len())).0.to_string()
                    } else {
                        "<INVALID>".to_string()
                    }
                } else {
                    "".to_string()
                }
            };
            let contents = format!("{:?}", contents);
            let contents = contents.split_at(contents.len() - 1).0.split_at(1).1;
            writeln!(
                w,
                "n_{}[label=\"{}: {}.{}: {}\"];",
                i,
                i,
                line.key.patch.to_base58(),
                line.key.line.to_hex(),
                contents
            )?;

            if add_others && !line.key.is_root() {
                for v in txn.iter_adjacent(branch, line.key, EdgeFlags::empty(), EdgeFlags::all()) {
                    if let Some(dest) = cache.get(&v.dest) {
                        writeln!(
                            w,
                            "n_{} -> n_{}[color=red,label=\"{:?}{}{}\"];",
                            i,
                            dest,
                            v.flag.bits(),
                            if introduced_by { " " } else { "" },
                            if introduced_by {
                                v.introduced_by.to_base58()
                            } else {
                                String::new()
                            }
                        )?;
                    } else {
                        if !others.contains(&v.dest) {
                            others.insert(v.dest);
                            writeln!(
                                w,
                                "n_{}[label=\"{}.{}\",color=red];",
                                v.dest.to_base58(),
                                v.dest.patch.to_base58(),
                                v.dest.line.to_hex()
                            )?;
                        }
                        writeln!(
                            w,
                            "n_{} -> n_{}[color=red,label=\"{:?}{}{}\"];",
                            i,
                            v.dest.to_base58(),
                            v.flag.bits(),
                            if introduced_by { " " } else { "" },
                            if introduced_by {
                                v.introduced_by.to_base58()
                            } else {
                                String::new()
                            }
                        )?;
                    }
                }
            }
            for &(ref edge, VertexId(j)) in
                &self.children[line.children..line.children + line.n_children]
            {
                if let Some(ref edge) = *edge {
                    writeln!(
                        w,
                        "n_{}->n_{}[label=\"{:?}{}{}\"];",
                        i,
                        j,
                        edge.flag.bits(),
                        if introduced_by { " " } else { "" },
                        if introduced_by {
                            edge.introduced_by.to_base58()
                        } else {
                            String::new()
                        }
                    )?
                } else {
                    writeln!(w, "n_{}->n_{}[label=\"none\"];", i, j)?
                }
            }
        }
        writeln!(w, "}}")?;
        Ok(())
    }
}

use sanakirja::value::Value;
/// A "line outputter" trait.
pub trait LineBuffer<'a, T: 'a + Transaction> {
    fn output_line(&mut self, key: &Key<PatchId>, contents: Value<'a, T>) -> Result<()>;

    fn output_conflict_marker(&mut self, s: &'a str) -> Result<()>;
    fn begin_conflict(&mut self) -> Result<()> {
        self.output_conflict_marker(conflict::START_MARKER)
    }
    fn begin_zombie_conflict(&mut self) -> Result<()> {
        self.begin_conflict()
    }
    fn conflict_next(&mut self) -> Result<()> {
        self.output_conflict_marker(conflict::SEPARATOR)
    }
    fn end_conflict(&mut self) -> Result<()> {
        self.output_conflict_marker(conflict::END_MARKER)
    }
}

pub struct Writer<W: std::io::Write> {
    pub w: W,
    new_line: bool,
}

impl<W: std::io::Write> Writer<W> {
    pub fn new(w: W) -> Self {
        Writer { w, new_line: true }
    }
}

impl<W: std::io::Write> std::ops::Deref for Writer<W> {
    type Target = W;
    fn deref(&self) -> &Self::Target {
        &self.w
    }
}

impl<W: std::io::Write> std::ops::DerefMut for Writer<W> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.w
    }
}

impl<'a, T: 'a + Transaction, W: std::io::Write> LineBuffer<'a, T> for Writer<W> {
    fn output_line(&mut self, k: &Key<PatchId>, c: Value<T>) -> Result<()> {
        let mut ends_with_newline = false;
        let mut is_empty = true;
        for chunk in c {
            debug!("output line {:?} {:?}", k, std::str::from_utf8(chunk));
            is_empty = is_empty && chunk.is_empty();
            ends_with_newline = chunk.ends_with(b"\n");
            self.w.write_all(chunk)?
        }
        if !is_empty {
            // empty "lines" (such as in the beginning of a file)
            // don't change the status of self.new_line.
            self.new_line = ends_with_newline;
        }
        Ok(())
    }

    fn output_conflict_marker(&mut self, s: &'a str) -> Result<()> {
        debug!("output_conflict_marker {:?}", self.new_line);
        if !self.new_line {
            self.w.write(s.as_bytes())?;
        } else {
            debug!("{:?}", &s.as_bytes()[1..]);
            self.w.write(&s.as_bytes()[1..])?;
        }
        Ok(())
    }
}

#[derive(Clone, Debug)]
pub struct Visits {
    pub first: usize,
    pub last: usize,
    /// Does this vertex have incomparable children?
    pub begins_conflict: Option<usize>,
    /// Does this vertex have incoming cross-edges?
    pub ends_conflict: bool,
    pub ends_conflict: bool,
    /// Has the line been output? (for the second DFS, in
    /// conflict_tree)
    pub output: bool,
}
}

impl Default for Visits {
    fn default() -> Self {
        Visits {
            first: 0,
            last: 0,
            begins_conflict: None,
            ends_conflict: false,
            ends_conflict: false,
            output: false,
        }
        }
    }
}

pub struct DFS {
    visits: Vec<Visits>,
    counter: usize,
    has_conflicts: bool,
}

impl DFS {
    pub fn new(n: usize) -> Self {
        DFS {
            visits: vec![Visits::default(); n],
            counter: 1,
            has_conflicts: false,
        }
    }
}

impl DFS {
    fn mark_discovered(&mut self, scc: usize) {
        if self.visits[scc].first == 0 {
            self.visits[scc].first = self.counter;
            self.counter += 1;
        }
    }

    fn mark_last_visit(&mut self, scc: usize) {
        self.mark_discovered(scc);
        self.visits[scc].last = self.counter;
        self.counter += 1;
    }

    fn first_visit(&self, scc: usize) -> usize {
        self.visits[scc].first
    }

    fn last_visit(&self, scc: usize) -> usize {
        self.visits[scc].last
    }
}

impl Graph {
    /// Tarjan's strongly connected component algorithm, returning a
    /// vector of strongly connected components, where each SCC is a
    /// vector of vertex indices.
    fn tarjan(&mut self) -> Vec<Vec<VertexId>> {
        if self.lines.len() <= 1 {
            return vec![vec![VertexId(0)]];
        }

        let mut call_stack = vec![(VertexId(1), 0, true)];

        let mut index = 0;
        let mut stack = Vec::new();
        let mut scc = Vec::new();
        while let Some((n_l, i, first_visit)) = call_stack.pop() {
            if first_visit {
                // First time we visit this node.
                let ref mut l = self[n_l];
                l.index = index;
                l.lowlink = index;
                l.flags = l.flags | Flags::LINE_ONSTACK | Flags::LINE_VISITED;
                debug!("tarjan {:?} {:?} chi", l.key, l.n_children);
                stack.push(n_l);
                index = index + 1;
            } else {
                let &(_, n_child) = self.child(n_l, i);
                self[n_l].lowlink = std::cmp::min(self[n_l].lowlink, self[n_child].lowlink);
            }

            let call_stack_length = call_stack.len();
            for j in i..self[n_l].n_children {
                let &(_, n_child) = self.child(n_l, j);
                if !self[n_child].flags.contains(Flags::LINE_VISITED) {
                    call_stack.push((n_l, j, false));
                    call_stack.push((n_child, 0, true));
                    break;
                // self.tarjan_dfs(scc, stack, index, n_child);
                } else {
                    if self[n_child].flags.contains(Flags::LINE_ONSTACK) {
                        self[n_l].lowlink = min(self[n_l].lowlink, self[n_child].index)
                    }
                }
            }
            if call_stack_length < call_stack.len() {
                // recursive call
                continue;
            }
            // Here, all children of n_l have been visited.

            if self[n_l].index == self[n_l].lowlink {
                let mut v = Vec::new();
                loop {
                    match stack.pop() {
                        None => break,
                        Some(n_p) => {
                            self[n_p].scc = scc.len();
                            self[n_p].flags = self[n_p].flags ^ Flags::LINE_ONSTACK;
                            v.push(n_p);
                            if n_p == n_l {
                                break;
                            }
                        }
                    }
                }
                scc.push(v);
            }
        }
        scc
    }

    /// Run a depth-first search on this graph, assigning the
    /// `first_visit` and `last_visit` numbers to each node.
    fn dfs<A: Transaction, R>(
        &mut self,
        txn: &GenericTxn<A, R>,
        branch: &Branch,
        scc: &[Vec<VertexId>],
        dfs: &mut DFS,
        forward: &mut Vec<(Key<PatchId>, Edge)>,
    ) {
        let mut call_stack: Vec<(_, HashSet<usize>, _)> = Vec::with_capacity(scc.len());
        call_stack.push((scc.len() - 1, HashSet::new(), None));

        let mut conflict_stack: Vec<(usize, usize)> = Vec::new();
        debug!(target: "libpijul::graph::dfs", "dfs starting");
        while let Some((n_scc, mut forward_scc, descendants)) = call_stack.pop() {
        while let Some((n_scc, mut forward_scc, descendants)) = call_stack.pop() {
            debug!(target: "libpijul::graph::dfs", "dfs, n_scc = {:?}", n_scc);
            for &VertexId(id) in scc[n_scc].iter() {
            for &VertexId(id) in scc[n_scc].iter() {
                debug!(target: "libpijul::graph::dfs", "dfs, n_scc: {:?}", self.lines[id].key);
            }
            }
            dfs.mark_discovered(n_scc);
            debug!(
                target: "libpijul::graph::dfs",
                "scc: {:?}, first {} last {}",
                "scc: {:?}, first {} last {}",
                n_scc,
                dfs.first_visit(n_scc),
                dfs.last_visit(n_scc)
            );
            let is_first_visit = descendants.is_none();
            debug!(
                target: "libpijul::graph::dfs",
                "descendants = {:?}",
                descendants
            );
            let mut descendants = if let Some(descendants) = descendants {
            let mut descendants = if let Some(descendants) = descendants {
            let mut descendants = if let Some(descendants) = descendants {
                descendants
            } else {
                // First visit / discovery of SCC n_scc.

                // After Tarjan's algorithm, the SCC numbers are in reverse
                // topological order.
                //
                // Here, we want to visit the first child in topological
                // order, hence the one with the largest SCC number first.
                //

                // Collect all descendants of this SCC, in order of increasing
                // SCC.
                let mut descendants = Vec::new();
                for cousin in scc[n_scc].iter() {
                    for &(e, n_child) in self.children(*cousin) {
                        let is_ok = match e {
                            Some(e) if e.flag.contains(EdgeFlags::FOLDER_EDGE) => false,
                            _ => true
                        };
                        if is_ok {
                            let child_component = self[n_child].scc;
                            if child_component < n_scc {
                                // If this is a child and not a sibling.
                                descendants.push(child_component)
                            }
                        }
                        }
                    }
                }
                descendants.sort_by(|a, b| {
                    let ord = dfs.first_visit(*b).cmp(&dfs.first_visit(*a));
                    if let std::cmp::Ordering::Equal = ord {
                        (*a).cmp(b)
                    } else {
                        ord
                    }
                });
                debug!(target: "libpijul::graph::dfs", "sorted descendants: {:?}", descendants);
                descendants
                descendants
            };

            // SCCs to which we have forward edges.
            let mut recursive_call = None;
            while let Some(child) = descendants.pop() {
                debug!(
                    target: "libpijul::graph::dfs",
                    "child {:?}, first {} last {}",
                    "child {:?}, first {} last {}",
                    child,
                    dfs.first_visit(child),
                    dfs.last_visit(child)
                );
                if dfs.first_visit(n_scc) < dfs.first_visit(child) {


                    // This is a forward edge.
                    debug!(target: "libpijul::graph::dfs", "last_visit to {:?}: {:?}", child, dfs.last_visit(child));
                    forward_scc.insert(child);

                } else {
                    // SCC `child` has not yet been visited, visit it.
                    // SCC `child` has not yet been visited, visit it.

                    // If this is not our first visit to SCC `n_scc`,
                    // mark it as the beginning of a conflict.
                    if !is_first_visit {
                        debug!(target: "libpijul::graph::dfs", "{:?}: begins conflict", n_scc);
                        dfs.has_conflicts = true;
                        dfs.has_conflicts = true;
                        dfs.visits[n_scc].begins_conflict = Some(n_scc);
                        if let Some((scc, end)) = conflict_stack.pop() {
                            conflict_stack.push((scc, end));
                            if scc != n_scc {
                                conflict_stack.push((n_scc, n_scc));
                            }
                        } else {
                            conflict_stack.push((n_scc, n_scc));
                        }
                    }
                    }
                    if dfs.first_visit(child) == 0 {
                        recursive_call = Some(child);
                        break;
                    } else {
                        // cross edge
                        debug!(
                            target: "libpijul::graph::dfs",
                            "cross edge, stack: {:?}, updating with {:?}",
                            conflict_stack, child
                        );
                        for c in conflict_stack.iter_mut() {
                            // If `child` was discovered after the
                            // beginning of this conflict, then we
                            // might be solving this conflict.
                            if dfs.first_visit(child) > dfs.first_visit(c.0) {
                                c.1 = std::cmp::min(c.1, child);
                            }
                        }
                        dfs.visits[child].ends_conflict = true
                    }
                    }
                }
                }
            }
            if let Some(child) = recursive_call {
                call_stack.push((n_scc, forward_scc, Some(descendants)));
                call_stack.push((child, HashSet::new(), None));
            } else {
            } else {
                dfs.mark_last_visit(n_scc);
                if dfs.visits[n_scc].begins_conflict.is_some() {
                    let (begin, end) = conflict_stack.pop().unwrap();
                    assert_eq!(begin, n_scc);
                    debug!(target: "libpijul::graph::dfs", "begins_conflict {:?}: {:?}", n_scc, end);
                    dfs.visits[n_scc].begins_conflict = Some(end);
                    dfs.visits[n_scc].begins_conflict = Some(end);
                }

                // After this, collect forward edges. Look at all
                // children of this SCC.
                for cousin in scc[n_scc].iter() {
                for cousin in scc[n_scc].iter() {
                    for &(edge, n_child) in self.children(*cousin) {
                        if let Some(mut edge) = edge {
                            // Is this edge a forward edge of the DAG?
                            // Is this edge a forward edge of the DAG?
                            if forward_scc.contains(&self[n_child].scc)
                                && edge.flag.contains(EdgeFlags::PSEUDO_EDGE)
                                && !txn.test_edge(
                                    branch,
                                    self[*cousin].key,
                                    edge.dest,
                                    EdgeFlags::DELETED_EDGE,
                                    EdgeFlags::DELETED_EDGE,
                                ) {
                                debug!(target: "libpijul::graph::dfs", "forward: {:?} {:?}", self[*cousin].key, edge);
                                forward.push((self[*cousin].key, edge))
                                forward.push((self[*cousin].key, edge))
                            } else {
                                // Does this edge have parallel PSEUDO edges? If so, they may not be "forward", but they are redundant.
                                edge.flag = EdgeFlags::PSEUDO_EDGE;
                                edge.introduced_by = ROOT_PATCH_ID;
                                let mut edges = txn
                                    .iter_nodes(branch, Some((self[*cousin].key, Some(edge))))
                                    .take_while(|&(k, v)| {
                                        k == self[*cousin].key
                                            && v.dest == edge.dest
                                            && v.flag
                                                <= EdgeFlags::FOLDER_EDGE | EdgeFlags::PSEUDO_EDGE
                                    });
                                edges.next(); // ignore the first pseudo-edge.
                                forward.extend(edges.map(|(k, v)| (k, v))); // add all parallel edges.
                            }
                            }
                            }
                        }
                        }
                    }
                }
            }
        }
    }
}

impl<A: Transaction, R> GenericTxn<A, R> {
    /// This function constructs a graph by reading the branch from the
    /// input key. It guarantees that all nodes but the first one (index
    /// 0) have a common descendant, which is index 0.
    pub fn retrieve<'a>(&'a self, branch: &Branch, key0: Key<PatchId>) -> Graph {
        let mut graph = Graph {
            lines: Vec::new(),
            children: Vec::new(),
        };
        // Insert last "dummy" line (so that all lines have a common descendant).
        graph.lines.push(Line {
            key: ROOT_KEY,
            flags: Flags::empty(),
            children: 0,
            n_children: 0,
            index: 0,
            lowlink: 0,
            scc: 0,
        });

        // Avoid the root key.
        let mut cache: HashMap<Key<PatchId>, VertexId> = HashMap::new();
        cache.insert(ROOT_KEY.clone(), DUMMY_VERTEX);
        let mut stack = Vec::new();
        if self.get_nodes(&branch, key0, None).is_some() {
            stack.push(key0)
        }
        while let Some(key) = stack.pop() {
            if cache.contains_key(&key) {
                // We're doing a DFS here, this can definitely happen.
                continue;
            }

            let idx = VertexId(graph.lines.len());
            cache.insert(key.clone(), idx);

            debug!("{:?}", key);
            let mut is_zombie = false;
            // Does this vertex have a DELETED/DELETED+FOLDER edge
            // pointing to it?
            let mut first_edge = Edge::zero(EdgeFlags::PARENT_EDGE | EdgeFlags::DELETED_EDGE);
            let mut nodes = self.iter_nodes(&branch, Some((key, Some(first_edge))));
            if let Some((k, v)) = nodes.next() {
                debug!("zombie? {:?} {:?}", k, v);
                if k == key
                    && (v.flag | EdgeFlags::FOLDER_EDGE == first_edge.flag | EdgeFlags::FOLDER_EDGE)
                {
                    // Does this vertex also have an alive edge
                    // pointing to it? (might not be the case for the
                    // first vertex)
                    if key == key0 {
                        first_edge.flag = EdgeFlags::PARENT_EDGE;
                        nodes = self.iter_nodes(&branch, Some((key, Some(first_edge))));
                        if let Some((_, v)) = nodes.next() {
                            // We know the key is `key`.
                            is_zombie = v.flag | EdgeFlags::FOLDER_EDGE
                                == first_edge.flag | EdgeFlags::FOLDER_EDGE
                        }
                    } else {
                        is_zombie = true
                    }
                }
            }
            debug!("is_zombie: {:?}", is_zombie);
            let mut l = Line {
                key: key.clone(),
                flags: if is_zombie {
                    Flags::LINE_HALF_DELETED
                } else {
                    Flags::empty()
                },
                children: graph.children.len(),
                n_children: 0,
                index: 0,
                lowlink: 0,
                scc: 0,
            };

            let mut last_flag = EdgeFlags::empty();
            let mut last_dest = ROOT_KEY;

            for (_, v) in self
                .iter_nodes(&branch, Some((key, None)))
                .take_while(|&(k, v)| {
                    k == key
                        && v.flag
                            <= EdgeFlags::PSEUDO_EDGE
                                | EdgeFlags::FOLDER_EDGE
                                | EdgeFlags::EPSILON_EDGE
                })
            {
                debug!("-> v = {:?}", v);
                if last_flag == EdgeFlags::PSEUDO_EDGE && last_dest == v.dest {
                    // This is a doubled edge, it should be removed.
                } else if v.flag.contains(EdgeFlags::EPSILON_EDGE) {
                    /*} else if v.flag.contains(EdgeFlags::EPSILON_EDGE) {
                    // Epsilon lines are skipped.
                    for (_, v_) in self
                        .iter_nodes(&branch, Some((v.dest, None)))
                        .take_while(|&(k_, v_)| {
                            k_ == v.dest
                                && v_.flag
                                <= EdgeFlags::PSEUDO_EDGE
                                | EdgeFlags::FOLDER_EDGE
                                | EdgeFlags::EPSILON_EDGE
                        }) {
                            graph.children.push((Some(v_.clone()), DUMMY_VERTEX));
                            l.n_children += 1;
                            if !cache.contains_key(&v_.dest) {
                                stack.push(v_.dest.clone())
                            } else {
                                debug!("v already visited");
                            }
                            last_flag = v_.flag;
                            last_dest = v_.dest;
                        }
                     */
                } else {
                    graph.children.push((Some(v.clone()), DUMMY_VERTEX));
                    l.n_children += 1;
                    if !cache.contains_key(&v.dest) {
                        stack.push(v.dest.clone())
                    } else {
                        debug!("v already visited");
                    }
                    last_flag = v.flag;
                    last_dest = v.dest;
                }
            }
            // If this key has no children, give it the dummy child.
            if l.n_children == 0 {
                debug!("no children for {:?}", l);
                graph.children.push((None, DUMMY_VERTEX));
                l.n_children = 1;
            }
            graph.lines.push(l)
        }
        for &mut (ref child_key, ref mut child_idx) in graph.children.iter_mut() {
            if let Some(ref child_key) = *child_key {
                if let Some(idx) = cache.get(&child_key.dest) {
                    *child_idx = *idx
                }
            }
        }
        graph
    }
}

/// The conflict markers keep track of the number of conflicts, and is
/// used for outputting conflicts to a given LineBuffer.
///
/// "Zombie" conflicts are those conflicts introduced by zombie
/// vertices in the contained Graph.
struct ConflictMarkers {
    current_conflicts: usize,
}

impl ConflictMarkers {
    /*
    fn output_zombie_markers_if_needed<'a, A: Transaction + 'a, B: LineBuffer<'a, A>>(
        &mut self,
        buf: &mut B,
        vertex: VertexId,
    ) -> Result<()> {
        if self.graph[vertex].is_zombie() {
            if !self.current_is_zombie {
                debug!("begin zombie conflict: vertex = {:?}", self.graph[vertex]);
                self.current_is_zombie = true;
                buf.begin_zombie_conflict()?;
            }
        } else if self.current_is_zombie {
            // Zombie segment has ended
            if !self.current_is_zombie {
                debug!("end zombie conflict: vertex = {:?}", self.graph[vertex]);
            }
            self.current_is_zombie = false;
            buf.end_conflict()?;
        }
        Ok(())
    }
    */
    fn begin_conflict<'a, A: Transaction + 'a, B: LineBuffer<'a, A>>(
        &mut self,
        buf: &mut B,
    ) -> Result<()> {
        buf.begin_conflict()?;
        self.current_conflicts += 1;
        Ok(())
    }
    fn end_conflict<'a, A: Transaction + 'a, B: LineBuffer<'a, A>>(
        &mut self,
        buf: &mut B,
    ) -> Result<()> {
        if self.current_conflicts > 0 {
            buf.end_conflict()?;
            self.current_conflicts -= 1;
        }
        Ok(())
    }
}

impl PathElement {
    fn smallest_line(&self, graph: &Graph, sccs: &[Vec<VertexId>]) -> Key<PatchId> {
        match *self {
            PathElement::Scc { ref scc } => sccs[*scc].iter().map(|x| graph[*x].key).min().unwrap(),
            PathElement::Conflict { ref sides } => sides
                .iter()
                .map(|x|
                     x.path.iter().map(|x| x.smallest_line(graph, sccs))
                     .min().unwrap())
                .min()
                .unwrap(),
    }
    }
}

impl<'a, A: Transaction + 'a, R> GenericTxn<A, R> {
    fn output_conflict<B: LineBuffer<'a, A>>(
        &'a self,
        conflicts: &mut ConflictMarkers,
        buf: &mut B,
        graph: &Graph,
        sccs: &[Vec<VertexId>],
        conflict: &mut [Path],
    ) -> Result<usize> {
        let mut is_first = true;
        let n_sides = conflict.len();
        debug!(target:"libpijul::graph::output_conflict", "n_sides = {:?}", n_sides);
        let mut n_conflicts = 0;
        if n_sides > 1 {
            conflicts.begin_conflict(buf)?;
            n_conflicts += 1;
        }
        conflict.sort_by(|a, b| {
            let a = a.path.iter().map(|a| a.smallest_line(graph, sccs)).min().unwrap();
            let b = b.path.iter().map(|a| a.smallest_line(graph, sccs)).min().unwrap();
            a.cmp(&b)
        });
        for side in conflict {
            if !is_first {
                buf.conflict_next()?;
            }
            is_first = false;
            debug!(target:"libpijul::graph::output_conflict", "side = {:?}", side);
            for i in side.path.iter_mut() {
                match *i {
                    PathElement::Scc { scc } => {
                        debug!(target:"libpijul::graph::output_conflict", "output {:?}", scc);
                        self.output_scc(graph, &sccs[scc], buf)?
                    },
                    PathElement::Conflict { ref mut sides } => {
                        debug!(target:"libpijul::graph::output_conflict", "begin conflict {:?}", sides);
                        n_conflicts += self.output_conflict(conflicts, buf, graph, sccs, sides)?;
                        debug!(target:"libpijul::graph::output_conflict", "end conflict");
                    }
                }
            }
        }
        if n_sides > 1 {
            conflicts.end_conflict(buf)?;
        }
        Ok(n_conflicts)
    }

    /// Output the database contents of the file into the buffer
    /// `buf`. The return value indicates whether there are any
    /// conflicts in the file that was output. If forward edges are
    /// encountered, they are collected into `forward`.
    ///
    pub fn output_file<B: LineBuffer<'a, A>>(
        &'a self,
        branch: &Branch,
        buf: &mut B,
        graph: &mut Graph,
        forward: &mut Vec<(Key<PatchId>, Edge)>,
    ) -> Result<usize> {
        debug!("output_file");
        if graph.lines.len() <= 1 {
            return Ok(0);
        }
        let scc = graph.tarjan(); // SCCs are given here in reverse order.
        debug!("There are {} SCC", scc.len());
        debug!("SCCs = {:?}", scc);

        let mut dfs = DFS::new(scc.len());
        let conflict_tree = graph.dfs(self, branch, &scc, &mut dfs, forward);

        debug!("dfs done");
        buf.output_line(&graph.lines[1].key, Value::from_slice(b""))?;
        // let conflict_tree = conflict_tree(graph, &scc, &mut dfs);
        debug!("conflict_tree = {:?}", conflict_tree);
        let mut conflicts = ConflictMarkers {
            current_conflicts: 0,
        };
        let n_conflicts =
            self.output_conflict(&mut conflicts, buf, graph, &scc, &mut [conflict_tree])?;
        // Close any remaining zombie part (if needed).
        // conflicts.output_zombie_markers_if_needed(buf, DUMMY_VERTEX)?;
        debug!("/output_file");
        Ok(n_conflicts)
    }

    fn output_scc<B: LineBuffer<'a, A>>(
        &'a self,
        // conflicts: &mut ConflictMarkers,
        graph: &Graph,
        scc: &[VertexId],
        buf: &mut B,
    ) -> Result<()> {
        assert_eq!(scc.len(), 1);
        // conflicts.output_zombie_markers_if_needed(buf, scc[0])?;
        if graph[scc[0]].is_zombie() {
            debug!(target:"libpijul::graph::output_conflict", "zombie {:?}", graph[scc[0]].key);
            buf.begin_zombie_conflict()?;
        }
        let key = graph[scc[0]].key;
        if let Some(cont) = self.get_contents(key) {
            debug!(target:"libpijul::graph::output_conflict", "outputting {:?}", cont);
            buf.output_line(&key, cont)?;
        }
        if graph[scc[0]].is_zombie() {
            buf.end_conflict()?;
        }
        Ok(())
    }
}

struct ConflictTree<'a> {
    stack: Vec<(usize, State)>,
    graph: &'a Graph,
    scc: &'a [Vec<VertexId>],
    dfs: &'a mut DFS,
}

impl<'a> ConflictTree<'a> {
    fn new(graph: &'a Graph, scc: &'a [Vec<VertexId>], dfs: &'a mut DFS) -> Self {
        ConflictTree {
            stack: vec![
                (scc.len() - 1,
                 State::EvalConflict {
                     start: scc.len() - 1,
                     cur: 1,
                     last_visit: 0,
                     sides: vec![Side {
                         next: scc.len() - 1,
                         side: vec![],
                     }],
                 })
            ],
            graph,
            scc,
            dfs,
        }
    }

    fn begin_conflict(&mut self, i: usize, c: usize) {
        if let Some((
            _,
            State::EvalConflict {
                ref cur,
                ref mut sides,
                ..
            },
        )) = self.stack.last_mut()
        {
            sides[*cur].next = c;
            sides[*cur].side.push(ConflictLine::Line(i))
        }
        debug!(target: "tree", "BEGINS CONFLICT {:?}", c);
        let mut sides = Vec::new();
        for cousin in self.scc[i].iter() {
            for &(e, n_child) in self.graph.children(*cousin) {
                debug!("cousin: {:?}", self.graph[n_child].scc);
                let is_ok = match e {
                    Some(e) if e.flag.contains(EdgeFlags::FOLDER_EDGE) => false,
                    _ => true
                };
                if is_ok {
                    let next = self.graph[n_child].scc;
                    sides.push(Side {
                        next,
                        side: Vec::new(),
                    })
                }
            }
        }
        sides.sort_by(|a, b| a.next.cmp(&b.next));
        debug!(target: "tree", "sides: {:?}", sides);
        let cur = sides.len();
        self.stack.push((
            i,
            State::EvalConflict {
                sides,
                start: i,
                last_visit: 0,
                cur,
            },
        ));

    }

    fn normal_line(&mut self, i: usize) {
        if let Some((
            _,
            State::EvalConflict {
                ref cur,
                ref mut sides,
                ..
            },
        )) = self.stack.last_mut()
        {
            sides[*cur].side.push(ConflictLine::Line(i))
        } else {
            unimplemented!()
        }
        let mut max_scc = None;
        for cousin in self.scc[i].iter() {
            for &(e, n_child) in self.graph.children(*cousin) {
                let is_ok = match e {
                    Some(e) if e.flag.contains(EdgeFlags::FOLDER_EDGE) => false,
                    _ => true
                };
                if is_ok {
                    let next = self.graph[n_child].scc;
                    max_scc = std::cmp::max(max_scc, Some(next))
                }
            }
        }
        debug!(target: "tree", "max_scc = {:?}", max_scc);
        if let Some(max_scc) = max_scc {
            self.stack.push((
                max_scc,
                State::Init {
                    resume_after_conflict: false,
                },
            ))
        }
    }

    fn visit_next_side(&mut self, i: usize, start: usize, cur: usize, last_visit: usize, sides: Vec<Side>) {
        let next = sides[cur - 1].next;
        let visit_next = self.dfs.visits[next].first > last_visit;
        self.stack.push((
            i,
            State::EvalConflict {
                start,
                cur: cur - 1,
                last_visit: if visit_next {
                    self.dfs.visits[next].last
                } else {
                    last_visit
                },
                sides,
            },
        ));
        debug!("visit_next ({:?}): {:?}", next, visit_next);
        if visit_next {
            self.stack.push((
                next,
                State::Init {
                    resume_after_conflict: self.dfs.visits[next].ends_conflict,
                },
            ));
        }
    }

    fn finish_conflict(&mut self, sides: Vec<Side>, next: usize) {
        let mut current: Vec<_> = sides
            .into_iter()
            .filter_map(|x| {
                if x.side.is_empty() {
                    None
                } else {
                    Some(x.side)
                }
            }).collect();
        if let Some((
            _,
            State::EvalConflict {
                ref cur,
                ref mut sides,
                ..
            },
        )) = self.stack.last_mut()
        {
            if current.len() >= 2 {
                // If there are at least two sides, this is a conflict.
                sides[*cur].side.push(ConflictLine::Conflict(current));
                sides[*cur].next = next;
            } else if let Some(current) = current.pop() {
                // Else, it is not a conflict, just extend.
                sides[*cur].side.extend(current.into_iter());
                sides[*cur].next = next;
            }
        }
    }

    fn continue_conflict(&mut self, sides: Vec<Side>) -> Vec<Side> {
        let mut sides_ = Vec::new();
        let mut next = sides[0].next;
        let mut current = Vec::new();
        debug!(target:"tree", "sides {:?}", sides);
        for side in sides.into_iter().filter(|x| !x.side.is_empty()) {
            debug!(target:"tree", "side {:?}", side);
            if side.next != next {
                let mut cur = std::mem::replace(&mut current, Vec::new());
                if cur.len() >= 2 {
                    sides_.push(Side {
                        next,
                        side: vec![ConflictLine::Conflict(cur)],
                    });
                } else if let Some(side) = cur.pop() {
                    sides_.push(Side {
                        next,
                        side,
                    })
                }
                next = side.next;
            }
            current.push(side.side);
        }
        if current.len() >= 2 {
            sides_.push(Side {
                next,
                side: vec![ConflictLine::Conflict(current)],
            });
        } else if let Some(side) = current.pop() {
            sides_.push(Side {
                next,
                side,
            })
        }
        debug!(target:"tree", "conflict reduction {:?}", sides_);
        assert!(sides_.len() > 1);
        sides_
    }
    }
    }
}

fn conflict_tree(graph: &Graph, scc: &[Vec<VertexId>], dfs: &mut DFS) -> Vec<ConflictLine> {
    debug!(target: "tree", "scc = {:?}", scc);
    let mut conflict = ConflictTree::new(graph, scc, dfs);
    debug!(target: "tree", "conflict tree starting");
    debug!(target: "tree", "conflict tree starting");


    while let Some((i, state)) = conflict.stack.pop() {
        debug!(target: "tree", ">>>>>>>>>>>>> {:?} ({:?}): {:?}, {:?}", i, scc[i], graph[scc[i][0]].key, conflict.dfs.visits[i]);
        debug!(target: "tree", "state: {:?}", state);
        debug!(target: "tree", "state: {:?}", state);
        debug!(target: "tree", "stack: {:?}", conflict.stack);
        match state {
        match state {
        match state {
            State::Init { resume_after_conflict } => {
                debug!(target:"tree", "new visit to {:?}", graph[scc[i][0]].key);
                debug!(target:"tree", "new visit to {:?}", graph[scc[i][0]].key);
                conflict.dfs.visits[i].output = true;
                if conflict.dfs.visits[i].ends_conflict {
                    debug!(target: "tree", "ends conflict, resume = {:?}", resume_after_conflict);
                }
                if conflict.dfs.visits[i].ends_conflict && !resume_after_conflict {
                    // We're not resuming after this conflict, so we
                    // just register where this side of the current
                    // conflict ends (and we already popped the stack).
                    if let Some((
                    if let Some((
                        _,
                        State::EvalConflict {
                            ref mut sides,
                            ref mut cur,
                            ..
                        },
                    )) = conflict.stack.last_mut()
                    {
                    {
                        sides[*cur].next = i
                    }
                    }
                } else {
                    // Else, we are exploring a line normally. If this
                    // line starts a conflict, then push the new
                    // conflict, else explore the line normally.
                    debug!(target: "tree", "begins = {:?}", conflict.dfs.visits[i].begins_conflict);
                    if let Some(c) = conflict.dfs.visits[i].begins_conflict {
                        conflict.begin_conflict(i, c)
                    } else {
                    } else {
                        conflict.normal_line(i)
                    }
                    }
                    }
                }
            }
            State::EvalConflict {
                start,
                mut cur,
                last_visit,
                mut sides,
            } => {
                debug!(target: "tree", "EvalConflict");
                if cur > 0 {
                if cur > 0 {
                if cur > 0 {
                    // Recurse, i.e. visit the next unvisited
                    // component of this conflict.
                    debug!(target: "tree", "Visiting the next unvisited component");
                    conflict.visit_next_side(i, start, cur, last_visit, sides)
                } else if conflict.stack.is_empty() {
                    // We're done, return.
                    // We're done, return.
                    debug!(target: "tree", "Conflict stack empty");
                    assert_eq!(sides.len(), 1);
                    assert_eq!(sides.len(), 1);
                    let side = sides.pop().unwrap();
                    assert!(sides.is_empty());
                    return side.side;
                } else {
                } else {
                    sides.sort_by(|a, b| a.next.cmp(&b.next));
                    // This conflict is over if all its sides have the same `next`.
                    let next = sides.iter().filter(|x| !x.side.is_empty()).next().unwrap().next;
                    let conflict_is_over = {
                    let conflict_is_over = {
                    let conflict_is_over = {
                        sides.iter().all(|x| x.side.is_empty() || x.next == next)
                        sides.iter().all(|x| x.side.is_empty() || x.next == next)
                    };
                    debug!(target: "tree", "Conflict_is_over: {:?}, next = {:?}", conflict_is_over, next);
                    if conflict_is_over {
                    if conflict_is_over {
                    if conflict_is_over {
                        // The conflict is over.
                        conflict.finish_conflict(sides, next);
                        conflict.stack.push((
                            next,
                            State::Init {
                            State::Init {
                                resume_after_conflict: true,
                            },
                            },
                        ));
                    } else {
                        // The conflict is not over.
                        let sides_ = conflict.continue_conflict(sides);
                        conflict.stack.push((
                            i,
                            i,
                            State::EvalConflict {
                                start,
                                cur: sides_.len(),
                                last_visit: 0,
                                sides: sides_,
                            },
                        ));

                    }
                    }
                }
                }
            }
        }
    }
    unreachable!()
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

    F: FnMut(usize, &Hash),
{
    use fs_representation::*;
    info!("applying patches with size_increase {:?}", size_increase);
    let repo = target.open_repo(Some(size_increase as u64))?;
    let mut txn = repo.mut_txn_begin(rand::thread_rng())?;
    let mut branch = txn.open_branch(branch_name)?;
    let conflicts = txn.apply_patches(
        diff_algorithm,
        &mut branch,
        target,
        &patches,
        partial_paths,
        apply_cb,
    )?;
    txn.commit_branch(branch)?;
    txn.commit()?;
    Ok(conflicts)
}

/// 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, F, I>(
    target: &RepoRoot<impl AsRef<Path>>,
    branch_name: &str,
    remote: I,
    apply_cb: F,
) -> Result<()>
where
    I: Iterator<Item = &'a Hash>,
    F: FnMut(usize, &Hash),
{
    let (patches, size_increase) = make_remote(target, remote)?;
    apply_resize_patches_no_output(target, branch_name, &patches, size_increase, apply_cb)
}

pub fn apply_resize_patches_no_output<'a, F>(
    target: &RepoRoot<impl AsRef<Path>>,
    branch_name: &str,
    patches: &[(Hash, Patch)],
    size_increase: usize,
    mut apply_cb: F,
) -> Result<()>
where
    F: FnMut(usize, &Hash),
{
    use fs_representation::*;

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

use libc;
use std;
use std::io::{Read, Write};
use utf8parse;

fn size() -> (usize, usize) {
    unsafe {
        let mut size: libc::winsize = std::mem::zeroed();

        // Albeit it may look useless in the general case, the use of `into()`
        // here is justified for portability reason.  It looks like there is a
        // type mismatch in the `libc` API for FreeBSD, which prevents `line`
        // from compiling.
        if libc::ioctl(1, libc::TIOCGWINSZ.into(), &mut size) == 0 {
            (size.ws_col as usize, size.ws_row as usize)
        } else {
            (0, 0)
        }
    }
}

pub struct Terminal {
    attr: libc::termios,
    posx: usize,
    posy: usize,
    posx0: usize,
    posy0: usize,
    cursor: usize,
    n_chars: usize,
    buf: String,
}

impl Terminal {
    pub fn new() -> Option<Terminal> {
        unsafe {
            if libc::isatty(0) != 0 {
                let mut attr = std::mem::zeroed();
                libc::tcgetattr(0, &mut attr);

                // attr type implements copy and therefore does not need to be
                // cloned
                let attr_orig = attr;

                attr.c_iflag &=
                    !(libc::BRKINT | libc::ICRNL | libc::INPCK | libc::ISTRIP | libc::IXON);
                attr.c_oflag &= !libc::OPOST;
                attr.c_lflag &= !(libc::ECHO | libc::ICANON | libc::IEXTEN | libc::ISIG);
                libc::tcsetattr(0, libc::TCSAFLUSH, &attr);
                Some(Terminal {
                    attr: attr_orig,
                    posx: 0,
                    posy: 0,
                    posx0: 0,
                    posy0: 0,
                    cursor: 0,
                    n_chars: 0,
                    buf: String::new(),
                })
            } else {
                None
            }
        }
    }
}

impl Drop for Terminal {
    fn drop(&mut self) {
        unsafe {
            libc::tcsetattr(0, libc::TCSAFLUSH, &self.attr);
        }
    }
}

fn next_char(s: &str, i: usize) -> usize {
    let s = s.as_bytes();
    if s[i] <= 0x7f {
        i + 1
    } else if s[i] >> 5 == 0b110 {
        i + 2
    } else if s[i] >> 4 == 0b1110 {
        i + 3
    } else {
        i + 4
    }
}

fn prev_char(s: &str, mut i: usize) -> usize {
    let s = s.as_bytes();
    i -= 1;
    while s[i] & 0b1100_0000 == 0b1000_0000 {
        i -= 1
    }
    i
}

impl Terminal {
    fn move_left(&mut self) -> Result<(), std::io::Error> {
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

333
334


337


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

403


406

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
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693

694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007

1008
1009

use atty;
use error::Error;
use libpijul::{EdgeFlags, Hash, LineId, MutTxn, PatchId};
use rand;
use std;
use std::char::from_u32;
use std::fs::{remove_file, File};
use std::process;
use std::str;
use term;
use term::{Attr, StdoutTerminal};

use ignore::gitignore::GitignoreBuilder;
use line;

const BINARY_CONTENTS: &'static str = "<binary contents>";
#[derive(Clone, Copy)]
pub enum Command {
    Pull,
    Push,
    Unrecord,
}

impl Command {
    fn verb(&self) -> &'static str {
        match *self {
            Command::Push => "push",
            Command::Pull => "pull",
            Command::Unrecord => "unrecord",
        }
    }
}

fn print_section(term: &mut Option<Box<StdoutTerminal>>, title: &str, contents: &str) {
    if let Some(ref mut term) = *term {
        term.attr(Attr::Bold).unwrap_or(());
    }
    let mut stdout = std::io::stdout();
    write!(stdout, "{}", title).unwrap_or(());
    if let Some(ref mut term) = *term {
        term.reset().unwrap_or(());
    }
    writeln!(stdout, "{}", contents).unwrap_or(());
}

fn remove_escape_codes(f: &str) -> std::borrow::Cow<str> {
    if f.as_bytes().contains(&27) {
        std::borrow::Cow::Owned(f.chars().filter(|&c| c != 27 as char).collect())
    } else {
        std::borrow::Cow::Borrowed(f)
    }
}

pub fn print_patch_descr(
    term: &mut Option<Box<StdoutTerminal>>,
    hash: &Hash,
    internal: Option<PatchId>,
    patch: &PatchHeader,
) {
    print_section(term, "Hash:", &format!(" {}", &hash.to_base58()));
    if let Some(internal) = internal {
        print_section(term, "Internal id:", &format!(" {}", &internal.to_base58()));
    }

    print_section(
        term,
        "Authors:",
        &format!(" {}", remove_escape_codes(&patch.authors.join(", "))),
    );
    print_section(term, "Timestamp:", &format!(" {}", patch.timestamp));

    let is_tag = if !patch.flag.is_empty() { "TAG: " } else { "" };

    let mut stdout = std::io::stdout();
    writeln!(
        stdout,
        "\n    {}{}",
        is_tag,
        remove_escape_codes(&patch.name)
    )
    .unwrap_or(());
    if let Some(ref d) = patch.description {
        writeln!(stdout, "").unwrap_or(());
        let d = remove_escape_codes(d);
        for descr_line in d.lines() {
            writeln!(stdout, "    {}", descr_line).unwrap_or(());
        }
    }
    writeln!(stdout, "").unwrap_or(());
}

fn check_forced_decision(
    command: Command,
    choices: &HashMap<&Hash, bool>,
    rev_dependencies: &HashMap<&Hash, Vec<&Hash>>,
    a: &Hash,
    b: &Patch,
) -> Option<bool> {
    let covariant = match command {
        Command::Pull | Command::Push => true,
        Command::Unrecord => false,
    };
    // If we've selected patches that depend on a, and this is a pull
    // or a push, select a.
    if let Some(x) = rev_dependencies.get(a) {
        for y in x {
            // Here, y depends on a.
            //
            // If this command is covariant, and we've selected y, select a.
            // If this command is covariant, and we've unselected y, don't do anything.
            //
            // If this command is contravariant, and we've selected y, don't do anything.
            // If this command is contravariant, and we've unselected y, unselect a.
            if let Some(&choice) = choices.get(y) {
                if choice == covariant {
                    return Some(covariant);
                }
            }
        }
    };

    // If we've unselected dependencies of a, unselect a.
    for y in b.dependencies().iter() {
        // Here, a depends on y.
        //
        // If this command is covariant, and we've selected y, don't do anything.
        // If this command is covariant, and we've unselected y, unselect a.
        //
        // If this command is contravariant, and we've selected y, select a.
        // If this command is contravariant, and we've unselected y, don't do anything.

        if let Some(&choice) = choices.get(&y) {
            if choice != covariant {
                return Some(!covariant);
            }
        }
    }

    None
}

fn interactive_ask(
    getch: &getch::Getch,
    a: &Hash,
    patchid: Option<PatchId>,
    b: &Patch,
    command_name: Command,
    show_help: bool,
) -> Result<(char, Option<bool>), Error> {
    let mut term = if stdout_isatty() {
    let mut term = if atty::is(atty::Stream::Stdout) {
        term::stdout()
    } else {
        None
    };
    print_patch_descr(&mut term, a, patchid, b);

    if show_help {
        display_help(command_name);
        print!("Shall I {} this patch? ", command_name.verb());
    } else {
        print!("Shall I {} this patch? [ynkad?] ", command_name.verb());
    }

    stdout().flush()?;
    match getch.getch().ok().and_then(|x| from_u32(x as u32)) {
        Some(e) => {
            println!("{}", e);
            let e = e.to_uppercase().next().unwrap_or('\0');
            match e {
                'A' => Ok(('Y', Some(true))),
                'D' => Ok(('N', Some(false))),
                e => Ok((e, None)),
            }
        }
        _ => Ok(('\0', None)),
    }
}

fn display_help(c: Command) {
    println!("Available options: ynkad?");
    println!("y: {} this patch", c.verb());
    println!("n: don't {} this patch", c.verb());
    println!("k: go bacK to the previous patch");
    println!("a: {} all remaining patches", c.verb());
    println!("d: finish, skipping all remaining patches");
    println!("")
}

/// Patches might have a dummy "changes" field here.
pub fn ask_patches(
    command: Command,
    patches: &[(Hash, Option<PatchId>, Patch)],
) -> Result<Vec<Hash>, Error> {
    let getch = getch::Getch::new();
    let mut i = 0;

    // Record of the user's choices.
    let mut choices: HashMap<&Hash, bool> = HashMap::new();

    // For each patch, the list of patches that depend on it.
    let mut rev_dependencies: HashMap<&Hash, Vec<&Hash>> = HashMap::new();

    // Decision for the remaining patches ('a' or 'd'), if any.
    let mut final_decision = None;
    let mut show_help = false;

    while i < patches.len() {
        let (ref a, patchid, ref b) = patches[i];
        let forced_decision = check_forced_decision(command, &choices, &rev_dependencies, a, b);

        // Is the decision already forced by a previous choice?
        let e = match final_decision.or(forced_decision) {
            Some(true) => 'Y',
            Some(false) => 'N',
            None => {
                debug!("decision not forced");
                let (current, remaining) =
                    interactive_ask(&getch, a, patchid, b, command, show_help)?;
                final_decision = remaining;
                current
            }
        };

        show_help = false;

        debug!("decision: {:?}", e);
        match e {
            'Y' => {
                choices.insert(a, true);
                match command {
                    Command::Pull | Command::Push => {
                        for ref dep in b.dependencies().iter() {
                            let d = rev_dependencies.entry(dep).or_insert(vec![]);
                            d.push(a)
                        }
                    }
                    Command::Unrecord => {}
                }
                i += 1
            }
            'N' => {
                choices.insert(a, false);
                match command {
                    Command::Unrecord => {
                        for ref dep in b.dependencies().iter() {
                            let d = rev_dependencies.entry(dep).or_insert(vec![]);
                            d.push(a)
                        }
                    }
                    Command::Pull | Command::Push => {}
                }
                i += 1
            }
            'K' if i > 0 => {
                let (ref a, _, _) = patches[i];
                choices.remove(a);
                i -= 1
            }
            '?' => {
                show_help = true;
            }
            _ => {}
        }
    }
    Ok(patches
        .into_iter()
        .filter_map(|&(ref hash, _, _)| {
            if let Some(true) = choices.get(hash) {
                Some(hash.to_owned())
            } else {
                None
            }
        })
        .collect())
}

/// Compute the dependencies of this change.
fn change_deps(
    id: usize,
    c: &Record<ChangeContext<Hash>>,
    provided_by: &mut HashMap<LineId, usize>,
) -> HashSet<LineId> {
    let mut s = HashSet::new();
    for c in c.iter() {
        match *c {
            Change::NewNodes {
                ref up_context,
                ref down_context,
                ref line_num,
                ref nodes,
                ..
            } => {
                for cont in up_context.iter().chain(down_context) {
                    if cont.patch.is_none() && !cont.line.is_root() {
                        s.insert(cont.line.clone());
                    }
                }
                for i in 0..nodes.len() {
                    provided_by.insert(*line_num + i, id);
                }
            }
            Change::NewEdges { ref edges, .. } => {
                for e in edges {
                    if e.from.patch.is_none() && !e.from.line.is_root() {
                        s.insert(e.from.line.clone());
                    }
                    if e.to.patch.is_none() && !e.from.line.is_root() {
                        s.insert(e.to.line.clone());
                    }
                }
            }
        }
    }
    s
}


>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
fn print_record<T: rand::Rng>(
    repo_root: &RepoRoot<impl AsRef<Path>>,

================================

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
fn print_change<T: rand::Rng>(

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    term: &mut Option<Box<StdoutTerminal>>,
    cwd: &Path,
    repo: &MutTxn<T>,
    current_file: &mut Option<Rc<RepoPath<PathBuf>>>,
    c: &Record<ChangeContext<Hash>>,
) -> Result<(), Error> {
    match *c {
        Record::FileAdd {
            ref name,
            ref contents,
            ..
        } => {
            if let Some(ref mut term) = *term {
                term.fg(term::color::CYAN).unwrap_or(());
            }
            print!("added file ");
            if let Some(ref mut term) = *term {
                term.reset().unwrap_or(());
            }
            println!("{}", pretty_repo_path(repo_root, name, cwd).display());
            if let Some(ref change) = contents {
                print_change(term, repo, 0, 0, change)?;
            }
            Ok(())
        }
        Record::FileDel {
            ref name,
            ref contents,
            ..
        } => {
            if let Some(ref mut term) = *term {
                term.fg(term::color::MAGENTA).unwrap_or(());
            }
            print!("deleted file: ");
            if let Some(ref mut term) = *term {
                term.reset().unwrap_or(());
            }
            println!("{}", pretty_repo_path(repo_root, name, cwd).display());
            if let Some(ref change) = contents {
                print_change(term, repo, 0, 0, change)?;
            }
            Ok(())
        }
        Record::FileMove { ref new_name, .. } => {
            if let Some(ref mut term) = *term {
                term.fg(term::color::YELLOW).unwrap_or(());
            }
            print!("file moved to: ");
            if let Some(ref mut term) = *term {
                term.reset().unwrap_or(());
            }
            println!("{}", pretty_repo_path(repo_root, new_name, cwd).display());
            Ok(())
        }
        Record::Change {
            ref change,
            ref replacement,
            ref file,
            old_line,
            new_line,
            ..
        } => {

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
                            }

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
                            if let Some(ref mut term) = *term {

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
            let mut file_changed = true;
            if let Some(ref cur_file) = *current_file {
                if file == cur_file {
                    file_changed = false;
                }
            }
            if file_changed {
                if let Some(ref mut term) = *term {
                    term.attr(Attr::Bold).unwrap_or(());
                    term.attr(Attr::Underline(true)).unwrap_or(());
                }
                println!("{}", pretty_repo_path(repo_root, file, cwd).display());
                if let Some(ref mut term) = *term {
                    term.reset().unwrap_or(());
                }
                *current_file = Some(file.clone())
            }

            print_change(term, repo, old_line, new_line, change)?;
            if let Some(ref c) = *replacement {
                print_change(term, repo, old_line, new_line, c)?
            }
            Ok(())
        }
    }
}

fn print_change<T: rand::Rng>(
    term: &mut Option<Box<StdoutTerminal>>,
    repo: &MutTxn<T>,
    old_line: usize,
    new_line: usize,
    change: &Change<ChangeContext<Hash>>,
) -> Result<(), Error> {
    match *change {
        Change::NewNodes {
            // ref up_context,ref down_context,ref line_num,
            ref flag,
            ref nodes,
            ..
        } => {
            if flag.contains(EdgeFlags::FOLDER_EDGE) {
                for n in nodes {
                    if n.len() >= 2 {
                        if let Some(ref mut term) = *term {
                            term.fg(term::color::CYAN).unwrap_or(());
                        }
                        print!("new file ");
                        if let Some(ref mut term) = *term {
                            term.reset().unwrap_or(());
                        }
                        println!("{}", str::from_utf8(&n[2..]).unwrap_or(""));
                    }
                }
            } else {
                if new_line > 0 {
                    println!("From line {}\n", new_line);
                }

                for n in nodes {
                    let s = str::from_utf8(n).unwrap_or(BINARY_CONTENTS);
                    if let Some(ref mut term) = *term {
                        term.fg(term::color::GREEN).unwrap_or(());
                    }
                    print!("+ ");
                    if let Some(ref mut term) = *term {
                        term.reset().unwrap_or(());
                    }
                    if s.ends_with("\n") {
                        print!("{}", s);
                    } else {
                        println!("{}", s);
                    }
                }
            }
            Ok(())
        }
        Change::NewEdges {
            ref edges, flag, ..
        } => {
            let mut h_targets = HashSet::with_capacity(edges.len());

            if old_line > 0 {
                println!("From line {}\n", old_line);
            }
            for e in edges {
                let (target, flag) = if !flag.contains(EdgeFlags::PARENT_EDGE) {
                    if h_targets.insert(&e.to) {
                        (Some(&e.to), flag)
                    } else {
                        (None, flag)
                    }
                } else {
                    if h_targets.insert(&e.from) {
                        (Some(&e.from), flag)
                    } else {
                        (None, flag)
                    }
                };
                if let Some(target) = target {
                    let internal = repo.internal_key_unwrap(target);
                    let l = repo.get_contents(internal).unwrap();
                    let l = l.into_cow();
                    let s = str::from_utf8(&l).unwrap_or(BINARY_CONTENTS);

                    if flag.contains(EdgeFlags::DELETED_EDGE) {
                        if let Some(ref mut term) = *term {
                            term.fg(term::color::RED).unwrap_or(());
                        }
                        print!("- ");
                    } else {
                        if let Some(ref mut term) = *term {
                            term.fg(term::color::GREEN).unwrap_or(());
                        }
                        print!("+ ");
                    }
                    if let Some(ref mut term) = *term {
                        term.reset().unwrap_or(());
                    }
                    if s.ends_with("\n") {
                        print!("{}", s)
                    } else {
                        println!("{}", s)
                    }
                }
            }
            Ok(())
        }
    }
}

#[derive(Clone, Copy, Debug)]
pub enum ChangesDirection {
    Record,
    Revert,
}

impl ChangesDirection {
    fn is_record(&self) -> bool {
        match *self {
            ChangesDirection::Record => true,
            _ => false,
        }
    }
    fn verb(&self) -> &str {
        match *self {
            ChangesDirection::Record => "record",
            ChangesDirection::Revert => "revert",
        }
    }
}

fn display_help_changes(
    potential_new_ignore: Option<&RepoPath<impl AsRef<Path>>>,
    direction: ChangesDirection,
) {
    println!("Available options:");
    println!("y: {} this change", direction.verb());
    println!("n: don't {} this change", direction.verb());
    println!(
        "f: {} the rest of the changes to this file",
        direction.verb()
    );
    println!(
        "s: don't {} the rest of the changes to this file",
        direction.verb()
    );
    println!("k: go back to the previous change");
    println!("a: {} all remaining changes", direction.verb());
    println!("d: skip all remaining changes");
    match potential_new_ignore {
        Some(filename) => println!("i: ignore file {}", filename.display()),
        None => (),
    }
    println!("")
}

fn prompt_one_change<T: rand::Rng>(
    repository: &MutTxn<T>,
    repo_root: &RepoRoot<impl AsRef<Path>>,
    change: &Record<ChangeContext<Hash>>,
    current_file: &mut Option<Rc<RepoPath<PathBuf>>>,
    n_changes: usize,
    i: usize,
    direction: ChangesDirection,
    potential_new_ignore: Option<&RepoPath<impl AsRef<Path>>>,
    terminal: &mut Option<Box<StdoutTerminal>>,
    getch: &getch::Getch,
    cwd: &Path,
    show_help: bool,
) -> Result<(char, Option<char>, Option<char>), Error> {
    debug!("changes: {:?}", change);
    print_record(repo_root, terminal, cwd, repository, current_file, &change)?;
    println!("");
    let choices = if potential_new_ignore.is_some() {
        "[ynsfkadi?]"
    } else {
        "[ynsfkad?]"
    };
    if show_help {
        display_help_changes(potential_new_ignore, direction);
        print!(
            "Shall I {} this change? ({}/{}) ",
            direction.verb(),
            i + 1,
            n_changes
        );
    } else {
        print!(
            "Shall I {} this change? ({}/{}) {} ",
            direction.verb(),
            i + 1,
            n_changes,
            choices
        );
    }
    stdout().flush()?;
    match getch.getch().ok().and_then(|x| from_u32(x as u32)) {
        Some(e) => {
            println!("{}\n", e);
            let e = e.to_uppercase().next().unwrap_or('\0');
            match e {
                'A' => Ok(('Y', Some('Y'), None)),
                'D' => Ok(('N', Some('N'), None)),
                'F' => Ok(('Y', None, Some('Y'))),
                'S' => Ok(('N', None, Some('N'))),
                e => Ok((e, None, None)),
            }
        }
        _ => Ok(('\0', None, None)),
    }
}

fn add_to_ignore_file(
    file: &RepoPath<impl AsRef<Path>>,
    repo_root: &RepoRoot<impl AsRef<Path>>,
    new_ignored_patterns: &mut Vec<String>,
    new_ignore_builder: &mut GitignoreBuilder,
) {
    loop {
        let pat = read_line_with_suggestion(
            "Pattern to add to ignore file (relative to repository root, empty to add nothing)? ",
            &file.as_path().to_string_lossy(),
        );
        if pat.is_empty() {
            return;
        };

        let mut ignore_builder = GitignoreBuilder::new(&repo_root.repo_root);
        let add_ok = match ignore_builder.add_line(None, &pat) {
            Ok(i) => match i.build() {
                Ok(i) => i
                    .matched_path_or_any_parents(file.as_path(), false)
                    .is_ignore(),
                Err(e) => {
                    println!("could not match pattern {}: {}", &pat, e);
                    false
                }
            },
            Err(e) => {
                println!("did not understand pattern {}: {}", &pat, e);
                false
            }
        };
        if add_ok {
            new_ignore_builder.add_line(None, &pat).unwrap();
            new_ignored_patterns.push(pat);
            return;
        }
        println!(
            "pattern {} is incorrect or does not match {}",
            pat,
            &file.display()
        );
    }
}

pub fn ask_changes<T: rand::Rng>(
    repository: &MutTxn<T>,
    repo_root: &RepoRoot<impl AsRef<Path>>,
    cwd: &Path,
    changes: &[Record<ChangeContext<Hash>>],
    direction: ChangesDirection,
    to_unadd: &mut HashSet<RepoPath<PathBuf>>,
) -> Result<(HashMap<usize, bool>, Vec<String>), Error> {
    debug!("changes: {:?}", changes);
    let mut terminal = if stdout_isatty() {
    let mut terminal = if atty::is(atty::Stream::Stdout) {
        term::stdout()
    } else {
        None
    };
    let getch = getch::Getch::new();
    let mut i = 0;
    let mut choices: HashMap<usize, bool> = HashMap::new();
    let mut new_ignored_patterns: Vec<String> = Vec::new();
    let mut new_ignore_builder = GitignoreBuilder::new(&repo_root.repo_root);
    let mut final_decision = None;
    // determines what decision to make on remaining change in the same file
    let mut file_decision: Option<char> = None;
    let mut provided_by = HashMap::new();
    let mut line_deps = Vec::with_capacity(changes.len());
    for i in 0..changes.len() {
        line_deps.push(change_deps(i, &changes[i], &mut provided_by));
    }
    let mut deps: HashMap<usize, Vec<usize>> = HashMap::new();
    let mut rev_deps: HashMap<usize, Vec<usize>> = HashMap::new();
    for i in 0..changes.len() {
        for dep in line_deps[i].iter() {
            debug!("provided: i {}, dep {:?}", i, dep);
            let p = provided_by.get(dep).unwrap();
            debug!("provided: p= {}", p);

            let e = deps.entry(i).or_insert(Vec::new());
            e.push(*p);

            let e = rev_deps.entry(*p).or_insert(Vec::new());
            e.push(i);
        }
    }

    let empty_deps = Vec::new();
    let mut current_file = None;
    let mut show_help = false;

    while i < changes.len() {
        let decision=
            // If one of our dependencies has been unselected (with "n")
            if deps.get(&i)
            .unwrap_or(&empty_deps)
            .iter()
            .any(|x| { ! *(choices.get(x).unwrap_or(&true)) }) {
                Some(false)
            } else if rev_deps.get(&i).unwrap_or(&empty_deps)
            .iter().any(|x| { *(choices.get(x).unwrap_or(&false)) }) {
                // If we are a dependency of someone selected (with "y").
                Some(true)
            } else {
                None
            };

        let decision = match changes[i] {
            Record::FileAdd { ref name, .. } => {
                let i = new_ignore_builder.build().unwrap();
                if i.matched_path_or_any_parents(name.as_path(), false)
                    .is_ignore()
                {
                    Some(false)
                } else {
                    None
                }
            }
            _ => decision,
        };
        let potential_new_ignore: Option<&RepoPath<PathBuf>> = match direction {
            ChangesDirection::Revert => None,
            ChangesDirection::Record => match changes[i] {
                Record::FileAdd { ref name, .. } => Some(&name),
                _ => None,
            },
        };
        let (e, f, file_d) = match decision {
            Some(true) => ('Y', final_decision, file_decision),
            Some(false) => ('N', final_decision, file_decision),
            None => {
                if let Some(d) = final_decision {
                    (d, Some(d), file_decision)
                } else {
                    let command_decisions = if let Some(ref f) = current_file {
                        file_decision.and_then(|d| match changes[i] {
                            Record::Change { ref file, .. } => {
                                if f == file {
                                    Some((d, final_decision, Some(d)))
                                } else {
                                    None
                                }
                            }
                            _ => None,
                        })
                    } else {
                        None
                    };

                    if let Some(res) = command_decisions {
                        res
                    } else {
                        prompt_one_change(
                            repository,
                            repo_root,
                            &changes[i],
                            &mut current_file,
                            changes.len(),
                            i,
                            direction,
                            potential_new_ignore,
                            &mut terminal,
                            &getch,
                            cwd,
                            show_help,
                        )?
                    }
                }
            }
        };

        show_help = false;

        final_decision = f;
        file_decision = file_d;
        match e {
            'Y' => {
                choices.insert(i, direction.is_record());
                match changes[i] {
                    Record::FileAdd { ref name, .. } => {
                        to_unadd.remove(&name);
                    }
                    _ => (),
                }
                i += 1
            }
            'N' => {
                choices.insert(i, !direction.is_record());
                i += 1
            }
            'K' if i > 0 => {
                choices.remove(&i);
                i -= 1
            }
            'I' => match potential_new_ignore {
                Some(file) => {
                    add_to_ignore_file(
                        file,
                        repo_root,
                        &mut new_ignored_patterns,
                        &mut new_ignore_builder,
                    );
                    choices.insert(i, !direction.is_record());
                    i += 1;
                }
                _ => {}
            },
            '?' => {
                show_help = true;
            }
            _ => {}
        }
    }
    Ok((choices, new_ignored_patterns))
}

fn read_line(s: &str) -> String {
    print!("{}", s);
    if let Some(mut term) = line::Terminal::new() {
        term.read_line().unwrap()
    } else {
        let stdin = std::io::stdin();
        let mut stdin = stdin.lock().lines();
        if let Some(Ok(x)) = stdin.next() {
            x
        } else {
            String::new()
        }
    }
}

pub fn read_line_with_suggestion(prompt: &str, _suggestion: &str) -> String {
    read_line(prompt)
}

pub fn ask_authors() -> Result<Vec<String>, Error> {
    std::io::stdout().flush()?;
    Ok(vec![read_line("What is your name <and email address>? ")])
}

pub fn ask_patch_name(
    repo_root: &RepoRoot<impl AsRef<Path>>,
    maybe_editor: Option<&String>,
    template: String,
) -> Result<(String, Option<String>), Error> {
    let repo_root = repo_root.repo_root.as_ref();
    if let Some(editor) = maybe_editor {
        let mut patch_name_file = repo_root.to_path_buf();
        patch_name_file.push(PIJUL_DIR_NAME);
        patch_name_file.push("PATCH_NAME");

        debug!("patch name file: {:?}", patch_name_file);

        // Initialize the PATCH_NAME file with the template given as argument of
        // this function. `File::create` truncate the file if it already exists.
        // FIXME: should we ask users if they want to use the previous content
        // instead?
        let _ =
            File::create(patch_name_file.as_path())?.write_all(template.into_bytes().as_slice())?;

        let mut editor_cmd = editor
            .trim()
            .split(" ")
            .map(OsString::from)
            .collect::<Vec<_>>();

        editor_cmd.push(patch_name_file.clone().into_os_string());

        process::Command::new(&editor_cmd[0])
            .args(&editor_cmd[1..])
            .current_dir(repo_root)
            .status()
            .map_err(|e| Error::CannotSpawnEditor {
                editor: editor.to_owned(),
                cause: e.to_string(),
            })?;
        // if we are here, it means the editor must have stopped and we can read
        // the content of PATCH_NAME.

        // in case of error, we consider it is because the file has not been
        // created and we consider it as empty
        let mut patch_name =
            File::open(patch_name_file.as_path()).map_err(|_| Error::EmptyPatchName)?;
        let mut patch_name_content = String::new();
        patch_name.read_to_string(&mut patch_name_content)?;

        // we are done with PATCH_NAME, so delete it
        remove_file(patch_name_file)?;

        // Now, we parse the file. About `(?s:.)`, it is the syntax of the regex
        // crate for `.` to also match `\n`. So `.(?s:.)` means we want at least
        // one character that is not a newline, then the rest.
        let re_with_desc = Regex::new(r"^([^\n]+)\n\s*(.(?s:.)*)$").unwrap();
        let re_without_desc = Regex::new(r"^([^\n]+)\s*$").unwrap();

        if let Some(capt) = re_without_desc.captures(patch_name_content.as_ref()) {
            debug!("patch name without description");
            if capt[1].chars().any(|x| x == '\n' || x == '\r') {
                return Err(Error::InvalidPatchName);
            }
            Ok((String::from(&capt[1]), None))
        } else if let Some(capt) = re_with_desc.captures(patch_name_content.as_ref()) {
            debug!("patch name with description");

            // In the description, we ignore the line starting with `#`, and we
            // remove trailing and leading space.  The `map()` call is necessary
            // because `lines()` elements does not contain the newline
            // character, therefore `collect` returns a String with a single
            // line.
            //
            // Note that, in the current implementation, it remains possible to
            // start the patch name with `#`.
            let descr: String = capt[2]
                .lines()
                .filter(|l| !l.starts_with("#"))
                .map(|x| format!("{}\n", x))
                .collect::<String>()
                .trim()
                .into();

            // If, once cleaned up, the description is empty, then we prefer
            // using `None` rather than `Some("")`.
            if descr.is_empty() {
                Ok((String::from(&capt[1]), None))
            } else {
                Ok((String::from(&capt[1]), Some(String::from(descr.trim()))))
            }
        } else {
            debug!("couldn't get a valid patch name");
            debug!("the content was:");
            debug!("=======================");
            debug!("{}", patch_name_content);
            debug!("=======================");
            Err(Error::EmptyPatchName)
        }
    } else {
        std::io::stdout().flush()?;

        let res = read_line("What is the name of this patch? ");
        debug!("res = {:?}", res);
        if res.trim().is_empty() {
            Err(Error::EmptyPatchName)
        } else {
            Ok((res, None))
        }
    }
}

pub fn ask_learn_ssh(host: &str, port: u16, fingerprint: &str) -> Result<bool, Error> {
    std::io::stdout().flush()?;
    print!(
        "The authenticity of host {:?}:{} cannot be established.\nThe fingerprint is {:?}.",
        host, port, fingerprint
    );

    let input = read_line("Are you sure you want to continue (yes/no)? ");
    let input = input.trim().to_uppercase();
    Ok(input == "YES")
}

pub fn print_status<T: rand::Rng>(
    repo_root: &RepoRoot<impl AsRef<Path>>,
    repository: &MutTxn<T>,
    cwd: &Path,
    changes: &[Record<ChangeContext<Hash>>],
) -> Result<(), Error> {
    debug!("changes: {:?}", changes);
    let mut terminal = if stdout_isatty() {
    let mut terminal = if atty::is(atty::Stream::Stdout) {
        term::stdout()
59
60

61

62
63


66


69
70

72
73
                if recursive {
                    debug!("adding from {:?}", p);
                    for file in repo_dir.untracked_files(&txn, &p) {
                    let mut files = Vec::new();
                    txn.with_untracked_files(r, &p, |file| {
                    for file in repo_dir.untracked_files(&txn, &p) {
                        debug!("untracked {:?}", file);

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
                        if let Ok(file) = file.strip_prefix(r) {

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

================================
                        let m = metadata(repo_dir.absolutize(&file))?;
                        files.push((file, m.is_dir()));

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
                    }
                    for (file, is_dir) in files {


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

use atty;
                let mut terminal = if atty::is(atty::Stream::Stdout) {
use super::validate_base58;
use atty;
use clap::{Arg, ArgGroup, ArgMatches, SubCommand};
use commands::{default_explain, BasicOptions, StaticSubcommand};
use error::Error;
use libpijul;
use libpijul::graph::LineBuffer;
use libpijul::patch::{Change, NewEdge, Patch};
use libpijul::{Branch, EdgeFlags, Hash, Key, LineId, PatchId, Transaction, Txn, Value, ROOT_KEY};
use std::cmp::max;
use std::collections::{HashMap, HashSet};
use std::fs::File;
use std::io::{copy, stdout, BufReader};
use std::str::from_utf8;
use term;
use term::StdoutTerminal;

pub fn invocation() -> StaticSubcommand {
    SubCommand::with_name("patch")
        .about("Output a patch")
        .arg(
            Arg::with_name("repository")
                .long("repository")
                .help("Path to the repository where the patches will be applied.")
                .takes_value(true),
        )
        .arg(
            Arg::with_name("patch")
                .help("The hash of the patch to be printed.")
                .takes_value(true)
                .required(true)
                .validator(validate_base58),
        )
        .arg(
            Arg::with_name("bin")
                .long("bin")
                .help("Output the patch in binary."),
        )
        .arg(
            Arg::with_name("name")
                .long("name")
                .help("Output the patch name."),
        )
        .arg(
            Arg::with_name("description")
                .long("description")
                .help("Output the patch description."),
        )
        .arg(
            Arg::with_name("authors")
                .long("authors")
                .help("Output the patch authors."),
        )
        .arg(
            Arg::with_name("date")
                .long("date")
                .help("Output the patch date."),
        )
        .group(ArgGroup::with_name("details").required(false).args(&[
            "bin",
            "name",
            "description",
            "date",
            "authors",
        ]))
}

#[derive(PartialEq, Eq)]
enum View {
    Normal,
    Bin,
    NameOnly,
    DescrOnly,
    DateOnly,
    AuthorsOnly,
}

pub fn run(args: &ArgMatches) -> Result<(), Error> {
    let opts = BasicOptions::from_args(args)?;
    let patch = Hash::from_base58(args.value_of("patch").unwrap()).unwrap();
    let mut patch_path = opts.repo_root.patches_dir().join(&patch.to_base58());
    patch_path.set_extension("gz");
    let mut f = File::open(&patch_path)?;

    let v: View = match (
        args.is_present("bin"),
        args.is_present("name"),
        args.is_present("description"),
        args.is_present("date"),
        args.is_present("authors"),
    ) {
        (true, _, _, _, _) => View::Bin,
        (_, true, _, _, _) => View::NameOnly,
        (_, _, true, _, _) => View::DescrOnly,
        (_, _, _, true, _) => View::DateOnly,
        (_, _, _, _, true) => View::AuthorsOnly,
        (_, _, _, _, _) => View::Normal,
    };

    if v == View::Bin {
        let mut stdout = stdout();
        copy(&mut f, &mut stdout)?;
    } else {
        // Write the patch in text.
        let mut f = BufReader::new(f);
        let (hash, _, patch) = Patch::from_reader_compressed(&mut f)?;

        match v {
            View::AuthorsOnly => print!("{:?}", patch.authors),
            View::DescrOnly => print!("{}", patch.description.clone().unwrap_or("".into())),
            View::DateOnly => print!("{:?}", patch.timestamp),
            View::NameOnly => print!("{}", patch.name),
            _ => {
                // it cannot be View::Bin, so it has to be View::Normal
                let repo = opts.open_repo()?;
                let branch_name = opts.branch();
                let txn = repo.txn_begin()?;
                let branch = txn.get_branch(&branch_name).expect("Branch not found");
                print_patch(&hash, &patch, &txn, &branch)?
            }
        }
    }
    Ok(())
}

pub fn print_patch(hash: &Hash, patch: &Patch, txn: &Txn, branch: &Branch) -> Result<(), Error> {
    let internal = txn
        .get_internal(hash.as_ref())
        .expect("Patch not in repository")
        .to_owned();

                let mut terminal = if stdout_isatty() {


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
    /*
     */
use clap::{Arg, ArgMatches, SubCommand};

use commands::{default_explain, BasicOptions, StaticSubcommand};
use error::Error;
use std::fs::File;
use std::path::Path;

use commands::ask::{ask_patches, Command};
use commands::remote;
use libpijul::fs_representation::{RepoPath, RepoRoot};
use libpijul::patch::Patch;
use libpijul::{ApplyTimestamp, Hash, PatchId, DEFAULT_BRANCH};
use meta::{Meta, Repository, DEFAULT_REMOTE};
use progrs;
use rand;
use std::env::current_dir;
use std::io::BufReader;

pub fn invocation() -> StaticSubcommand {
    return SubCommand::with_name("pull")
        .about("Pull from a remote repository")
        .arg(
            Arg::with_name("repository")
                .long("repository")
                .help("Repository to list.")
                .takes_value(true),
        )
        .arg(Arg::with_name("remote").help("Repository from which to pull."))
        .arg(
            Arg::with_name("remote_branch")
                .long("from-branch")
                .help("The branch to pull from. Defaults to master.")
                .takes_value(true),
        )
        .arg(
            Arg::with_name("local_branch")
                .long("to-branch")
                .help("The branch to pull into. Defaults to the current branch.")
                .takes_value(true),
        )
        .arg(
            Arg::with_name("all")
                .short("a")
                .long("all")
                .help("Answer 'y' to all questions")
                .takes_value(false),
        )
        .arg(
            Arg::with_name("set-default")
                .long("set-default")
                .help("Used with --set-remote, sets this remote as the default pull remote."),
        )
        .arg(
            Arg::with_name("set-remote")
                .long("set-remote")
                .help("Name this remote destination.")
                .takes_value(true),
        )
        .arg(
            Arg::with_name("remote_path")
                .long("path")
                .help("Only pull patches affecting the part of the repo under that path (relative to the root of the repo).")
                .help("Only pull patches relative to that patch.")
                .takes_value(true),
        )
        .arg(
            Arg::with_name("port")
                .short("p")
                .long("port")
                .help("Port of the remote ssh server.")
                .takes_value(true)
                .validator(|val| {
                    let x: Result<u16, _> = val.parse();
                    match x {
                        Ok(_) => Ok(()),
                        Err(_) => Err(val),
                    }
                }),
        );
}

#[derive(Debug)]
pub struct Params<'a> {
    pub remote_id: Option<&'a str>,
    pub set_remote: Option<&'a str>,
    pub yes_to_all: bool,
    pub set_default: bool,
    pub port: Option<u16>,
    pub local_branch: Option<&'a str>,
    pub remote_branch: &'a str,
    pub remote_paths: Vec<RepoPath<&'a Path>>,
}

fn parse_args<'a>(args: &'a ArgMatches) -> Params<'a> {
    Params {
        remote_id: args.value_of("remote"),
        set_remote: args.value_of("set-remote"),
        yes_to_all: args.is_present("all"),
        set_default: args.is_present("set-default"),
        port: args.value_of("port").and_then(|x| Some(x.parse().unwrap())),
        local_branch: args.value_of("local_branch"),
        remote_branch: args.value_of("remote_branch").unwrap_or(DEFAULT_BRANCH),
        remote_paths: if let Some(rem) = args.values_of("remote_path") {
            rem.map(|p| RepoPath(Path::new(p))).collect()
        } else {
            Vec::new()
        },
    }
}

fn fetch_pullable_patches(
    session: &mut remote::Session,
    pullable: &[(Hash, ApplyTimestamp)],
    r: &RepoRoot<impl AsRef<Path>>,
) -> Result<Vec<(Hash, Option<PatchId>, Patch)>, Error> {
    let mut patches = Vec::new();

    let (mut p, mut n) = (progrs::start("Pulling patches", pullable.len() as u64), 0);
    for &(ref i, _) in pullable {
        let (hash, _, patch) = {
            let filename = session.download_patch(r, i)?;
            debug!("filename {:?}", filename);
            let file = File::open(&filename)?;
            let mut file = BufReader::new(file);
            Patch::from_reader_compressed(&mut file)?
        };
        p.display({
            n += 1;
            n
        });
        assert_eq!(&hash, i);
        patches.push((hash, None, patch));
    }
    p.stop("done");
    Ok(patches)
}

pub fn select_patches(
    interactive: bool,
    session: &mut remote::Session,
    remote_branch: &str,
    local_branch: &str,
    r: &RepoRoot<impl AsRef<Path>>,
    remote_paths: &[RepoPath<&Path>],
) -> Result<Vec<(Hash, ApplyTimestamp)>, Error> {
    let pullable = session.pullable_patches(remote_branch, local_branch, r, remote_paths)?;
    let mut pullable: Vec<_> = pullable.iter().collect();
    pullable.sort_by(|&(_, a), &(_, b)| a.cmp(&b));
    if interactive && !pullable.is_empty() {
        let selected = {
            let patches = fetch_pullable_patches(session, &pullable, r)?;
            ask_patches(Command::Pull, &patches[..])?
        };
        Ok(pullable
            .into_iter()
            .filter(|&(ref h, _)| selected.contains(h))
            .collect())
    } else {
        Ok(pullable)
    }
}

pub fn run(arg_matches: &ArgMatches) -> Result<(), Error> {
    let opts = BasicOptions::from_args(arg_matches)?;
    let args = parse_args(arg_matches);
    debug!("pull args {:?}", args);
    let mut meta = Meta::load(&opts.repo_root).unwrap_or(Meta::new());
    let cwd = current_dir()?;
    let local_branch = if let Some(b) = args.local_branch {
        b.to_string()
    } else {
        opts.branch()
    };
    let repo_root = opts.repo_root();
    let conflicts = {
        let remote = meta.pull(args.remote_id, args.port, Some(&cwd), Some(&repo_root))?;
        let mut session = remote.session()?;
        let mut pullable = select_patches(
            !args.yes_to_all,
            &mut session,
            args.remote_branch,
            &local_branch,
            &opts.repo_root,
            &args.remote_paths,
        )?;

        // Pulling and applying
        info!("Pulling patch {:?}", pullable);
        if !pullable.is_empty() {
            session.pull(
                &opts.repo_root,
                &local_branch,
                &mut pullable,
                &args.remote_paths,
                false,
            )?
        } else {
            println!("No new patches to pull.");
            Vec::new()
        }
    };
    info!("Saving meta");
    let set_remote = if args.set_default && args.set_remote.is_none() {
        Some(DEFAULT_REMOTE)
    } else {
        args.set_remote
    };
    if let (Some(set_remote), Some(remote_id)) = (set_remote, args.remote_id) {
        let mut repo = Repository::default();
        repo.address = remote_id.to_string();
        repo.port = args.port;

        meta.remote.insert(set_remote.to_string(), repo);
        if args.set_default {
            meta.pull = Some(set_remote.to_string());
        }
        meta.save(&opts.repo_root)?;
    }
    let repo = opts.open_repo()?;
    let mut txn = repo.mut_txn_begin(rand::thread_rng())?;
    let conflicts = txn.list_conflict_files(&local_branch, &args.remote_paths)?;
    // Conflicts must be returned by session.pull above. It is feasible.
    if !conflicts.is_empty() {
        println!("There are pending conflicts waiting to be solved:");
        for f in conflicts {
            println!("    {}", f.path.display());
        }
    }

    Ok(())



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


108


111


114

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

526
527
528











529
530
531
532
533
534
535
536
537
538
539
540
541
use std::fs::{metadata, OpenOptions};
use std::io::Write;
        metadata(&file)?;
use super::ask::{ask_changes, ChangesDirection};
use super::default_explain;
use chrono;
use clap::{Arg, ArgMatches, SubCommand};
use commands::hooks::run_hook;
use commands::{ask, BasicOptions, StaticSubcommand};
use error::Error;
use libpijul;
use libpijul::fs_representation::{ignore_file, patches_dir};
use libpijul::fs_representation::{in_repo_root, RepoPath, RepoRoot};
use libpijul::patch::{PatchFlags, Record};
use libpijul::{Hash, InodeUpdate, Key, MutTxn, Patch, PatchId, RecordState, Repository};
use meta::{load_signing_key, Global, Meta};
use rand;
use std::collections::HashSet;
use std::fs::canonicalize;
use std::fs::OpenOptions;
use std::io::Write;
use std::io::Write;
use std::io::Write;
use std::fs::{metadata, OpenOptions};
use std::io::Write;
use std::mem::drop;
use std::path::{Path, PathBuf};
use std::str::FromStr;

pub fn record_args(sub: StaticSubcommand) -> StaticSubcommand {
    sub.arg(Arg::with_name("repository")
            .long("repository")
            .help("The repository where to record, defaults to the current directory.")
            .takes_value(true)
            .required(false))
        .arg(Arg::with_name("branch")
             .long("branch")
             .help("The branch where to record, defaults to the current branch.")
             .takes_value(true)
             .required(false))
        .arg(Arg::with_name("date")
             .long("date")
             .help("The date to use to record the patch, default is now.")
             .takes_value(true)
             .required(false))
        .arg(Arg::with_name("message")
             .short("m")
             .long("message")
             .help("The name of the patch to record")
             .takes_value(true))
        .arg(Arg::with_name("description")
             .short("d")
             .long("description")
             .help("The description of the patch to record")
             .takes_value(true))
        .arg(Arg::with_name("no-editor")
             .long("no-editor")
             .help("Do not use an editor to write the patch name and description, even if the variable is set in the configuration file")
             .takes_value(false))
        .arg(Arg::with_name("author")
             .short("A")
             .long("author")
             .help("Author of this patch (multiple occurrences allowed)")
             .takes_value(true))
        .arg(Arg::with_name("patience")
             .long("patience")
             .help("Use patience diff instead of the default (Myers diff)")
             .conflicts_with("myers")
             .takes_value(false))
        .arg(Arg::with_name("myers")
             .long("myers")
             .help("Use Myers diff")
             .conflicts_with("patience")
             .takes_value(false))
}

pub fn invocation() -> StaticSubcommand {
    return record_args(
        SubCommand::with_name("record")
            .about("Record changes in the repository")
            .arg(
                Arg::with_name("all")
                    .short("a")
                    .long("all")
                    .help("Answer 'y' to all questions")
                    .takes_value(false),
            )
            .arg(
                Arg::with_name("add-new-files")
                    .short("n")
                    .long("add-new-files")
                    .help("Offer to add files that have been created since the last record")
                    .takes_value(false),
            )
            .arg(
                Arg::with_name("depends-on")
                    .help("Add a dependency to this patch (internal id or hash accepted)")
                    .long("depends-on")
                    .takes_value(true)
                    .multiple(true),
            )
            .arg(
                Arg::with_name("prefix")
                    .help("Prefix to start from")
                    .takes_value(true)
                    .multiple(true),
            ),
    );
}

fn add_untracked_files<T: rand::Rng, P: AsRef<Path> + 'static>(
    txn: &mut MutTxn<T>,
    repo_root: &RepoRoot<P>,

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        if let Err(e) = txn.add_file(&file, m.is_dir()) {

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        }

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    }

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    Ok(untracked)
}

fn append_to_ignore_file(
    repo_root: &RepoRoot<impl AsRef<Path>>,
    lines: &Vec<String>,
) -> Result<(), Error> {
    let ignore_file = repo_root.local_ignore_file();
    let mut file = OpenOptions::new()
        .append(true)
        .create(true)
        .open(ignore_file)?;
    for line in lines {
        file.write_all(line.as_ref())?;
        file.write_all(b"\n")?
    }
    Ok(())
}

fn select_changes(
    algo: libpijul::DiffAlgorithm,
    opts: &BasicOptions,
    add_new_files: bool,
    branch_name: &str,
    yes_to_all: bool,
    prefix: Option<Vec<RepoPath<PathBuf>>>,
) -> Result<(Vec<Record<Vec<Key<Option<Hash>>>>>, HashSet<InodeUpdate>), Error> {
    // Increase by 100 pages. The most things record can write is one
    // write in the branches table, affecting at most O(log n) blocks.
    let repo = opts.open_and_grow_repo(409600)?;
    let mut txn = repo.mut_txn_begin(rand::thread_rng())?;
    let mut to_unadd = if add_new_files {
        add_untracked_files(&mut txn, &opts.repo_root)?
    } else {
        HashSet::new()
    };
    let (changes, syncs) = changes_from_prefixes(
        algo,
        &opts.repo_root,
        &mut txn,
        &branch_name,
        prefix.as_ref(),
    )?;
    let changes: Vec<_> = changes
        .into_iter()
        .map(|x| txn.globalize_record(x))
        .collect();
    if !yes_to_all {
        let (c, i) = ask_changes(
            &txn,
            &opts.repo_root,
            &opts.cwd,
            &changes,
            ChangesDirection::Record,
            &mut to_unadd,
        )?;
        let selected = changes
            .into_iter()
            .enumerate()
            .filter(|&(i, _)| *(c.get(&i).unwrap_or(&false)))
            .map(|(_, x)| x)
            .collect();
        for file in to_unadd {
            txn.remove_file(&file)?
        }
        txn.commit()?;
        append_to_ignore_file(&opts.repo_root, &i)?;
        Ok((selected, syncs))
    } else {
        txn.commit()?;
        Ok((changes, syncs))
    }
}

pub fn run(args: &ArgMatches) -> Result<Option<Hash>, Error> {
    let opts = BasicOptions::from_args(args)?;
    let yes_to_all = args.is_present("all");
    let patch_name_arg = args.value_of("message");
    let patch_descr_arg = args.value_of("description");
    let authors_arg = args.values_of("author").map(|x| x.collect::<Vec<_>>());
    let branch_name = opts.branch();
    let add_new_files = args.is_present("add-new-files");

    let patch_date = args.value_of("date").map_or(Ok(chrono::Utc::now()), |x| {
        chrono::DateTime::from_str(x).map_err(|_| Error::InvalidDate {
            date: String::from(x),
        })
    })?;

    let mut save_meta = false;

    let (mut global, save_global) = Global::load().map(|c| (c, false)).unwrap_or_else(|e| {
        info!("loading global key, error {:?}", e);
        (Global::new(), true)
    });

    let mut meta = match Meta::load(&opts.repo_root) {
        Ok(m) => m,
        Err(_) => {
            save_meta = true;
            Meta::new()
        }
    };

    run_hook(&opts.repo_root, "pre-record", None)?;

    debug!("prefix {:?}", args.value_of("prefix"));
    let prefix = prefix(args, &opts)?;

    let (changes, syncs) = select_changes(
        if args.is_present("patience") {
            libpijul::DiffAlgorithm::Patience
        } else {
            libpijul::DiffAlgorithm::Myers
        },
        &opts,
        add_new_files,
        &branch_name,
        yes_to_all,
        prefix,
    )?;

    if changes.is_empty() {
        println!("Nothing to record");
        Ok(None)
    } else {
        let template = prepare_changes_template(patch_name_arg.unwrap_or(""), &changes);

        let repo = opts.open_repo()?;
        let patch = {
            let txn = repo.txn_begin()?;
            debug!("meta:{:?}", meta);

            let authors = decide_authors(authors_arg, &meta, &global)?;

            if authors.is_empty() {
                return Err(Error::NoAuthor);
            }

            if meta.authors.is_empty() {
                meta.authors = authors.clone();
                save_meta = true;
            }

            if global.author.is_none() {
                global.author = Some(authors[0].clone());
            }

            debug!("authors:{:?}", authors);

            let (patch_name, description) = decide_patch_message(
                patch_name_arg,
                patch_descr_arg,
                template,
                !args.is_present("no-editor"),
                &opts.repo_root,
                &meta,
                &global,
            )?;

            run_hook(&opts.repo_root, "patch-name", Some(&patch_name))?;

            debug!("patch_name:{:?}", patch_name);
            if save_meta {
                meta.save(&opts.repo_root)?
            }
            if save_global {
                global.save().unwrap_or(())
            }
            debug!("new");
            let changes = changes.into_iter().flat_map(|x| x.into_iter()).collect();
            let branch = txn.get_branch(&branch_name).unwrap();

            let mut extra_deps = Vec::new();
            if let Some(deps) = args.values_of("depends-on") {
                for dep in deps {
                    if let Some(hash) = Hash::from_base58(dep) {
                        if let Some(internal) = txn.get_internal(hash.as_ref()) {
                            if txn.get_patch(&branch.patches, internal).is_some() {
                                extra_deps.push(hash)
                            } else {
                                return Err(Error::ExtraDepNotOnBranch { hash });
                            }
                        } else {
                            return Err(Error::PatchNotFound {
                                repo_root: opts.repo_root().to_string_lossy().into_owned(),
                                patch_hash: hash,
                            });
                        }
                    } else if let Some(internal) = PatchId::from_base58(dep) {
                        if let Some(hash) = txn.get_external(internal) {
                            if txn.get_patch(&branch.patches, internal).is_some() {
                                extra_deps.push(hash.to_owned())
                            } else {
                                return Err(Error::ExtraDepNotOnBranch {
                                    hash: hash.to_owned(),
                                });
                            }
                        }
                    } else {
                        return Err(Error::WrongHash);
                    }
                }
            }
            txn.new_patch(
                &branch,
                authors,
                patch_name,
                description,
                patch_date,
                changes,
                extra_deps.into_iter(),
                PatchFlags::empty(),
            )
        };
        drop(repo);

        let patches_dir = opts.repo_root.patches_dir();
        let mut key = meta
            .signing_key
            .or(global.signing_key)
            .and_then(|s| load_signing_key(s).ok());
        let hash = if let Some(ref mut key) = key {
            key.check_author(&patch.header().authors)?;
            patch.save(&patches_dir, key.keys.get_mut(0))?
        } else {
            patch.save(&patches_dir, None)?
        };

        let pristine_dir = opts.pristine_dir();
        let mut increase = 409600;
        let res = loop {
            match record_no_resize(
                &pristine_dir,
                &opts.repo_root,
                &branch_name,
                &hash,
                &patch,
                &syncs,
                increase,
            ) {
                Err(ref e) if e.lacks_space() => increase *= 2,
                e => break e,
            }
        };

        run_hook(&opts.repo_root, "post-record", None)?;

        res
    }
}

pub fn record_no_resize(
    pristine_dir: &Path,
    r: &RepoRoot<impl AsRef<Path>>,
    branch_name: &str,
    hash: &Hash,
    patch: &Patch,
    syncs: &HashSet<InodeUpdate>,
    increase: u64,
) -> Result<Option<Hash>, Error> {
    let size_increase = increase + patch.size_upper_bound() as u64;
    let repo = match Repository::open(&pristine_dir, Some(size_increase)) {
        Ok(repo) => repo,
        Err(x) => return Err(Error::Repository(x)),
    };
    let mut txn = repo.mut_txn_begin(rand::thread_rng())?;
    // save patch
    debug!("syncs: {:?}", syncs);
    let mut branch = txn.open_branch(branch_name)?;
    txn.apply_local_patch(&mut branch, r, &hash, &patch, &syncs, false)?;
    txn.commit_branch(branch)?;
    txn.commit()?;
    println!("Recorded patch {}", hash.to_base58());
    Ok(Some(hash.clone()))
}

pub fn explain(res: Result<Option<Hash>, Error>) {
    default_explain(res)
}

pub fn changes_from_prefixes<T: rand::Rng, P: AsRef<Path>>(
    algo: libpijul::DiffAlgorithm,
    repo_root: &RepoRoot<impl AsRef<Path>>,
    txn: &mut MutTxn<T>,
    branch_name: &str,
    prefix: Option<&Vec<RepoPath<P>>>,
) -> Result<
    (
        Vec<libpijul::patch::Record<libpijul::patch::ChangeContext<PatchId>>>,
        HashSet<libpijul::InodeUpdate>,
    ),
    Error,
> {
    let mut record = RecordState::new();
    let branch = txn.open_branch(branch_name)?;
    if let Some(prefixes) = prefix {
        for prefix in prefixes {
            txn.record(algo, &mut record, &branch, repo_root, prefix)?;
        }
    } else {
        txn.record(algo, &mut record, &branch, repo_root, &in_repo_root())?;
    }
    txn.commit_branch(branch)?;
    let (changes, updates) = record.finish();
    // let changes = changes.into_iter().map(|x| txn.globalize_change(x)).collect();
    Ok((changes, updates))
}

pub fn prefix(
    args: &ArgMatches,
    opts: &BasicOptions,
) -> Result<Option<Vec<RepoPath<PathBuf>>>, Error> {
    if let Some(prefixes) = args.values_of("prefix") {
        let prefixes: Result<Vec<_>, Error> = prefixes
            .map(|prefix| {
                let p = opts.cwd.join(prefix);
                let p = if let Ok(p) = canonicalize(&p) { p } else { p };
                let file = opts.repo_root.relativize(&p)?;
                Ok(file.to_owned())
            })
            .collect();
        Ok(Some(prefixes?))
    } else {
        Ok(None)
    }
}

pub fn decide_authors(
    authors_args: Option<Vec<&str>>,
    meta: &Meta,
    global: &Global,
) -> Result<Vec<String>, Error> {
    Ok(match authors_args {
        Some(authors) => authors.iter().map(|x| x.to_string()).collect(),
        _ => {
            if meta.authors.len() > 0 {
                meta.authors.clone()
            } else if let Some(ref auth) = global.author {
                vec![auth.clone()]
            } else {
                ask::ask_authors()?
            }
        }
    })
}

pub fn decide_patch_message(
    name_arg: Option<&str>,
    descr_arg: Option<&str>,
    template: String,
    use_editor: bool,
    repo_root: &RepoRoot<impl AsRef<Path>>,
    meta: &Meta,
    global: &Global,
) -> Result<(String, Option<String>), Error> {
    Ok(match name_arg {
        Some(m) => (m.to_string(), descr_arg.map(|x| String::from(x.trim()))),
        _ => {
            let maybe_editor = if use_editor {
                if meta.editor.is_some() {
                    meta.editor.as_ref()
                } else {
                    global.editor.as_ref()
                }
            } else {
                None
            };

            ask::ask_patch_name(repo_root, maybe_editor, template)?
        }
    })
}

fn prepare_changes_template(descr: &str, changes: &[Record<Vec<Key<Option<Hash>>>>]) -> String {
    let mut res = format!(
        r#"
{}
# Please enter a patch title, and consider writing a description too. Lines
# starting with '#' will be ignored. Besides, an empty patch title aborts the
# patch recording.
#
# Here is a summary of the changes you are about to record:
#"#,
        descr
    );
    let mut known_files = Vec::new();
    for change in changes.iter() {
        match *change {
            Record::Change { ref file, .. } => {
                if !known_files.contains(&file) {
                    res = format!("{}\n#\tmodified:  {}", res, file.display());
                    known_files.push(file);
                }
            }
            Record::FileAdd { ref name, .. } => {
                res = format!("{}\n#\tnew file:  {}", res, name.display());
            }
            Record::FileDel { ref name, .. } => {
                res = format!("{}\n#\tdeleted:  {}", res, name.display());
            }
            Record::FileMove { ref new_name, .. } => {
                res = format!("{}\n#\t   moved:  to {}", res, new_name.display());
            }
        }
    }

    return res;
}

================================
) -> Result<HashSet<RepoPath<PathBuf>>, Error> {
    let mut untracked = HashSet::new();
    for file in repo_root.untracked_files(txn, &repo_root.repo_root) {
        let m = metadata(&file)?;
        let file = file.strip_prefix(&repo_root.repo_root)?;
    txn.with_untracked_files(repo_root, repo_root, |file| {
        let file = file.strip_prefix(&repo_root)?;
        let file = file.strip_prefix(&repo_root)?;
        if let Err(e) = txn.add_file(&file, m.is_dir()) {
        if let Err(e) = txn.add_file(&file, m.is_dir()) {
        untracked.insert(file.to_path_buf());
        let result: Result<bool, Error> = Ok(true);
        result
    })?;
        debug!("untracked: {:?}", file);
        untracked.insert(file);
    }
    for file in untracked.iter() {
        let metadata = metadata(repo_root.absolutize(&file))?;
        // Because we're using a HashSet and not a Vec, our untracked
        // paths are in a random order, and hence add_inode of a long
        // path might add the components of prefixes of that path.
        match txn.add_inode(None, file, metadata.is_dir()) {
            Ok(()) | Err(libpijul::Error::AlreadyAdded) => {}
            Err(e) => return Err(e.into()),
        }
    }
1
2



3


6


9

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







use clap::{Arg, ArgMatches, SubCommand};
use commands::{default_explain, BasicOptions, StaticSubcommand};
use libpijul::fs_representation::untracked_files;
use libpijul::status::{ChangeType, unrecorded_changes};
use libpijul::status::{ChangeType, unrecorded_changes};
use error::Error;

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
use libpijul::fs_representation::RepoRoot;

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

================================
use libpijul::fs_representation::{RepoPath, RepoRoot};

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
use libpijul::status::{unrecorded_changes, ChangeType};
use rand;

use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::rc::Rc;

const UNRECORDED_FILES: &'static str = r#"
Changes not yet recorded:
  (use "pijul record ..." to record a new patch)
"#;

const UNTRACKED_FILES: &'static str = r#"
Untracked files:
  (use "pijul add <file>..." to track them)
"#;

const CONFLICTED_FILES: &'static str = r#"
Unresolved conflicts:
  (fix conflicts and record the resolution with "pijul record ...")
"#;

pub fn invocation() -> StaticSubcommand {
    SubCommand::with_name("status")
        .about("Show working tree status")
        .arg(
            Arg::with_name("repository")
                .long("repository")
                .takes_value(true)
                .help("Local repository."),
        )
        .arg(
            Arg::with_name("short")
                .long("short")
                .short("s")
                .help("Output in short format"),
        )
}

pub fn explain(r: Result<(), Error>) {
    default_explain(r)
}

pub fn run(args: &ArgMatches) -> Result<(), Error> {
    let opts = BasicOptions::from_args(args)?;
    let current_branch = opts.branch();
    let repo = opts.open_and_grow_repo(409600)?;
    let short = args.is_present("short");

    let (unrecorded, untracked, conflicts) = {
        let mut txn = repo.mut_txn_begin(rand::thread_rng())?;
        let unrecorded = unrecorded_changes(&mut txn, &opts.repo_root, &current_branch)?;

        let mut untracked = HashSet::new();
        txn.with_untracked_files(&opts.repo_root, &opts.repo_root, |file| {
            untracked.insert(file);
            let result: Result<bool, Error> = Ok(true);
            result
        })?;
        let untracked =
35
36

37
extern crate tempfile;

extern crate isatty;
extern crate atty;