Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 4.9 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! The round trip: git to braid and back, compared object by object.
5
6use std::collections::{BTreeMap, HashSet};
7use std::path::Path;
8
9use braid_format::MemoryObjects;
10
11use crate::error::Error;
12use crate::export::{RefTarget, RefUpdate, reached, write_to_repo};
13use crate::import::{ImportOptions, import};
14use crate::map::GitMap;
15use crate::oid::{GitKind, GitOid};
16use crate::repo::GitRepo;
17
18/// What a round trip compared.
19#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
20pub struct RoundTripReport {
21 /// Commits, identical on both sides.
22 pub commits: usize,
23 /// Trees, identical on both sides.
24 pub trees: usize,
25 /// Of those trees, the ones the export kept as raw bytes.
26 pub raw_trees: usize,
27 /// Blobs, identical on both sides.
28 pub blobs: usize,
29 /// Annotated tags, identical on both sides.
30 pub tags: usize,
31 /// Refs pointing to the same objects on both sides.
32 pub refs: usize,
33}
34
35/// Imports every branch and tag of `src_repo` into memory, exports
36/// everything into a fresh bare repository under `tmp_dir`, and checks that
37/// both repositories hold exactly the same commits, trees, blobs and tags,
38/// with the same ids, and the same refs.
39///
40/// The refs are read once, at import, so commits added to the source while
41/// the round trip runs do not disturb it. Every object read on either side is
42/// checked to hash to its id.
43pub fn verify_round_trip(src_repo: &Path, tmp_dir: &Path) -> Result<RoundTripReport, Error> {
44 verify_round_trip_with(src_repo, tmp_dir, &ImportOptions::default())
45}
46
47/// [`verify_round_trip`] for the refs that `options` selects, such as `HEAD`
48/// in a checkout without branches.
49pub fn verify_round_trip_with(
50 src_repo: &Path,
51 tmp_dir: &Path,
52 options: &ImportOptions,
53) -> Result<RoundTripReport, Error> {
54 let objects = MemoryObjects::new();
55 let mut map = GitMap::new();
56 let imported = import(src_repo, &objects, &mut map, options)?;
57
58 let copy_path = tmp_dir.join("round-trip.git");
59 GitRepo::init_bare(&copy_path)?;
60 let updates: Vec<RefUpdate> = imported
61 .refs
62 .iter()
63 .map(|r| RefUpdate {
64 name: r.name.clone(),
65 target: RefTarget::Git(r.oid),
66 })
67 .collect();
68 write_to_repo(&copy_path, &objects, &map, &updates)?;
69
70 let source = GitRepo::open(src_repo)?;
71 let copy = GitRepo::open(&copy_path)?;
72 let tips: Vec<GitOid> = imported.refs.iter().map(|r| r.oid).collect();
73 let expected = reachable(&source, &tips)?;
74 let found = reachable(&copy, &tips)
75 .map_err(|err| Error::RoundTrip(format!("the copy is incomplete: {err}")))?;
76 if expected != found {
77 return Err(Error::RoundTrip(describe_difference(&expected, &found)));
78 }
79 for r in &imported.refs {
80 let target = copy.resolve_ref(&r.name)?;
81 if target != Some(r.oid) {
82 return Err(Error::RoundTrip(format!(
83 "ref {} points to {target:?} in the copy, {} in the source",
84 String::from_utf8_lossy(&r.name),
85 r.oid
86 )));
87 }
88 }
89
90 let mut report = RoundTripReport {
91 refs: imported.refs.len(),
92 raw_trees: map.counts().raw_trees,
93 ..RoundTripReport::default()
94 };
95 for kind in expected.values() {
96 match kind {
97 GitKind::Commit => report.commits += 1,
98 GitKind::Tree => report.trees += 1,
99 GitKind::Blob => report.blobs += 1,
100 GitKind::Tag => report.tags += 1,
101 }
102 }
103 Ok(report)
104}
105
106/// Every object reachable from `tips`, with its kind. Submodule commits are
107/// not followed: they live in another repository.
108fn reachable(repo: &GitRepo, tips: &[GitOid]) -> Result<BTreeMap<GitOid, GitKind>, Error> {
109 let mut found = BTreeMap::new();
110 let mut queued: HashSet<GitOid> = tips.iter().copied().collect();
111 let mut pending: Vec<GitOid> = tips.to_vec();
112 while let Some(oid) = pending.pop() {
113 let (kind, bytes) = repo.read(&oid)?;
114 for next in reached(oid, kind, &bytes)? {
115 if queued.insert(next) {
116 pending.push(next);
117 }
118 }
119 found.insert(oid, kind);
120 }
121 Ok(found)
122}
123
124fn describe_difference(
125 expected: &BTreeMap<GitOid, GitKind>,
126 found: &BTreeMap<GitOid, GitKind>,
127) -> String {
128 let missing: Vec<String> = expected
129 .iter()
130 .filter(|(oid, kind)| found.get(oid) != Some(kind))
131 .take(5)
132 .map(|(oid, kind)| format!("{kind} {oid}"))
133 .collect();
134 let extra: Vec<String> = found
135 .iter()
136 .filter(|(oid, kind)| expected.get(oid) != Some(kind))
137 .take(5)
138 .map(|(oid, kind)| format!("{kind} {oid}"))
139 .collect();
140 format!(
141 "{} objects in the source, {} in the copy; missing from the copy: [{}]; only in the copy: [{}]",
142 expected.len(),
143 found.len(),
144 missing.join(", "),
145 extra.join(", ")
146 )
147}