pijul 0.7.2

A patch-based distributed version control system, easy to use and fast. Command-line interface.
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
use std::io::prelude::*;
use base64::URL_SAFE_NO_PAD;
use getch;
use libpijul::patch::{Change, Patch, Record, EdgeOp, PatchHeader};

use std::io::stdout;
use std::collections::{HashMap, HashSet};
use std::rc::Rc;
use std::path::PathBuf;

use error::Error;
use libpijul::{MutTxn, LineId, FOLDER_EDGE, PARENT_EDGE, DELETED_EDGE, Hash, PatchId};
use std::char::from_u32;
use std::str;
use std;
use rand;
use rustyline;
use term::{StdoutTerminal, Attr};
use term;

const BINARY_CONTENTS: &'static str = "<binary contents>";
#[derive(Clone,Copy)]
pub enum Command {
    Pull,
    Push,
    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(());
    }
    print!("{}", title);
    if let Some(ref mut term) = *term {
        term.reset().unwrap_or(());
    }
    println!("{}", contents);
}

pub fn print_patch_descr(term: &mut Option<Box<StdoutTerminal>>, hash: &Hash, internal: Option<&PatchId>, patch: &PatchHeader) {

    print_section(term, "Hash:", &format!(" {}", &hash.to_base64(URL_SAFE_NO_PAD)));
    if let Some(internal) = internal {
        print_section(term, "Internal id:", &format!(" {}", &internal.to_base64(URL_SAFE_NO_PAD)));
    }

    print_section(term, "Authors:", &format!(" {:?}", patch.authors));
    print_section(term, "Timestamp:", &format!(" {}", patch.timestamp));
    println!("");
    println!("    {}", patch.name);
    println!("");
    if let Some(ref d) = patch.description {
        println!("");
        println!("   {}", d);
    }
}


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)
                   -> Result<(char, Option<bool>), Error> {
    let mut term = term::stdout();
    print_patch_descr(&mut term, a, patchid, b);
    print!("{} [ynkad] ",
           match command_name {
               Command::Push => "Shall I push this patch?",
               Command::Pull => "Shall I pull this patch?",
               Command::Unrecord => "Shall I unrecord this patch?",
           });
    try!(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)),
    }
}



/// Patches might have a dummy "changes" field here.
pub fn ask_patches(command: Command, patches: &[(Hash, Option<PatchId>, Patch)]) -> Result<HashSet<Hash>, Error> {

    let getch = try!(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;


    while i < patches.len() {
        let (ref a, ref 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 forced_decision.or(final_decision) {
            Some(true) => 'Y',
            Some(false) => 'N',
            None => {
                debug!("decision not forced");
                let (current, remaining) = try!(interactive_ask(&getch, a, patchid.as_ref(), b, command));
                final_decision = remaining;
                current
            }
        };
        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
            }
            _ => {}
        }
    }
    Ok(choices.into_iter()
        .filter(|&(_, selected)| selected)
        .map(|(x, _)| x.to_owned())
        .collect())
}


fn change_deps(id: usize, c: &Record, 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_change<T: rand::Rng>(term: &mut Option<Box<StdoutTerminal>>,
                              repo: &MutTxn<T>,
                              current_file: &mut Option<Rc<PathBuf>>,
                              c: &Record)
                              -> Result<(), Error> {
    match *c {

        Record::FileAdd { ref name, .. } => {
            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!("{}", name);
            Ok(())
        }
        Record::FileDel { ref name, .. } => {
            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!("{}", name);
            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!("{}", new_name);
            Ok(())
        }
        Record::Replace { ref adds, ref dels, ref file, .. } => {
            let r = Record::Change { change: dels.clone(), file: file.clone(), conflict_reordering: Vec::new() };
            print_change(term, repo, current_file, &r)?;
            let r = Record::Change { change: adds.clone(), file: file.clone(), conflict_reordering: Vec::new() };
            print_change(term, repo, current_file, &r)
        }
        Record::Change { ref change, ref file, .. } => {
            match *change {
                Change::NewNodes { // ref up_context,ref down_context,ref line_num,
                                   ref flag,
                                   ref nodes,
                                   .. } => {
                    for n in nodes {
                        if flag.contains(FOLDER_EDGE) {
                            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 {
                            let s = str::from_utf8(n).unwrap_or(BINARY_CONTENTS);
                            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!("In file {:?}\n", file);
                                if let Some(ref mut term) = *term {
                                    term.reset().unwrap_or(());
                                }
                                *current_file = Some(file.clone())
                            }
                            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, ref op, .. } => {
                    let mut h_targets = HashSet::with_capacity(edges.len());
                    for e in edges {
                        let (target, flag) = match *op {
                            EdgeOp::Map { flag, .. } |
                            EdgeOp::New { flag, .. } |
                            EdgeOp::Forget { previous: flag } => {
                                if !flag.contains(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);

                            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!("In file {:?}\n", file);
                                if let Some(ref mut term) = *term {
                                    term.reset().unwrap_or(());
                                }
                                *current_file = Some(file.clone())
                            }


                            if flag.contains(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(())
                }
            }
        }
    }
}

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",
        }
    }
}

pub fn ask_changes<T: rand::Rng>(repository: &MutTxn<T>,
                                 changes: &[Record],
                                 direction: ChangesDirection)
                                 -> Result<HashMap<usize, bool>, Error> {
    debug!("changes: {:?}", changes);
    let mut terminal = term::stdout();
    let getch = try!(getch::Getch::new());
    let mut i = 0;
    let mut choices: HashMap<usize, bool> = HashMap::new();
    let mut final_decision = 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;
    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 e = match decision {
            Some(true) => 'Y',
            Some(false) => 'N',
            None => {
                if let Some(d) = final_decision {
                    d
                } else {
                    debug!("changes: {:?}", changes[i]);
                    try!(print_change(&mut terminal, repository, &mut current_file, &changes[i]));
                    println!("");
                    print!("Shall I {} this change? [ynkad] ", direction.verb());
                    try!(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' => {
                                    final_decision = Some('Y');
                                    'Y'
                                }
                                'D' => {
                                    final_decision = Some('N');
                                    'N'
                                }
                                e => e,
                            }
                        }
                        _ => '\0',
                    }
                }
            }
        };
        match e {
            'Y' => {
                choices.insert(i, direction.is_record());
                i += 1
            }
            'N' => {
                choices.insert(i, !direction.is_record());
                i += 1
            }
            'K' if i > 0 => {
                choices.remove(&i);
                i -= 1
            }
            _ => {}
        }
    }
    Ok(choices)
}

pub fn ask_authors() -> Result<Vec<String>, Error> {

    try!(std::io::stdout().flush());
    let mut rl = rustyline::Editor::<()>::new();
    let input = rl.readline("What is your name <and email address>? ")?;
    Ok(vec![input])
}


pub fn ask_patch_name() -> Result<String, Error> {
    try!(std::io::stdout().flush());
    let mut rl = rustyline::Editor::<()>::new();
    let input = rl.readline("What is the name of this patch? ")?;
    Ok(input)
}

pub fn ask_learn_ssh(host: &str, port: u16, fingerprint: &str) -> Result<bool, Error> {
    try!(std::io::stdout().flush());
    print!("The authenticity of host {:?}:{} cannot be established.\nThe fingerprint is {:?}.",
           host,
           port,
           fingerprint);
    let mut rl = rustyline::Editor::<()>::new();
    let input = rl.readline("Are you sure you want to continue (yes/no)? ")?;
    let input = input.to_uppercase();
    Ok(input.trim() == "YES")
}


pub fn print_status<T: rand::Rng>(repository: &MutTxn<T>,
                                  changes: &[Record]) -> Result<(), Error> {

    debug!("changes: {:?}", changes);
    let mut terminal = term::stdout();
    let mut i = 0;
    let mut current_file = None;
    while i < changes.len() {
        debug!("changes: {:?}", changes[i]);
        try!(print_change(&mut terminal, repository, &mut current_file, &changes[i]));
        println!("");
        i += 1
    }
    Ok(())
}

pub fn password() -> Result<String, Error> {

    std::io::stdout().flush()?;
    println!("Password: ");
    let mut terminal = term::stdout();
    if let Some(ref mut terminal) = terminal {
        terminal.attr(term::Attr::Secure)?;
    }
    let stdin = std::io::stdin();
    let line = stdin.lock().lines().next().unwrap();
    Ok(line?)
}