pijul_org / pijul

Refactors in pijul::commands::diff and libpiul::status

By Florent Becker on May 23, 2019
This patch is not signed.
BEMpPpQbPbQegeYXqKYaqpN6ZKCxG6gSwtfZy4uJ2hcxQ5dWKFxcd7TNvHokYbroVrDhzLKqCeqyFj6y7PGEMTc3
This patch is in the following branches:
latest
master
testing

2

3
4
5
6
7
8
9
10
11


14


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

88


91



95


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

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
use super::{EdgeFlags, MutTxn};
use backend::{FileMetadata, PatchId, ROOT_PATCH_ID};
use backend::{PatchId, ROOT_PATCH_ID};
use fs_representation::{in_repo_root, RepoPath, RepoRoot};
use patch::{Change, ChangeContext, Record};
use record::RecordState;
use std::borrow::Cow;
use std::collections::hash_map::{Entry, HashMap};
use std::path::{Path, PathBuf};
use std::rc::Rc;
use Result;

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

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
use std::path::{PathBuf};

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

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

#[derive(Debug, PartialEq, Eq, Ord, PartialOrd)]
pub enum ChangeType {
    Modified,
    New,
    Del,
    Move {
        new_name: Rc<RepoPath<PathBuf>>,
        former_names: Vec<Vec<(FileMetadata, String)>>,
        former_names: Vec<RepoPath<PathBuf>>,
    },
}

impl ChangeType {
    pub fn short(&self) -> Cow<'static, str> {
        match *self {
            ChangeType::Modified => "M".into(),
            ChangeType::New => "A".into(),
            ChangeType::Del => "D".into(),
            ChangeType::Move {
                ref former_names, ..
            } => {
                let mut s = String::new();
                if former_names.len() == 1 {
                    for (i, (_, name)) in former_names[0].iter().enumerate() {
                        if i > 0 {
                            s.push_str("/");
                        }
                        s.push_str(name)
                    }
                    s.push_str(" →");
                    s.push_str(&format!("{} →", former_names[0].display()));
                } else if former_names.len() > 1 {
                    s.push_str("{ ");
                    for (k, former_names) in former_names.iter().enumerate() {
                    for (k, former_name) in former_names.iter().enumerate() {
                        if k > 0 {
                            s.push_str(", ");
                        }
                        for (i, (_, name)) in former_names.iter().enumerate() {
                            if i > 0 {
                                s.push_str("/");
                            }
                            s.push_str(name)
                        }
                        s.push_str(&former_name.display().to_string())
                    }
                    s.push_str(" } →");
                } else {
                    s.push_str("→");
                }
                s.into()
            }
        }
    }

    pub fn long(&self) -> &str {
    pub fn long(&self) ->  Cow<'static, str> {
        match *self {
            ChangeType::Modified => "modified:",
            ChangeType::New => "new file:",
            ChangeType::Del => "deleted:",
            ChangeType::Move { .. } => "moved:",
            ChangeType::Modified => "modified:".into(),
            ChangeType::New => "new file:".into(),
            ChangeType::Del => "deleted:".into(),
            ChangeType::Move { ref former_names, .. } => {
                let mut s = String::new();
                if former_names.len() == 1 {
                    s.push_str(&former_names[0].display().to_string())
                } else {
                    let n = former_names.len();
                    for (k, former_name) in former_names.iter().enumerate() {
                        if k > 0 {
                            s.push_str(", ");
                            if k == n - 1 {
                                s.push_str("and ")
                            }
                        }
                        s.push_str(&former_name.display().to_string())
                    }
                }
                format!("Moved: {} to", &s).into()
            }
        }
    }
}

pub fn unrecorded_changes<T: rand::Rng>(
    txn: &mut MutTxn<T>,

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    repo_root: &RepoRoot<impl AsRef<Path>>,

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

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    repo_root: &PathBuf,

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

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

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    repo_root: &Path,

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

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    branch: &String,
) -> Result<Vec<(Rc<RepoPath<PathBuf>>, ChangeType)>> {
    let mut record = RecordState::new();
    let branch = txn.open_branch(branch)?;
    txn.record(
        super::DiffAlgorithm::default(),
        &mut record,
        &branch,
        repo_root,
        &in_repo_root(),
    )?;
    let (changes, _) = record.finish();

    let mut ret = vec![];
    let mut current_file = None;

    for change in changes.iter() {
        match *change {
            Record::Change { ref file, .. } => {
                if current_file.clone().map_or(true, |f| &f != file) {
                    ret.push((file.clone(), ChangeType::Modified));
                    current_file = Some(file.clone());
                }
            }
            Record::FileAdd { ref name, .. } => {
                let file = Rc::new(name.clone());
                current_file = Some(file.clone());
                ret.push((file.clone(), ChangeType::New));
            }
            Record::FileDel { ref name, .. } => {
                let file = Rc::new(name.clone());
                current_file = Some(file.clone());
                ret.push((file.clone(), ChangeType::Del));
            }
            Record::FileMove {
                ref new_name,
                ref del,
                ..
            } => {
                let former_names = if let Change::NewEdges {
                    ref edges,
                    ref flag,
                    ..
                } = del
                {
                    edges
                        .iter()
                        .flat_map(|edge| {
                            let (_, name) = if flag.contains(EdgeFlags::PARENT_EDGE) {
                                (
                                    txn.internal_key(&edge.to, ROOT_PATCH_ID),
                                    txn.internal_key(&edge.from, ROOT_PATCH_ID),
                                )
                            } else {
                                (
                                    txn.internal_key(&edge.from, ROOT_PATCH_ID),
                                    txn.internal_key(&edge.to, ROOT_PATCH_ID),
                                )
                            };
                            txn.file_paths(&branch, name).into_iter().map(|names| {
                                let mut n: Vec<_> = names
                                    .into_iter()
                                    .map(|key| {
                                        let name = txn.get_contents(key).unwrap();
                                        let (perms, basename) = name.as_slice().split_at(2);
                                        let perms = FileMetadata::from_contents(perms);
                                        let (_perms, basename) = name.as_slice().split_at(2);
                                        let basename =
                                            std::str::from_utf8(basename).unwrap().to_string();
                                        (perms, basename)
                                        basename
                                    })
                                    .collect();
                                n.reverse();
                                n
                                let mut p = RepoPath::new();
                                for c in n {
                                    p.push(&c)
                                };
                                p
                            })
                        })
                        .collect()
                } else {
                    Vec::new()
                };
                let new_name = Rc::new(new_name.clone());
                current_file = Some(new_name.clone());
                ret.push((
                    new_name.clone(),
                    ChangeType::Move {
                        new_name: new_name.clone(),
                        former_names,
                    },
                ));
            }
        }
    }
    txn.commit_branch(branch)?;
    Ok(ret)
}

pub struct FileStatus {
    pub inode_status: ChangeType,
    pub records: Vec<Record<ChangeContext<PatchId>>>,
}

pub fn detailed_status<T: rand::Rng>(
    txn: &mut MutTxn<T>,
    repo_root: &RepoRoot<impl AsRef<Path>>,
    branch: &str,
    diff_algorithm: super::DiffAlgorithm,
    prefix: &RepoPath<impl AsRef<Path>>
) -> Result<HashMap<Rc<RepoPath<PathBuf>>, FileStatus>> {
    let mut record = RecordState::new();
    let branch = txn.open_branch(branch)?;
    txn.record(
        super::DiffAlgorithm::default(),
        diff_algorithm,
        &mut record,
        &branch,
        repo_root,
        &in_repo_root(),
        prefix
    )?;
    let (mut changes, _) = record.finish();

    let mut ret = HashMap::new();

    for change in changes.drain(..) {
        let mut changes_f;

        match &change {
            Record::Change { ref file, .. } => {
                changes_f = ret.entry(file.clone()).or_insert(FileStatus {
                    inode_status: ChangeType::Modified,
                    records: vec![],
                });
            }
            Record::Change { .. } => (),

            Record::FileAdd { ref name, .. } => {
                let file = Rc::new(name.clone());
                changes_f = ret.entry(file).or_insert(FileStatus {
                let mut changes_f = ret.entry(file).or_insert(FileStatus {
                    inode_status: ChangeType::New,
                    records: vec![],
                });
                changes_f.inode_status = ChangeType::New;
            }
            Record::FileDel { ref name, .. } => {
                let file = Rc::new(name.clone());
                changes_f = ret.entry(file).or_insert(FileStatus {
                let mut changes_f = ret.entry(file).or_insert(FileStatus {
                    inode_status: ChangeType::Del,
                    records: vec![],
                });
                changes_f.inode_status = ChangeType::Del;
            }
            Record::FileMove {
                ref new_name,
                ref del,
                ..
            } => {
                let former_names = if let Change::NewEdges {
                    ref edges,
                    ref flag,
                    ..
                } = del
                {
                    edges
                        .iter()
                        .flat_map(|edge| {
                            let (_, name) = if flag.contains(EdgeFlags::PARENT_EDGE) {
                                (
                                    txn.internal_key(&edge.to, ROOT_PATCH_ID),
                                    txn.internal_key(&edge.from, ROOT_PATCH_ID),
                                )
                            } else {
                                (
                                    txn.internal_key(&edge.from, ROOT_PATCH_ID),
                                    txn.internal_key(&edge.to, ROOT_PATCH_ID),
                                )
                            };
                            txn.file_paths(&branch, name).into_iter().map(|names| {
                                let mut n: Vec<_> = names
                                    .into_iter()
                                    .map(|key| {
                                        let name = txn.get_contents(key).unwrap();
                                        let (perms, basename) = name.as_slice().split_at(2);
                                        let perms = FileMetadata::from_contents(perms);
                                        let (_perms, basename) = name.as_slice().split_at(2);
                                        let basename =
                                            std::str::from_utf8(basename).unwrap().to_string();
                                        (perms, basename)
                                        basename
                                    })
                                    .collect();
                                n.reverse();
                                n
                                let mut p = RepoPath::new();
                                for c in n {
                                    p.push(&c)
                                };
                                p
                            })
                        })
                        .collect()
                } else {
                    Vec::new()
                };
                let new_name = Rc::new(new_name.clone());
                let moove = ChangeType::Move {
                    new_name: new_name.clone(),
                    former_names,
                };

                changes_f = match ret.entry(new_name) {
                match ret.entry(new_name) {
                    Entry::Occupied(mut o) => {
                        o.get_mut().inode_status = moove;
                        o.into_mut()
                    }
                    Entry::Vacant(v) => v.insert(FileStatus {
                        inode_status: moove,
                        records: vec![],
                    }),
                    Entry::Vacant(v) => {
                        v.insert(FileStatus {
                            inode_status: moove,
                            records: vec![],
                        });
                    },
                }
            }
        }

        changes_f.records.push(change)
        let file_with_new_record = if let &Record::Change { ref file, .. } = &change {
            Some(file.clone())
        } else {
            None
        };
        if let Some(file) = file_with_new_record {
            let mut changes_f = ret.entry(file.clone()).or_insert(FileStatus {
                    inode_status: ChangeType::Modified,
                    records: vec![],
                });                
            changes_f.records.push(change)
        }


    }
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


334
335


338


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

401


404

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
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
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051



1052
1053
1054
1055
1056
1057
1058
1059




















1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079


1082


1085


1088

use libpijul::fs_representation::{RepoPath, RepoRoot, PIJUL_DIR_NAME};
use libpijul::status::ChangeType;

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 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>(

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
fn print_record<T: rand::Rng, H>(
    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<H>>,
) {
    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);
            }
        }
        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);
            }
        }
        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());
        }
        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)
            }
        }
    }
}

fn print_change<T: rand::Rng>(
fn print_change<T: rand::Rng, H>(
    term: &mut Option<Box<StdoutTerminal>>,
    repo: &MutTxn<T>,
    old_line: usize,
    new_line: usize,
    change: &Change<ChangeContext<Hash>>,
    change: &Change<ChangeContext<H>>,
) {
    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);
                    }
                }
            }
        }
        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 = if !flag.contains(EdgeFlags::PARENT_EDGE) {
                    if h_targets.insert(&e.to) {
                        Some(&e.to)
                    } else {
                        None
                    }
                } else {
                    if h_targets.insert(&e.from) {
                        Some(&e.from)
                    } else {
                        None
                    }
                };
                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)
                    }
                }
            }
        }
    }
}

#[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 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>(
pub fn print_fileheader(term: &mut Option<Box<StdoutTerminal>>,
                        inode_status: ChangeType,
                        file: &RepoPath<impl AsRef<Path>>,
                        repo_root: &RepoRoot<impl AsRef<Path>>,
                        cwd: &Path
) {
    if let Some(ref mut term) = *term {
        term.attr(Attr::Bold).unwrap_or(());
        term.attr(Attr::Underline(true)).unwrap_or(());
    }
    match inode_status {
        ChangeType::Modified =>
            println!("{}", pretty_repo_path(repo_root, file, cwd).display()),
        ChangeType::New => {
            if let Some(ref mut term) = *term {
                term.fg(term::color::CYAN).unwrap_or(());
            };
            println!("new file {}", pretty_repo_path(repo_root, file, cwd).display())
        },
        ChangeType::Del => {
            if let Some(ref mut term) = *term {
                term.fg(term::color::MAGENTA).unwrap_or(());
            };
            println!("deleted file {}", pretty_repo_path(repo_root, file, cwd).display())
        },
        ChangeType::Move {ref former_names, ref new_name} => {
            let mut s = String::new();
            if former_names.len() == 1 {
                s.push_str(&format!("{} →", former_names[0].display()));
            } else if former_names.len() > 1 {
                s.push_str("{ ");
                for (k, former_name) in former_names.iter().enumerate() {
                    if k > 0 {
                        s.push_str(", ");
                    }
                    s.push_str(&former_name.display().to_string())
                }
                s.push_str(" } →");
            } else {
                s.push_str("→");
            }
            if let Some(ref mut term) = *term {
                term.fg(term::color::YELLOW).unwrap_or(());
            }
            println!("{} {}", s, pretty_repo_path(repo_root, new_name, cwd).display());
        }
    };
    if let Some(ref mut term) = *term {
        term.reset().unwrap_or(());
    }
} 

pub fn print_diff<T: rand::Rng>(
    repo_root: &RepoRoot<impl AsRef<Path>>,
    repository: &MutTxn<T>,
    cwd: &Path,
    changes: &[Record<ChangeContext<Hash>>],
) -> Result<(), Error> {
    debug!("changes: {:?}", changes);
    mut file_changes: HashMap<Rc<RepoPath<PathBuf>>, libpijul::status::FileStatus>
) {

    let mut terminal = if atty::is(atty::Stream::Stdout) {
        term::stdout()
    } else {
        None
    };
    let mut i = 0;
    let mut i = 0;
    let mut current_file = None;
    while i < changes.len() {
        debug!("changes: {:?}", changes[i]);
        print_record(
            repo_root,
            &mut terminal,
            &mut terminal,
            &mut terminal,
            cwd,
            repository,
            &mut current_file,
            &changes[i],
        );
        println!("");
        println!("");
        println!("");
        i += 1

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

    let mut current_file;

    for (file, file_status) in file_changes.drain() {

        current_file = Some(file.to_owned());

        print_fileheader(&mut terminal, file_status.inode_status, &file, repo_root, cwd);
        
        for r in file_status.records {
            print_record(repo_root,
                         &mut terminal,
                         cwd,
                         repository,
                         &mut current_file,
                         &r
            );
            println!("")
        }           

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

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        debug!("changes: {:?}", changes[i]);

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

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        print_change(

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

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    }
    Ok(())
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
use error::Error;
use libpijul::fs_representation::in_repo_root;
use libpijul::RecordState;
use libpijul::status::detailed_status;
use rand;
use std::fs::canonicalize;
use std::io::{stderr, Write};
use std::process::exit;

pub fn invocation() -> StaticSubcommand {
    return SubCommand::with_name("diff")
        .about("Show what would be recorded if record were called")
        .arg(
            Arg::with_name("repository")
                .long("repository")
                .help("The repository to show, defaults to the current directory.")
                .takes_value(true)
                .required(false),
        )
        .arg(
            Arg::with_name("branch")
                .long("branch")
                .help("The branch to show, defaults to the current branch.")
                .takes_value(true)
                .required(false),
        )
        .arg(
            Arg::with_name("prefix")
                .help("Prefix to start from")
                .takes_value(true)
                .multiple(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 run(args: &ArgMatches) -> Result<(), Error> {
    let opts = BasicOptions::from_args(args)?;
    let repo = opts.open_repo()?;
    let mut txn = repo.mut_txn_begin(rand::thread_rng())?;
    let prefix = if let Some(prefix) = args.value_of("prefix") {
        let p = canonicalize(opts.cwd.join(prefix))?;
        opts.repo_root.relativize(&p)?.to_owned()
    } else {
        in_repo_root().to_owned()
    };
    let diff_algorithm = if args.is_present("patience") {
        libpijul::DiffAlgorithm::Patience
    } else {
        libpijul::DiffAlgorithm::Myers
    };
    let status = detailed_status(&mut txn, &opts.repo_root, &opts.branch(), diff_algorithm, &prefix)?;
    super::ask::print_diff(&opts.repo_root, &txn, &opts.cwd, status);
    Ok(())