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
use crate::graph::{CommitInfo, GitGraph, HeadInfo};
use crate::print::format::CommitFormat;
use crate::settings::{Characters, Settings};
use itertools::Itertools;
use std::cmp::max;
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::collections::HashMap;
use std::fmt::Write;
use textwrap::Options;
use yansi::Paint;
const SPACE: u8 = 0;
const DOT: u8 = 1;
const CIRCLE: u8 = 2;
const VER: u8 = 3;
const HOR: u8 = 4;
const CROSS: u8 = 5;
const R_U: u8 = 6;
const R_D: u8 = 7;
const L_D: u8 = 8;
const L_U: u8 = 9;
const VER_L: u8 = 10;
const VER_R: u8 = 11;
const HOR_U: u8 = 12;
const HOR_D: u8 = 13;
const ARR_L: u8 = 14;
const ARR_R: u8 = 15;
const WHITE: u8 = 7;
const HEAD_COLOR: u8 = 14;
const HASH_COLOR: u8 = 11;
type UnicodeGraphInfo = (Vec<String>, Vec<String>, Vec<usize>);
pub fn print_unicode(graph: &GitGraph, settings: &Settings) -> Result<UnicodeGraphInfo, String> {
let num_cols = 2 * graph
.all_branches
.iter()
.map(|b| b.visual.column.unwrap_or(0))
.max()
.unwrap()
+ 1;
let head_idx = graph.indices.get(&graph.head.oid);
let inserts = get_inserts(graph, settings.compact);
let (indent1, indent2) = if let Some((_, ind1, ind2)) = settings.wrapping {
(" ".repeat(ind1.unwrap_or(0)), " ".repeat(ind2.unwrap_or(0)))
} else {
("".to_string(), "".to_string())
};
let wrap_options = if let Some((width, _, _)) = settings.wrapping {
create_wrapping_options(width, &indent1, &indent2, num_cols + 4)?
} else {
None
};
let mut index_map = vec![];
let mut text_lines = vec![];
let mut offset = 0;
for (idx, info) in graph.commits.iter().enumerate() {
index_map.push(idx + offset);
let cnt_inserts = if let Some(inserts) = inserts.get(&idx) {
inserts
.iter()
.filter(|vec| {
vec.iter().all(|occ| match occ {
Occ::Commit(_, _) => false,
Occ::Range(_, _, _, _) => true,
})
})
.count()
} else {
0
};
let head = if head_idx.map_or(false, |h| h == &idx) {
Some(&graph.head)
} else {
None
};
let lines = format(
&settings.format,
graph,
info,
head,
settings.colored,
&wrap_options,
)?;
let num_lines = if lines.is_empty() { 0 } else { lines.len() - 1 };
let max_inserts = max(cnt_inserts, num_lines);
let add_lines = max_inserts - num_lines;
text_lines.extend(lines.into_iter().map(Some));
text_lines.extend((0..add_lines).map(|_| None));
offset += max_inserts;
}
let mut grid = Grid::new(
num_cols,
graph.commits.len() + offset,
[SPACE, WHITE, settings.branches.persistence.len() as u8 + 2],
);
for (idx, info) in graph.commits.iter().enumerate() {
if let Some(trace) = info.branch_trace {
let branch = &graph.all_branches[trace];
let column = branch.visual.column.unwrap();
let idx_map = index_map[idx];
let branch_color = branch.visual.term_color;
grid.set(
column * 2,
idx_map,
if info.is_merge { CIRCLE } else { DOT },
branch_color,
branch.persistence,
);
for p in 0..2 {
if let Some(par_oid) = info.parents[p] {
if let Some(par_idx) = graph.indices.get(&par_oid) {
let par_idx_map = index_map[*par_idx];
let par_info = &graph.commits[*par_idx];
let par_branch = &graph.all_branches[par_info.branch_trace.unwrap()];
let par_column = par_branch.visual.column.unwrap();
let (color, pers) = if info.is_merge {
(par_branch.visual.term_color, par_branch.persistence)
} else {
(branch_color, branch.persistence)
};
if branch.visual.column == par_branch.visual.column {
if par_idx_map > idx_map + 1 {
vline(&mut grid, (idx_map, par_idx_map), column, color, pers);
}
} else {
let split_index = super::get_deviate_index(graph, idx, *par_idx);
let split_idx_map = index_map[split_index];
let inserts = &inserts[&split_index];
for (insert_idx, sub_entry) in inserts.iter().enumerate() {
for occ in sub_entry {
match occ {
Occ::Commit(_, _) => {}
Occ::Range(i1, i2, _, _) => {
if *i1 == idx && i2 == par_idx {
vline(
&mut grid,
(idx_map, split_idx_map + insert_idx),
column,
color,
pers,
);
hline(
&mut grid,
split_idx_map + insert_idx,
(par_column, column),
info.is_merge && p > 0,
color,
pers,
);
vline(
&mut grid,
(split_idx_map + insert_idx, par_idx_map),
par_column,
color,
pers,
);
}
}
}
}
}
}
}
}
}
}
}
let lines = print_graph(&settings.characters, &grid, text_lines, settings.colored);
Ok((lines.0, lines.1, index_map))
}
fn create_wrapping_options<'a>(
width: Option<usize>,
indent1: &'a str,
indent2: &'a str,
graph_width: usize,
) -> Result<Option<Options<'a>>, String> {
let wrapping = if let Some(width) = width {
Some(
textwrap::Options::new(width)
.initial_indent(indent1)
.subsequent_indent(indent2),
)
} else if atty::is(atty::Stream::Stdout) {
let width = crossterm::terminal::size()
.map_err(|err| err.to_string())?
.0;
let width = if width as usize > graph_width {
width as usize - graph_width
} else {
1
};
Some(
textwrap::Options::new(width)
.initial_indent(indent1)
.subsequent_indent(indent2),
)
} else {
None
};
Ok(wrapping)
}
fn vline(grid: &mut Grid, (from, to): (usize, usize), column: usize, color: u8, pers: u8) {
for i in (from + 1)..to {
let (curr, _, old_pers) = grid.get_tuple(column * 2, i);
let (new_col, new_pers) = if pers < old_pers {
(Some(color), Some(pers))
} else {
(None, None)
};
match curr {
DOT | CIRCLE => {}
HOR => {
grid.set_opt(column * 2, i, Some(CROSS), Some(color), Some(pers));
}
HOR_U | HOR_D => {
grid.set_opt(column * 2, i, Some(CROSS), Some(color), Some(pers));
}
CROSS | VER | VER_L | VER_R => grid.set_opt(column * 2, i, None, new_col, new_pers),
L_D | L_U => {
grid.set_opt(column * 2, i, Some(VER_L), new_col, new_pers);
}
R_D | R_U => {
grid.set_opt(column * 2, i, Some(VER_R), new_col, new_pers);
}
_ => {
grid.set_opt(column * 2, i, Some(VER), new_col, new_pers);
}
}
}
}
fn hline(
grid: &mut Grid,
index: usize,
(from, to): (usize, usize),
merge: bool,
color: u8,
pers: u8,
) {
if from == to {
return;
}
let from_2 = from * 2;
let to_2 = to * 2;
if from < to {
for column in (from_2 + 1)..to_2 {
if merge && column == to_2 - 1 {
grid.set(column, index, ARR_R, color, pers);
} else {
let (curr, _, old_pers) = grid.get_tuple(column, index);
let (new_col, new_pers) = if pers < old_pers {
(Some(color), Some(pers))
} else {
(None, None)
};
match curr {
DOT | CIRCLE => {}
VER => grid.set_opt(column, index, Some(CROSS), None, None),
HOR | CROSS | HOR_U | HOR_D => {
grid.set_opt(column, index, None, new_col, new_pers)
}
L_U | R_U => grid.set_opt(column, index, Some(HOR_U), new_col, new_pers),
L_D | R_D => grid.set_opt(column, index, Some(HOR_D), new_col, new_pers),
_ => {
grid.set_opt(column, index, Some(HOR), new_col, new_pers);
}
}
}
}
let (left, _, old_pers) = grid.get_tuple(from_2, index);
let (new_col, new_pers) = if pers < old_pers {
(Some(color), Some(pers))
} else {
(None, None)
};
match left {
DOT | CIRCLE => {}
VER => grid.set_opt(from_2, index, Some(VER_R), new_col, new_pers),
VER_L => grid.set_opt(from_2, index, Some(CROSS), None, None),
VER_R => {}
HOR | L_U => grid.set_opt(from_2, index, Some(HOR_U), new_col, new_pers),
_ => {
grid.set_opt(from_2, index, Some(R_D), new_col, new_pers);
}
}
let (right, _, old_pers) = grid.get_tuple(to_2, index);
let (new_col, new_pers) = if pers < old_pers {
(Some(color), Some(pers))
} else {
(None, None)
};
match right {
DOT | CIRCLE => {}
VER => grid.set_opt(to_2, index, Some(VER_L), None, None),
VER_L | HOR_U => grid.set_opt(to_2, index, None, new_col, new_pers),
HOR | R_U => grid.set_opt(to_2, index, Some(HOR_U), new_col, new_pers),
_ => {
grid.set_opt(to_2, index, Some(L_U), new_col, new_pers);
}
}
} else {
for column in (to_2 + 1)..from_2 {
if merge && column == to_2 + 1 {
grid.set(column, index, ARR_L, color, pers);
} else {
let (curr, _, old_pers) = grid.get_tuple(column, index);
let (new_col, new_pers) = if pers < old_pers {
(Some(color), Some(pers))
} else {
(None, None)
};
match curr {
DOT | CIRCLE => {}
VER => grid.set_opt(column, index, Some(CROSS), None, None),
HOR | CROSS | HOR_U | HOR_D => {
grid.set_opt(column, index, None, new_col, new_pers)
}
L_U | R_U => grid.set_opt(column, index, Some(HOR_U), new_col, new_pers),
L_D | R_D => grid.set_opt(column, index, Some(HOR_D), new_col, new_pers),
_ => {
grid.set_opt(column, index, Some(HOR), new_col, new_pers);
}
}
}
}
let (left, _, old_pers) = grid.get_tuple(to_2, index);
let (new_col, new_pers) = if pers < old_pers {
(Some(color), Some(pers))
} else {
(None, None)
};
match left {
DOT | CIRCLE => {}
VER => grid.set_opt(to_2, index, Some(VER_R), None, None),
VER_R => grid.set_opt(to_2, index, None, new_col, new_pers),
HOR | L_U => grid.set_opt(to_2, index, Some(HOR_U), new_col, new_pers),
_ => {
grid.set_opt(to_2, index, Some(R_U), new_col, new_pers);
}
}
let (right, _, old_pers) = grid.get_tuple(from_2, index);
let (new_col, new_pers) = if pers < old_pers {
(Some(color), Some(pers))
} else {
(None, None)
};
match right {
DOT | CIRCLE => {}
VER => grid.set_opt(from_2, index, Some(VER_L), new_col, new_pers),
VER_R => grid.set_opt(from_2, index, Some(CROSS), None, None),
VER_L => grid.set_opt(from_2, index, None, new_col, new_pers),
HOR | R_D => grid.set_opt(from_2, index, Some(HOR_D), new_col, new_pers),
_ => {
grid.set_opt(from_2, index, Some(L_D), new_col, new_pers);
}
}
}
}
fn get_inserts(graph: &GitGraph, compact: bool) -> HashMap<usize, Vec<Vec<Occ>>> {
let mut inserts: HashMap<usize, Vec<Vec<Occ>>> = HashMap::new();
for (idx, info) in graph.commits.iter().enumerate() {
let column = graph.all_branches[info.branch_trace.unwrap()]
.visual
.column
.unwrap();
inserts.insert(idx, vec![vec![Occ::Commit(idx, column)]]);
}
for (idx, info) in graph.commits.iter().enumerate() {
if let Some(trace) = info.branch_trace {
let branch = &graph.all_branches[trace];
let column = branch.visual.column.unwrap();
for p in 0..2 {
if let Some(par_oid) = info.parents[p] {
if let Some(par_idx) = graph.indices.get(&par_oid) {
let par_info = &graph.commits[*par_idx];
let par_branch = &graph.all_branches[par_info.branch_trace.unwrap()];
let par_column = par_branch.visual.column.unwrap();
let column_range = sorted(column, par_column);
if column != par_column {
let split_index = super::get_deviate_index(graph, idx, *par_idx);
match inserts.entry(split_index) {
Occupied(mut entry) => {
let mut insert_at = entry.get().len();
for (insert_idx, sub_entry) in entry.get().iter().enumerate() {
let mut occ = false;
for other_range in sub_entry {
if other_range.overlaps(&column_range) {
match other_range {
Occ::Commit(target_index, _) => {
if !compact
|| !info.is_merge
|| idx != *target_index
|| p == 0
{
occ = true;
break;
}
}
Occ::Range(o_idx, o_par_idx, _, _) => {
if idx != *o_idx && par_idx != o_par_idx {
occ = true;
break;
}
}
}
}
}
if !occ {
insert_at = insert_idx;
break;
}
}
let vec = entry.get_mut();
if insert_at == vec.len() {
vec.push(vec![Occ::Range(
idx,
*par_idx,
column_range.0,
column_range.1,
)]);
} else {
vec[insert_at].push(Occ::Range(
idx,
*par_idx,
column_range.0,
column_range.1,
));
}
}
Vacant(entry) => {
entry.insert(vec![vec![Occ::Range(
idx,
*par_idx,
column_range.0,
column_range.1,
)]]);
}
}
}
}
}
}
}
}
inserts
}
fn print_graph(
characters: &Characters,
grid: &Grid,
text_lines: Vec<Option<String>>,
color: bool,
) -> (Vec<String>, Vec<String>) {
let mut g_lines = vec![];
let mut t_lines = vec![];
for (row, line) in grid.data.chunks(grid.width).zip(text_lines.into_iter()) {
let mut g_out = String::new();
let mut t_out = String::new();
if color {
for arr in row {
if arr[0] == SPACE {
write!(g_out, "{}", characters.chars[arr[0] as usize])
} else {
write!(
g_out,
"{}",
Paint::fixed(arr[1], characters.chars[arr[0] as usize])
)
}
.unwrap();
}
} else {
let str = row
.iter()
.map(|arr| characters.chars[arr[0] as usize])
.collect::<String>();
write!(g_out, "{}", str).unwrap();
}
if let Some(line) = line {
write!(t_out, "{}", line).unwrap();
}
g_lines.push(g_out);
t_lines.push(t_out);
}
(g_lines, t_lines)
}
fn format(
format: &CommitFormat,
graph: &GitGraph,
info: &CommitInfo,
head: Option<&HeadInfo>,
color: bool,
wrapping: &Option<Options>,
) -> Result<Vec<String>, String> {
let commit = graph
.repository
.find_commit(info.oid)
.map_err(|err| err.message().to_string())?;
let branch_str = format_branches(graph, info, head, color);
let hash_color = if color { Some(HASH_COLOR) } else { None };
crate::print::format::format(&commit, branch_str, wrapping, hash_color, format)
}
pub fn format_branches(
graph: &GitGraph,
info: &CommitInfo,
head: Option<&HeadInfo>,
color: bool,
) -> String {
let curr_color = info
.branch_trace
.map(|branch_idx| &graph.all_branches[branch_idx].visual.term_color);
let mut branch_str = String::new();
let head_str = "HEAD ->";
if let Some(head) = head {
if !head.is_branch {
if color {
write!(branch_str, " {}", Paint::fixed(HEAD_COLOR, head_str))
} else {
write!(branch_str, " {}", head_str)
}
.unwrap();
}
}
if !info.branches.is_empty() {
write!(branch_str, " (").unwrap();
let branches = info.branches.iter().sorted_by_key(|br| {
if let Some(head) = head {
head.name != graph.all_branches[**br].name
} else {
false
}
});
for (idx, branch_index) in branches.enumerate() {
let branch = &graph.all_branches[*branch_index];
let branch_color = branch.visual.term_color;
if let Some(head) = head {
if idx == 0 && head.is_branch {
if color {
write!(branch_str, "{} ", Paint::fixed(14, head_str))
} else {
write!(branch_str, "{} ", head_str)
}
.unwrap();
}
}
if color {
write!(branch_str, "{}", Paint::fixed(branch_color, &branch.name))
} else {
write!(branch_str, "{}", &branch.name)
}
.unwrap();
if idx < info.branches.len() - 1 {
write!(branch_str, ", ").unwrap();
}
}
write!(branch_str, ")").unwrap();
}
if !info.tags.is_empty() {
write!(branch_str, " [").unwrap();
for (idx, tag_index) in info.tags.iter().enumerate() {
let tag = &graph.all_branches[*tag_index];
let tag_color = curr_color.unwrap_or(&tag.visual.term_color);
if color {
write!(branch_str, "{}", Paint::fixed(*tag_color, &tag.name[5..]))
} else {
write!(branch_str, "{}", &tag.name[5..])
}
.unwrap();
if idx < info.tags.len() - 1 {
write!(branch_str, ", ").unwrap();
}
}
write!(branch_str, "]").unwrap();
}
branch_str
}
enum Occ {
Commit(usize, usize),
Range(usize, usize, usize, usize),
}
impl Occ {
fn overlaps(&self, (start, end): &(usize, usize)) -> bool {
match self {
Occ::Commit(_, col) => start <= col && end >= col,
Occ::Range(_, _, s, e) => s <= end && e >= start,
}
}
}
fn sorted(v1: usize, v2: usize) -> (usize, usize) {
if v2 > v1 {
(v1, v2)
} else {
(v2, v1)
}
}
#[allow(dead_code)]
struct Grid {
width: usize,
height: usize,
data: Vec<[u8; 3]>,
}
impl Grid {
pub fn new(width: usize, height: usize, initial: [u8; 3]) -> Self {
Grid {
width,
height,
data: vec![initial; width * height],
}
}
pub fn index(&self, x: usize, y: usize) -> usize {
y * self.width + x
}
pub fn get_tuple(&self, x: usize, y: usize) -> (u8, u8, u8) {
let v = self.data[self.index(x, y)];
(v[0], v[1], v[2])
}
pub fn set(&mut self, x: usize, y: usize, character: u8, color: u8, pers: u8) {
let idx = self.index(x, y);
self.data[idx] = [character, color, pers];
}
pub fn set_opt(
&mut self,
x: usize,
y: usize,
character: Option<u8>,
color: Option<u8>,
pers: Option<u8>,
) {
let idx = self.index(x, y);
let arr = &mut self.data[idx];
if let Some(character) = character {
arr[0] = character;
}
if let Some(color) = color {
arr[1] = color;
}
if let Some(pers) = pers {
arr[2] = pers;
}
}
}