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
use std::fs;
use std::path::{Path, PathBuf};

use radicle::git;
use radicle_git_ext::Oid;
use radicle_surf::diff;
use radicle_surf::diff::{Added, Copied, Deleted, FileStats, Hunks, Modified, Moved};
use radicle_surf::diff::{Diff, DiffContent, FileDiff, Hunk, Modification};
use radicle_term as term;
use term::cell::Cell;
use term::VStack;

use crate::git::unified_diff::FileHeader;
use crate::terminal::highlight::{Highlighter, Theme};

use super::unified_diff::{Decode, HunkHeader};

/// Blob returned by the [`Repo`] trait.
#[derive(PartialEq, Eq, Debug)]
pub enum Blob {
    Binary,
    Empty,
    Plain(Vec<u8>),
}

/// A repository of Git blobs.
pub trait Repo {
    /// Lookup a blob from the repo.
    fn blob(&self, oid: git::Oid) -> Result<Blob, git::raw::Error>;
    /// Lookup a file in the workdir.
    fn file(&self, path: &Path) -> Option<Blob>;
}

impl Repo for git::raw::Repository {
    fn blob(&self, oid: git::Oid) -> Result<Blob, git::raw::Error> {
        let blob = self.find_blob(*oid)?;

        if blob.is_binary() {
            Ok(Blob::Binary)
        } else {
            let content = blob.content();

            if content.is_empty() {
                Ok(Blob::Empty)
            } else {
                Ok(Blob::Plain(blob.content().to_vec()))
            }
        }
    }

    fn file(&self, path: &Path) -> Option<Blob> {
        self.workdir()
            .and_then(|dir| fs::read(dir.join(path)).ok())
            .map(|content| {
                // A file is considered binary if there is a zero byte in the first 8 kilobytes
                // of the file. This is the same heuristic Git uses.
                let binary = content.iter().take(8192).any(|b| *b == 0);
                if binary {
                    Blob::Binary
                } else {
                    Blob::Plain(content)
                }
            })
    }
}

/// Blobs passed down to the hunk renderer.
#[derive(Debug)]
pub struct Blobs<T> {
    pub old: Option<T>,
    pub new: Option<T>,
}

impl<T> Blobs<T> {
    pub fn new(old: Option<T>, new: Option<T>) -> Self {
        Self { old, new }
    }
}

impl Blobs<(PathBuf, Blob)> {
    pub fn highlight(&self, hi: &mut Highlighter) -> Blobs<Vec<term::Line>> {
        let mut blobs = Blobs::default();
        if let Some((path, Blob::Plain(content))) = &self.old {
            blobs.old = hi.highlight(path, content).ok();
        }
        if let Some((path, Blob::Plain(content))) = &self.new {
            blobs.new = hi.highlight(path, content).ok();
        }
        blobs
    }

    pub fn from_paths<R: Repo>(
        old: Option<(&Path, Oid)>,
        new: Option<(&Path, Oid)>,
        repo: &R,
    ) -> Blobs<(PathBuf, Blob)> {
        Blobs::new(
            old.and_then(|(path, oid)| {
                repo.blob(oid)
                    .ok()
                    .or_else(|| repo.file(path))
                    .map(|blob| (path.to_path_buf(), blob))
            }),
            new.and_then(|(path, oid)| {
                repo.blob(oid)
                    .ok()
                    .or_else(|| repo.file(path))
                    .map(|blob| (path.to_path_buf(), blob))
            }),
        )
    }
}

impl<T> Default for Blobs<T> {
    fn default() -> Self {
        Self {
            old: None,
            new: None,
        }
    }
}

/// Types that can be rendered as pretty diffs.
pub trait ToPretty {
    /// The output of the render process.
    type Output: term::Element;
    /// Context that can be passed down from parent objects during rendering.
    type Context;

    /// Render to pretty diff output.
    fn pretty<R: Repo>(
        &self,
        hi: &mut Highlighter,
        context: &Self::Context,
        repo: &R,
    ) -> Self::Output;
}

impl ToPretty for Diff {
    type Output = term::VStack<'static>;
    type Context = ();

    fn pretty<R: Repo>(
        &self,
        hi: &mut Highlighter,
        context: &Self::Context,
        repo: &R,
    ) -> Self::Output {
        term::VStack::default()
            .padding(0)
            .children(self.files().flat_map(|f| {
                [
                    f.pretty(hi, context, repo).boxed(),
                    term::Line::blank().boxed(), // Blank line between files.
                ]
            }))
    }
}

impl ToPretty for FileHeader {
    type Output = term::Line;
    type Context = Option<FileStats>;

    fn pretty<R: Repo>(
        &self,
        _hi: &mut Highlighter,
        stats: &Self::Context,
        _repo: &R,
    ) -> Self::Output {
        let theme = Theme::default();
        let (mut header, badge, binary) = match self {
            FileHeader::Added { path, binary, .. } => (
                term::Line::new(path.display().to_string()),
                Some(term::format::badge_positive("created")),
                *binary,
            ),
            FileHeader::Moved {
                old_path, new_path, ..
            } => (
                term::Line::spaced([
                    term::label(old_path.display().to_string()),
                    term::label("->".to_string()),
                    term::label(new_path.display().to_string()),
                ]),
                Some(term::format::badge_secondary("moved")),
                false,
            ),
            FileHeader::Deleted { path, binary, .. } => (
                term::Line::new(path.display().to_string()),
                Some(term::format::badge_negative("deleted")),
                *binary,
            ),
            FileHeader::Modified {
                path,
                old,
                new,
                binary,
                ..
            } => {
                if old.mode != new.mode {
                    (
                        term::Line::spaced([
                            term::label(path.display().to_string()),
                            term::label(format!("{:o}", u32::from(old.mode.clone())))
                                .fg(term::Color::Blue),
                            term::label("->".to_string()),
                            term::label(format!("{:o}", u32::from(new.mode.clone())))
                                .fg(term::Color::Blue),
                        ]),
                        Some(term::format::badge_secondary("mode changed")),
                        *binary,
                    )
                } else {
                    (term::Line::new(path.display().to_string()), None, *binary)
                }
            }
            FileHeader::Copied {
                old_path, new_path, ..
            } => (
                term::Line::spaced([
                    term::label(old_path.display().to_string()),
                    term::label("->".to_string()),
                    term::label(new_path.display().to_string()),
                ]),
                Some(term::format::badge_secondary("copied")),
                false,
            ),
        };

        if binary {
            header.push(term::Label::space());
            header.push(term::label(term::format::badge_yellow("binary")));
        }

        let (additions, deletions) = if let Some(stats) = stats {
            (stats.additions, stats.deletions)
        } else {
            (0, 0)
        };
        if deletions > 0 {
            header.push(term::Label::space());
            header.push(term::label(format!("-{deletions}")).fg(theme.color("negative.light")));
        }
        if additions > 0 {
            header.push(term::Label::space());
            header.push(term::label(format!("+{additions}")).fg(theme.color("positive.light")));
        }
        if let Some(badge) = badge {
            header.push(term::Label::space());
            header.push(badge);
        }
        header
    }
}

impl ToPretty for FileDiff {
    type Output = term::VStack<'static>;
    type Context = ();

    fn pretty<R: Repo>(
        &self,
        hi: &mut Highlighter,
        _context: &Self::Context,
        repo: &R,
    ) -> Self::Output {
        let header = FileHeader::from(self);

        match self {
            FileDiff::Added(f) => f.pretty(hi, &header, repo),
            FileDiff::Deleted(f) => f.pretty(hi, &header, repo),
            FileDiff::Modified(f) => f.pretty(hi, &header, repo),
            FileDiff::Moved(f) => f.pretty(hi, &header, repo),
            FileDiff::Copied(f) => f.pretty(hi, &header, repo),
        }
    }
}

impl ToPretty for DiffContent {
    type Output = term::VStack<'static>;
    type Context = Blobs<(PathBuf, Blob)>;

    fn pretty<R: Repo>(
        &self,
        hi: &mut Highlighter,
        blobs: &Self::Context,
        repo: &R,
    ) -> Self::Output {
        let mut vstack = term::VStack::default().padding(0);

        match self {
            DiffContent::Plain {
                hunks: Hunks(hunks),
                ..
            } => {
                let blobs = blobs.highlight(hi);

                for (i, h) in hunks.iter().enumerate() {
                    vstack.push(h.pretty(hi, &blobs, repo));
                    if i != hunks.len() - 1 {
                        vstack = vstack.divider();
                    }
                }
            }
            DiffContent::Empty => {}
            DiffContent::Binary => {}
        }
        vstack
    }
}

impl ToPretty for Moved {
    type Output = term::VStack<'static>;
    type Context = FileHeader;

    fn pretty<R: Repo>(
        &self,
        hi: &mut Highlighter,
        header: &Self::Context,
        repo: &R,
    ) -> Self::Output {
        let header = header.pretty(hi, &self.diff.stats().copied(), repo);

        term::VStack::default()
            .border(Some(term::colors::FAINT))
            .padding(1)
            .child(term::Line::default().extend(header))
    }
}

impl ToPretty for Added {
    type Output = term::VStack<'static>;
    type Context = FileHeader;

    fn pretty<R: Repo>(
        &self,
        hi: &mut Highlighter,
        header: &Self::Context,
        repo: &R,
    ) -> Self::Output {
        let old = None;
        let new = Some((self.path.as_path(), self.new.oid));

        pretty_modification(header, &self.diff, old, new, repo, hi)
    }
}

impl ToPretty for Deleted {
    type Output = term::VStack<'static>;
    type Context = FileHeader;

    fn pretty<R: Repo>(
        &self,
        hi: &mut Highlighter,
        header: &Self::Context,
        repo: &R,
    ) -> Self::Output {
        let old = Some((self.path.as_path(), self.old.oid));
        let new = None;

        pretty_modification(header, &self.diff, old, new, repo, hi)
    }
}

impl ToPretty for Modified {
    type Output = term::VStack<'static>;
    type Context = FileHeader;

    fn pretty<R: Repo>(
        &self,
        hi: &mut Highlighter,
        header: &Self::Context,
        repo: &R,
    ) -> Self::Output {
        let old = Some((self.path.as_path(), self.old.oid));
        let new = Some((self.path.as_path(), self.new.oid));

        pretty_modification(header, &self.diff, old, new, repo, hi)
    }
}

impl ToPretty for Copied {
    type Output = term::VStack<'static>;
    type Context = FileHeader;

    fn pretty<R: Repo>(
        &self,
        hi: &mut Highlighter,
        _context: &Self::Context,
        repo: &R,
    ) -> Self::Output {
        let header = FileHeader::Copied {
            old_path: self.old_path.clone(),
            new_path: self.old_path.clone(),
        }
        .pretty(hi, &self.diff.stats().copied(), repo);

        term::VStack::default()
            .border(Some(term::colors::FAINT))
            .padding(1)
            .child(header)
    }
}

impl ToPretty for HunkHeader {
    type Output = term::Line;
    type Context = ();

    fn pretty<R: Repo>(
        &self,
        _hi: &mut Highlighter,
        _context: &Self::Context,
        _repo: &R,
    ) -> Self::Output {
        term::Line::spaced([
            term::label(format!(
                "@@ -{},{} +{},{} @@",
                self.old_line_no, self.old_size, self.new_line_no, self.new_size,
            ))
            .fg(term::colors::fixed::FAINT),
            term::label(String::from_utf8_lossy(&self.text).to_string())
                .fg(term::colors::fixed::DIM),
        ])
    }
}

impl ToPretty for Hunk<Modification> {
    type Output = term::VStack<'static>;
    type Context = Blobs<Vec<term::Line>>;

    fn pretty<R: Repo>(
        &self,
        hi: &mut Highlighter,
        blobs: &Self::Context,
        repo: &R,
    ) -> Self::Output {
        let mut vstack = term::VStack::default().padding(0);
        let mut table = term::Table::<5, term::Filled<term::Line>>::new(term::TableOptions {
            overflow: false,
            spacing: 0,
            border: None,
        });
        let theme = Theme::default();

        if let Ok(header) = HunkHeader::from_bytes(self.header.as_bytes()) {
            vstack.push(header.pretty(hi, &(), repo));
        }
        for line in &self.lines {
            match line {
                Modification::Addition(a) => {
                    table.push([
                        term::Label::space()
                            .pad(5)
                            .bg(theme.color("positive"))
                            .to_line()
                            .filled(theme.color("positive")),
                        term::label(a.line_no.to_string())
                            .pad(5)
                            .fg(theme.color("positive.light"))
                            .to_line()
                            .filled(theme.color("positive")),
                        term::label(" + ")
                            .fg(theme.color("positive.light"))
                            .to_line()
                            .filled(theme.color("positive.dark")),
                        line.pretty(hi, blobs, repo)
                            .filled(theme.color("positive.dark")),
                        term::Line::blank().filled(term::Color::default()),
                    ]);
                }
                Modification::Deletion(a) => {
                    table.push([
                        term::label(a.line_no.to_string())
                            .pad(5)
                            .fg(theme.color("negative.light"))
                            .to_line()
                            .filled(theme.color("negative")),
                        term::Label::space()
                            .pad(5)
                            .fg(theme.color("dim"))
                            .to_line()
                            .filled(theme.color("negative")),
                        term::label(" - ")
                            .fg(theme.color("negative.light"))
                            .to_line()
                            .filled(theme.color("negative.dark")),
                        line.pretty(hi, blobs, repo)
                            .filled(theme.color("negative.dark")),
                        term::Line::blank().filled(term::Color::default()),
                    ]);
                }
                Modification::Context {
                    line_no_old,
                    line_no_new,
                    ..
                } => {
                    table.push([
                        term::label(line_no_old.to_string())
                            .pad(5)
                            .fg(theme.color("dim"))
                            .to_line()
                            .filled(theme.color("faint")),
                        term::label(line_no_new.to_string())
                            .pad(5)
                            .fg(theme.color("dim"))
                            .to_line()
                            .filled(theme.color("faint")),
                        term::label("   ").to_line().filled(term::Color::default()),
                        line.pretty(hi, blobs, repo).filled(term::Color::default()),
                        term::Line::blank().filled(term::Color::default()),
                    ]);
                }
            }
        }
        vstack.push(table);
        vstack
    }
}

impl ToPretty for Modification {
    type Output = term::Line;
    type Context = Blobs<Vec<term::Line>>;

    fn pretty<R: Repo>(
        &self,
        _hi: &mut Highlighter,
        blobs: &Blobs<Vec<term::Line>>,
        _repo: &R,
    ) -> Self::Output {
        match self {
            Modification::Deletion(diff::Deletion { line, line_no }) => {
                if let Some(lines) = &blobs.old.as_ref() {
                    lines[*line_no as usize - 1].clone()
                } else {
                    term::Line::new(String::from_utf8_lossy(line.as_bytes()).as_ref())
                }
            }
            Modification::Addition(diff::Addition { line, line_no }) => {
                if let Some(lines) = &blobs.new.as_ref() {
                    lines[*line_no as usize - 1].clone()
                } else {
                    term::Line::new(String::from_utf8_lossy(line.as_bytes()).as_ref())
                }
            }
            Modification::Context {
                line, line_no_new, ..
            } => {
                // Nb. we can check in the old or the new blob, we choose the new.
                if let Some(lines) = &blobs.new.as_ref() {
                    lines[*line_no_new as usize - 1].clone()
                } else {
                    term::Line::new(String::from_utf8_lossy(line.as_bytes()).as_ref())
                }
            }
        }
    }
}

/// Render a file added, deleted or modified.
fn pretty_modification<R: Repo>(
    header: &FileHeader,
    diff: &DiffContent,
    old: Option<(&Path, Oid)>,
    new: Option<(&Path, Oid)>,
    repo: &R,
    hi: &mut Highlighter,
) -> VStack<'static> {
    let blobs = Blobs::from_paths(old, new, repo);
    let header = header.pretty(hi, &diff.stats().copied(), repo);
    let vstack = term::VStack::default()
        .border(Some(term::colors::FAINT))
        .padding(1)
        .child(header);

    let body = diff.pretty(hi, &blobs, repo);
    if body.is_empty() {
        vstack
    } else {
        vstack.divider().merge(body)
    }
}

#[cfg(test)]
mod test {
    use std::ffi::OsStr;

    use term::Constraint;
    use term::Element;

    use super::*;
    use radicle::git::raw::RepositoryOpenFlags;
    use radicle::git::raw::{Oid, Repository};

    #[test]
    #[ignore]
    fn test_pretty() {
        let repo = Repository::open_ext::<_, _, &[&OsStr]>(
            env!("CARGO_MANIFEST_DIR"),
            RepositoryOpenFlags::all(),
            &[],
        )
        .unwrap();
        let commit = repo
            .find_commit(Oid::from_str("5078396028e2ec5660aa54a00208f6e11df84aa9").unwrap())
            .unwrap();
        let parent = commit.parents().next().unwrap();
        let old_tree = parent.tree().unwrap();
        let new_tree = commit.tree().unwrap();
        let diff = repo
            .diff_tree_to_tree(Some(&old_tree), Some(&new_tree), None)
            .unwrap();
        let diff = Diff::try_from(diff).unwrap();

        let mut hi = Highlighter::default();
        let pretty = diff.pretty(&mut hi, &(), &repo);

        pretty
            .write(Constraint::from_env().unwrap_or_default())
            .unwrap();
    }
}