git-async 0.1.1

An async-first library for reading git repositories
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
//! A module for computing diffs between git trees
//!
//! # Usage
//!
//! First, construct a [`TreeDiff`] object, which walks the specified trees and
//! finds differing files. Then, use [`TreeDiff::to_text_diff`] to perform a
//! line-by-line diff on each differing file.
//!
//! # Example
//!
//! ```
//! # use git_async::{diff::{TreeDiff, Diff}, error::GResult, object::Tree, Repo, file_system::FileSystem};
//! async fn get_diff<F: FileSystem>(repo: &Repo<F>, left: &Tree, right: &Tree) -> GResult<Diff> {
//!     let tree_diff = TreeDiff::new(repo, left, right).await?;
//!     tree_diff.to_text_diff(repo).await
//! }
//! ```
//!
//! # Notes
//!
//! This algorithm is relatively naive, in that it simply loads each object in
//! full and then computes their diff. You will find that using `git diff` on
//! the command line is much faster. This is likely because because `git diff`
//! may be aware of the packfile delta encoding and may use it to compute
//! efficient diffs.

use crate::{
    Repo,
    error::{Error, GResult},
    file_system::FileSystem,
    object::{Object, ObjectId, Tree, TreeEntry, TreeEntryType},
};
use accessory::Accessors;
use alloc::format;
use alloc::{string::String, vec::Vec};
use core::convert::Infallible;
use similar::{TextDiff, TextDiffConfig};

/// A path for a file in a diff
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct Path(Vec<u8>);

impl core::fmt::Debug for Path {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match str::from_utf8(&self.0) {
            Ok(p) => f.debug_tuple("Path").field(&p).finish(),
            Err(_) => f
                .debug_tuple("Path")
                .field(&String::from_utf8_lossy(&self.0))
                .finish(),
        }
    }
}

impl Path {
    /// View the path as a slice of bytes
    pub fn as_slice(&self) -> &[u8] {
        self.0.as_slice()
    }

    /// Consume the path and return its inner [`Vec<u8>`]
    pub fn inner(self) -> Vec<u8> {
        self.0
    }
}

fn join(path: Option<&Path>, component: &[u8]) -> Path {
    match path {
        Some(p) => {
            let mut out = Vec::with_capacity(p.0.len() + 1 + component.len());
            out.extend_from_slice(&p.0);
            out.push(b'/');
            out.extend_from_slice(component);
            Path(out)
        }
        None => Path(component.to_vec()),
    }
}

/// Represents a diff of a single file
///
/// It is generic over the content of the file diff. For tree diffs, `Content`
/// is a pair of [`ObjectId`]s, one of which may be zero. For full diffs,
/// `Content` is a `similar::TextDiff`.
#[expect(missing_docs)]
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub enum DiffEntry<Content> {
    LeftOnly {
        path: Path,
        entry_type: TreeEntryType,
        content: Content,
    },
    Both {
        path: Path,
        left_type: TreeEntryType,
        right_type: TreeEntryType,
        content: Content,
    },
    RightOnly {
        path: Path,
        entry_type: TreeEntryType,
        content: Content,
    },
}

impl<Content> DiffEntry<Content> {
    /// The content of the diff entry
    pub fn content(&self) -> &Content {
        match self {
            DiffEntry::LeftOnly { content, .. }
            | DiffEntry::Both { content, .. }
            | DiffEntry::RightOnly { content, .. } => content,
        }
    }

    /// The path of the file that the entry represents
    pub fn path(&self) -> &Path {
        match self {
            DiffEntry::LeftOnly { path, .. }
            | DiffEntry::Both { path, .. }
            | DiffEntry::RightOnly { path, .. } => path,
        }
    }

    /// Map a function over the content contained in the entry.
    pub fn map_content<T>(&self, fun: impl Fn(&Content) -> T) -> DiffEntry<T> {
        self.map_content_res(|c| Ok::<T, Infallible>(fun(c)))
            .unwrap()
    }

    /// Map a fallible function over the content contained in the entry.
    pub fn map_content_res<T, E>(
        &self,
        fun: impl Fn(&Content) -> Result<T, E>,
    ) -> Result<DiffEntry<T>, E> {
        use DiffEntry::*;
        Ok(match self {
            LeftOnly {
                path,
                entry_type,
                content,
            } => DiffEntry::LeftOnly {
                path: path.clone(),
                entry_type: *entry_type,
                content: fun(content)?,
            },
            Both {
                path,
                left_type,
                right_type,
                content,
            } => DiffEntry::Both {
                path: path.clone(),
                left_type: *left_type,
                right_type: *right_type,
                content: fun(content)?,
            },
            RightOnly {
                path,
                entry_type,
                content,
            } => DiffEntry::RightOnly {
                path: path.clone(),
                entry_type: *entry_type,
                content: fun(content)?,
            },
        })
    }
}

/// A "full" diff, i.e. one which encapsulates line changes between files
///
/// This is constructed by first creating a [`TreeDiff`] object and then calling
/// the [`TreeDiff::to_text_diff`] method.
#[derive(Accessors)]
pub struct Diff {
    /// The entries of the diff, one per differing path in the tree
    #[access(get(ty(&[DiffEntry<TextDiff<'static, 'static, [u8]>>])))]
    entries: Vec<DiffEntry<TextDiff<'static, 'static, [u8]>>>,
}

/// A diff of git trees, holding the [`ObjectId`]s of differing files
#[derive(Accessors)]
pub struct TreeDiff {
    /// The entries of the diff, one per differing path in the tree
    #[access(get(ty(&[DiffEntry<(ObjectId, ObjectId)>])))]
    entries: Vec<DiffEntry<(ObjectId, ObjectId)>>,
}

impl TreeDiff {
    /// Construct a [`TreeDiff`] by diffing two trees
    pub async fn new<F: FileSystem>(repo: &Repo<F>, left: &Tree, right: &Tree) -> GResult<Self> {
        Self::new_cancelable(repo, left, right, async || false).await
    }

    /// Construct a [`TreeDiff`] by diffing two trees
    ///
    /// The `cancel` parameter is a function which may cancel the diff operation
    /// by returning `true` at any point. It is called regularly while the diff
    /// operation is running.
    ///
    /// For example,
    /// ```
    /// # use git_async::{diff::TreeDiff, error::GResult, object::Tree, Repo, file_system::FileSystem};
    /// # use std::rc::Rc;
    /// # use core::cell::Cell;
    /// struct CancelableDiffFactory { canceled: Rc<Cell<bool>> }
    /// impl CancelableDiffFactory {
    ///     pub async fn make_diff<F: FileSystem>(
    ///         &self,
    ///         repo: &Repo<F>,
    ///         left: &Tree,
    ///         right: &Tree
    ///     ) -> GResult<TreeDiff> {
    ///         let canceled = self.canceled.clone();
    ///         let cancel = async move || canceled.get();
    ///         TreeDiff::new_cancelable(repo, left, right, cancel).await
    ///     }
    ///
    ///     pub fn cancel(&self) {
    ///         self.canceled.set(true);
    ///     }
    /// }
    /// ```
    ///
    /// In this example, a diff operation may be started by some async routine,
    /// and then canceled by another by calling the
    /// `CancelableDiffFactory::cancel` method.
    #[allow(clippy::too_many_lines)]
    pub async fn new_cancelable<F: FileSystem>(
        repo: &Repo<F>,
        left: &Tree,
        right: &Tree,
        mut cancel: impl AsyncFnMut() -> bool,
    ) -> GResult<Self> {
        if left.id() == right.id() {
            return Ok(Self {
                entries: Vec::new(),
            });
        }
        let mut out: Vec<DiffEntry<(ObjectId, ObjectId)>> = Vec::new();
        #[allow(clippy::type_complexity)]
        let mut stack: Vec<(Option<Path>, Option<Tree>, Option<Tree>)> = Vec::new();
        stack.push((None, Some(left.clone()), Some(right.clone())));

        while let Some((parent_path, left, right)) = stack.pop() {
            // Loop invariants:
            // - one of left or right is Some()
            // - left and right have different IDs
            debug_assert!(left.is_some() || right.is_some());
            debug_assert!(left.as_ref().map(Tree::id) != right.as_ref().map(Tree::id));
            if cancel().await {
                return Err(Error::DiffCanceled);
            }
            let (left, right) = match (left, right) {
                (Some(left), Some(right)) => (left, right),
                (Some(left), None) => {
                    for entry in left.entries() {
                        let path = join(parent_path.as_ref(), entry.name());
                        if entry.entry_type() == TreeEntryType::Tree {
                            let tree = tree(repo, entry.id()).await?;
                            stack.push((Some(path), None, Some(tree)));
                        } else {
                            out.push(DiffEntry::LeftOnly {
                                path,
                                entry_type: entry.entry_type(),
                                content: (entry.id(), ObjectId::zero()),
                            });
                        }
                    }
                    continue;
                }
                (None, Some(right)) => {
                    for entry in right.entries() {
                        let path = join(parent_path.as_ref(), entry.name());
                        if entry.entry_type() == TreeEntryType::Tree {
                            let tree = tree(repo, entry.id()).await?;
                            stack.push((Some(path), None, Some(tree)));
                        } else {
                            out.push(DiffEntry::RightOnly {
                                path,
                                entry_type: entry.entry_type(),
                                content: (ObjectId::zero(), entry.id()),
                            });
                        }
                    }
                    continue;
                }
                (None, None) => unreachable!(),
            };

            let mut left_only: Vec<TreeEntry> = Vec::new();
            let mut right_only: Vec<TreeEntry> = Vec::new();
            let mut both: Vec<(TreeEntry, TreeEntry)> = Vec::new();
            for left_entry in left.entries() {
                let right_entry = right.entries().find(|e| e.name() == left_entry.name());
                match right_entry {
                    Some(e) => both.push((left_entry, e)),
                    None => left_only.push(left_entry),
                }
            }
            for right_entry in right.entries() {
                if both
                    .iter()
                    .find(|(_, e)| e.name() == right_entry.name())
                    .is_none()
                {
                    right_only.push(right_entry);
                }
            }
            for entry in left_only {
                let path = join(parent_path.as_ref(), entry.name());
                if entry.entry_type() == TreeEntryType::Tree {
                    let left_tree = tree(repo, entry.id()).await?;
                    stack.push((Some(path), Some(left_tree), None));
                } else {
                    out.push(DiffEntry::LeftOnly {
                        path,
                        entry_type: entry.entry_type(),
                        content: (entry.id(), ObjectId::zero()),
                    });
                }
            }
            for entry in right_only {
                let path = join(parent_path.as_ref(), entry.name());
                if entry.entry_type() == TreeEntryType::Tree {
                    let right_tree = tree(repo, entry.id()).await?;
                    stack.push((Some(path), None, Some(right_tree)));
                } else {
                    out.push(DiffEntry::RightOnly {
                        path,
                        entry_type: entry.entry_type(),
                        content: (ObjectId::zero(), entry.id()),
                    });
                }
            }
            for (left, right) in both {
                if left.id() == right.id() {
                    continue;
                }
                let name = left.name();
                match (left.entry_type(), right.entry_type()) {
                    (TreeEntryType::Tree, TreeEntryType::Tree) => {
                        let left = tree(repo, left.id()).await?;
                        let right = tree(repo, right.id()).await?;
                        let path = join(parent_path.as_ref(), name);
                        stack.push((Some(path), Some(left), Some(right)));
                    }
                    (TreeEntryType::Tree, _) => {
                        let path = join(parent_path.as_ref(), name);
                        out.push(DiffEntry::RightOnly {
                            path: path.clone(),
                            entry_type: right.entry_type(),
                            content: (ObjectId::zero(), right.id()),
                        });
                        let left_tree = tree(repo, left.id()).await?;
                        stack.push((Some(path), Some(left_tree), None));
                    }
                    (_, TreeEntryType::Tree) => {
                        let path = join(parent_path.as_ref(), name);
                        out.push(DiffEntry::LeftOnly {
                            path: path.clone(),
                            entry_type: left.entry_type(),
                            content: (left.id(), ObjectId::zero()),
                        });
                        let right_tree = tree(repo, right.id()).await?;
                        stack.push((Some(path), None, Some(right_tree)));
                    }
                    _ => {
                        out.push(DiffEntry::Both {
                            path: join(parent_path.as_ref(), name),
                            left_type: left.entry_type(),
                            right_type: right.entry_type(),
                            content: (left.id(), right.id()),
                        });
                    }
                }
            }
        }
        Ok(Self { entries: out })
    }

    /// Turn the [`TreeDiff`] into a [`Diff`] by creating a line diff of each
    /// file.
    pub async fn to_text_diff<F: FileSystem>(&self, repo: &Repo<F>) -> GResult<Diff> {
        self.to_text_diff_full(repo, &TextDiffConfig::default(), async || false)
            .await
    }

    /// Like [`TreeDiff::to_text_diff`] but accepts a
    /// [`similar::TextDiffConfig`] parameter to configure the file diff
    /// operations and a `cancel` parameter to externally cancel the diff.
    ///
    /// The `cancel` parameter is analogous to the `cancel` parameter on
    /// [`TreeDiff::new_cancelable`]; see there for further details.
    pub async fn to_text_diff_full<F: FileSystem>(
        &self,
        repo: &Repo<F>,
        config: &TextDiffConfig,
        mut cancel: impl AsyncFnMut() -> bool,
    ) -> GResult<Diff> {
        let mut out: Vec<_> = Vec::with_capacity(self.entries.len());
        for entry in &self.entries {
            if cancel().await {
                return Err(Error::DiffCanceled);
            }
            let entry = entry.resolve(repo, config.clone()).await?;
            out.push(entry);
        }
        Ok(Diff { entries: out })
    }
}

async fn tree<F: FileSystem>(repo: &Repo<F>, id: ObjectId) -> GResult<Tree> {
    repo.lookup_object(id)
        .await?
        .peel_to_tree(repo)
        .await?
        .ok_or_else(|| Error::MalformedObject(id))
}

impl DiffEntry<(ObjectId, ObjectId)> {
    /// Look up the objects encoded in the diff entry and compute a diff of the
    /// files.
    pub async fn resolve<F: FileSystem>(
        &self,
        repo: &Repo<F>,
        config: TextDiffConfig,
    ) -> GResult<DiffEntry<TextDiff<'static, 'static, [u8]>>> {
        match self {
            DiffEntry::LeftOnly {
                path,
                entry_type,
                content: (id, _),
            } => {
                let body = read_leaf(repo, *entry_type, *id).await?;
                Ok(DiffEntry::LeftOnly {
                    path: path.clone(),
                    entry_type: *entry_type,
                    content: config.diff_lines(body, Vec::new()),
                })
            }
            DiffEntry::RightOnly {
                path,
                entry_type,
                content: (_, id),
            } => {
                let body = read_leaf(repo, *entry_type, *id).await?;
                Ok(DiffEntry::RightOnly {
                    path: path.clone(),
                    entry_type: *entry_type,
                    content: config.diff_lines(Vec::new(), body),
                })
            }
            DiffEntry::Both {
                path,
                left_type,
                right_type,
                content: (left_id, right_id),
            } => {
                let left_body = read_leaf(repo, *left_type, *left_id).await?;
                let right_body = read_leaf(repo, *right_type, *right_id).await?;
                let diff = config.diff_lines(left_body, right_body);
                Ok(DiffEntry::Both {
                    path: path.clone(),
                    left_type: *left_type,
                    right_type: *right_type,
                    content: diff,
                })
            }
        }
    }
}

async fn read_leaf<F: FileSystem>(
    repo: &Repo<F>,
    entry_type: TreeEntryType,
    id: ObjectId,
) -> GResult<Vec<u8>> {
    debug_assert!(entry_type != TreeEntryType::Tree);
    if entry_type == TreeEntryType::Commit {
        let s = format!("{id}");
        return Ok(s.into_bytes());
    }
    let object = repo.lookup_object(id).await?;
    if let Object::Blob(b) = object {
        return Ok(b.data_owned());
    }
    unreachable!("Tree entry resolved object was not a blob")
}

#[cfg(test)]
mod tests {
    use crate::{
        Repo,
        reference::RefName,
        test::{
            helpers::{make_basic_repo, make_file},
            impls::TestFileSystem,
        },
    };
    use futures::executor::block_on;
    use std::{
        collections::BTreeSet,
        fs::{create_dir, remove_file},
        io::Write,
        path::PathBuf,
    };

    use super::*;

    fn head_tree(repo: &Repo<TestFileSystem>) -> Tree {
        let head = block_on(repo.lookup_ref(&RefName::Head)).unwrap();
        block_on(head.peel_to_tree(repo)).unwrap().unwrap()
    }

    #[test]
    fn diff_same() {
        let test_repo = make_basic_repo().unwrap();
        let repo = test_repo.repo();
        let tree = head_tree(&repo);
        assert!(
            block_on(TreeDiff::new(&repo, &tree, &tree))
                .unwrap()
                .entries()
                .is_empty()
        );
    }

    #[test]
    fn basic_root_diff() {
        let test_repo = make_basic_repo().unwrap();
        let repo = test_repo.repo();
        let mut file_a = make_file(&test_repo, "a").unwrap();
        test_repo.run_git(["add", "--all"]).unwrap();
        test_repo
            .commit("a commit", "a user", "an-email", "2000-01-01T00:00:00Z")
            .unwrap();
        let before = head_tree(&repo);
        file_a.write_all(b"some data").unwrap();
        file_a.flush().unwrap();
        let mut file_b = make_file(&test_repo, "b").unwrap();
        file_b.write_all(b"some more data").unwrap();
        test_repo.run_git(["add", "--all"]).unwrap();
        test_repo
            .commit("a commit", "a user", "an-email", "2000-01-01T00:00:00Z")
            .unwrap();
        let after = head_tree(&repo);
        let the_diff = block_on(TreeDiff::new(&repo, &before, &after))
            .unwrap()
            .entries()
            .iter()
            .map(Clone::clone)
            .collect::<BTreeSet<_>>();
        assert_eq!(
            the_diff,
            vec![
                DiffEntry::Both {
                    path: Path(b"a".to_vec()),
                    left_type: TreeEntryType::File,
                    right_type: TreeEntryType::File,
                    content: (
                        ObjectId::from_hex(b"e69de29bb2d1d6434b8b29ae775ad8c2e48c5391").unwrap(),
                        ObjectId::from_hex(b"7c0646bfd53c1f0ed45ffd81563f30017717ca58").unwrap(),
                    ),
                },
                DiffEntry::RightOnly {
                    path: Path(b"b".to_vec()),
                    entry_type: TreeEntryType::File,
                    content: (
                        ObjectId::zero(),
                        ObjectId::from_hex(b"dfa37ec69ffae3abcf7efbb386226cb84b510fa8").unwrap()
                    )
                }
            ]
            .into_iter()
            .collect()
        );
        let the_diff = block_on(TreeDiff::new(&repo, &after, &before))
            .unwrap()
            .entries()
            .iter()
            .map(Clone::clone)
            .collect::<BTreeSet<_>>();
        assert_eq!(
            the_diff,
            vec![
                DiffEntry::Both {
                    path: Path(b"a".to_vec()),
                    left_type: TreeEntryType::File,
                    right_type: TreeEntryType::File,
                    content: (
                        ObjectId::from_hex(b"7c0646bfd53c1f0ed45ffd81563f30017717ca58").unwrap(),
                        ObjectId::from_hex(b"e69de29bb2d1d6434b8b29ae775ad8c2e48c5391").unwrap(),
                    ),
                },
                DiffEntry::LeftOnly {
                    path: Path(b"b".to_vec()),
                    entry_type: TreeEntryType::File,
                    content: (
                        ObjectId::from_hex(b"dfa37ec69ffae3abcf7efbb386226cb84b510fa8").unwrap(),
                        ObjectId::zero()
                    )
                }
            ]
            .into_iter()
            .collect()
        );
    }

    #[test]
    fn basic_subtree_diff() {
        let test_repo = make_basic_repo().unwrap();
        let repo = test_repo.repo();
        create_dir(test_repo.location.path().join("dir")).unwrap();
        let mut file_a = make_file(&test_repo, PathBuf::from("dir").join("a")).unwrap();
        test_repo.run_git(["add", "--all"]).unwrap();
        test_repo
            .commit("a commit", "a user", "an-email", "2000-01-01T00:00:00Z")
            .unwrap();
        let before = head_tree(&repo);
        file_a.write_all(b"some data").unwrap();
        file_a.flush().unwrap();
        test_repo.run_git(["add", "--all"]).unwrap();
        test_repo
            .commit("a commit", "a user", "an-email", "2000-01-01T00:00:00Z")
            .unwrap();
        let after = head_tree(&repo);
        let the_diff = block_on(TreeDiff::new(&repo, &before, &after))
            .unwrap()
            .entries()
            .iter()
            .map(Clone::clone)
            .collect::<BTreeSet<_>>();
        assert_eq!(
            the_diff,
            vec![DiffEntry::Both {
                path: Path(b"dir/a".to_vec()),
                left_type: TreeEntryType::File,
                right_type: TreeEntryType::File,
                content: (
                    ObjectId::from_hex(b"e69de29bb2d1d6434b8b29ae775ad8c2e48c5391").unwrap(),
                    ObjectId::from_hex(b"7c0646bfd53c1f0ed45ffd81563f30017717ca58").unwrap(),
                )
            },]
            .into_iter()
            .collect()
        );
        let the_diff = block_on(TreeDiff::new(&repo, &after, &before))
            .unwrap()
            .entries()
            .iter()
            .map(Clone::clone)
            .collect::<BTreeSet<_>>();
        assert_eq!(
            the_diff,
            vec![DiffEntry::Both {
                path: Path(b"dir/a".to_vec()),
                left_type: TreeEntryType::File,
                right_type: TreeEntryType::File,
                content: (
                    ObjectId::from_hex(b"7c0646bfd53c1f0ed45ffd81563f30017717ca58").unwrap(),
                    ObjectId::from_hex(b"e69de29bb2d1d6434b8b29ae775ad8c2e48c5391").unwrap(),
                ),
            },]
            .into_iter()
            .collect()
        );
    }

    #[test]
    fn complex_subtree_diff() {
        let test_repo = make_basic_repo().unwrap();
        let repo = test_repo.repo();
        make_file(&test_repo, "a").unwrap();
        test_repo.run_git(["add", "--all"]).unwrap();
        test_repo
            .commit("a commit", "a user", "an-email", "2000-01-01T00:00:00Z")
            .unwrap();
        let before = head_tree(&repo);
        remove_file(test_repo.location.path().join("a")).unwrap();
        create_dir(test_repo.location.path().join("a")).unwrap();
        make_file(&test_repo, PathBuf::from("a").join("b")).unwrap();
        create_dir(test_repo.location.path().join("dir")).unwrap();
        make_file(&test_repo, PathBuf::from("dir").join("c")).unwrap();
        test_repo.run_git(["add", "--all"]).unwrap();
        test_repo
            .commit("a commit", "a user", "an-email", "2000-01-01T00:00:00Z")
            .unwrap();
        let after = head_tree(&repo);
        let the_diff = block_on(TreeDiff::new(&repo, &before, &after))
            .unwrap()
            .entries()
            .iter()
            .map(Clone::clone)
            .collect::<BTreeSet<_>>();
        assert_eq!(
            the_diff,
            vec![
                DiffEntry::RightOnly {
                    path: Path(b"a/b".to_vec()),
                    entry_type: TreeEntryType::File,
                    content: (
                        ObjectId::zero(),
                        ObjectId::from_hex(b"e69de29bb2d1d6434b8b29ae775ad8c2e48c5391").unwrap(),
                    )
                },
                DiffEntry::LeftOnly {
                    path: Path(b"a".to_vec()),
                    entry_type: TreeEntryType::File,
                    content: (
                        ObjectId::from_hex(b"e69de29bb2d1d6434b8b29ae775ad8c2e48c5391").unwrap(),
                        ObjectId::zero()
                    )
                },
                DiffEntry::RightOnly {
                    path: Path(b"dir/c".to_vec()),
                    entry_type: TreeEntryType::File,
                    content: (
                        ObjectId::zero(),
                        ObjectId::from_hex(b"e69de29bb2d1d6434b8b29ae775ad8c2e48c5391").unwrap(),
                    )
                },
            ]
            .into_iter()
            .collect()
        );
        let the_diff = block_on(TreeDiff::new(&repo, &after, &before))
            .unwrap()
            .entries()
            .iter()
            .map(Clone::clone)
            .collect::<BTreeSet<_>>();
        assert_eq!(
            the_diff,
            vec![
                DiffEntry::LeftOnly {
                    path: Path(b"a/b".to_vec()),
                    entry_type: TreeEntryType::File,
                    content: (
                        ObjectId::from_hex(b"e69de29bb2d1d6434b8b29ae775ad8c2e48c5391").unwrap(),
                        ObjectId::zero()
                    )
                },
                DiffEntry::RightOnly {
                    path: Path(b"a".to_vec()),
                    entry_type: TreeEntryType::File,
                    content: (
                        ObjectId::zero(),
                        ObjectId::from_hex(b"e69de29bb2d1d6434b8b29ae775ad8c2e48c5391").unwrap(),
                    )
                },
                DiffEntry::LeftOnly {
                    path: Path(b"dir/c".to_vec()),
                    entry_type: TreeEntryType::File,
                    content: (
                        ObjectId::from_hex(b"e69de29bb2d1d6434b8b29ae775ad8c2e48c5391").unwrap(),
                        ObjectId::zero()
                    )
                },
            ]
            .into_iter()
            .collect()
        );
    }
}