Elffuss BraidHub

utopia-ia/elffuss-braid public

bceec3f3d91e · 25.1 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! Export: braid objects back to git objects, and into a git repository.
5
6use std::collections::{HashMap, HashSet};
7use std::fmt;
8use std::path::Path;
9use std::sync::Arc;
10
11use braid_format::{Changeset, Entry, EntryKind, GitId, Kind, ObjectId, Objects};
12
13use crate::error::Error;
14use crate::fetch::{self, TreeCache};
15use crate::map::{GitMap, Pairings};
16use crate::oid::{GitKind, GitOid};
17use crate::raw::{self, EntryType, TreeItem};
18use crate::repo::GitRepo;
19
20/// Produces git objects from braid objects.
21///
22/// What came from git goes back byte for byte: a changeset with a git origin
23/// is exported as its original commit, after checking that the tree and the
24/// parents the commit names are the ones the map links to the changeset; a
25/// git tree that is not canonical as its raw bytes; a tag as its raw bytes.
26///
27/// Everything else is generated deterministically from braid content alone:
28/// a tree with canonical modes and git's entry order, a commit with `tree`,
29/// `parent`, `author` and `committer` headers, one header per extra, and the
30/// message unchanged.
31///
32/// An exporter caches the git ids it computes, so exporting many related
33/// objects through one exporter does each piece of work once. Nothing is
34/// recursive: deep histories and deep directories are walked with explicit
35/// stacks. What it computed that the map does not know yet is available from
36/// [`pairings`](Self::pairings), to record in the map.
37pub struct Exporter<'a, O: Objects> {
38 objects: &'a O,
39 map: &'a GitMap,
40 /// Canonical git trees computed here, for braid trees the map does not
41 /// link to one, and back.
42 trees: HashMap<ObjectId, GitOid>,
43 tree_sources: HashMap<GitOid, ObjectId>,
44 /// Git blobs computed here, with their sizes, and back.
45 blobs: HashMap<ObjectId, (GitOid, u64)>,
46 blob_sources: HashMap<GitOid, ObjectId>,
47 /// Commits exported here, and back.
48 commits: HashMap<ObjectId, GitOid>,
49 commit_sources: HashMap<GitOid, ObjectId>,
50 /// Directories read back already, shared with whoever made this
51 /// exporter, if anyone.
52 cache: Option<&'a TreeCache>,
53}
54
55impl<O: Objects> fmt::Debug for Exporter<'_, O> {
56 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57 f.debug_struct("Exporter")
58 .field("computed_trees", &self.trees.len())
59 .field("computed_blobs", &self.blobs.len())
60 .field("computed_commits", &self.commits.len())
61 .finish_non_exhaustive()
62 }
63}
64
65impl<'a, O: Objects> Exporter<'a, O> {
66 /// An exporter reading braid objects from `objects`, with what `map`
67 /// knows about imported git objects.
68 pub fn new(objects: &'a O, map: &'a GitMap) -> Self {
69 Self {
70 objects,
71 map,
72 trees: HashMap::new(),
73 tree_sources: HashMap::new(),
74 blobs: HashMap::new(),
75 blob_sources: HashMap::new(),
76 commits: HashMap::new(),
77 commit_sources: HashMap::new(),
78 cache: None,
79 }
80 }
81
82 /// An exporter that reads directories through `cache`, and keeps what it
83 /// reads there.
84 pub(crate) fn with_cache(objects: &'a O, map: &'a GitMap, cache: &'a TreeCache) -> Self {
85 Self {
86 cache: Some(cache),
87 ..Self::new(objects, map)
88 }
89 }
90
91 /// Every entry of a braid directory.
92 fn entries(&self, tree: ObjectId) -> Result<Arc<[Entry]>, Error> {
93 match self.cache {
94 Some(cache) => cache.entries(self.objects, tree),
95 None => Ok(fetch::tree_entries(self.objects, tree)?.into()),
96 }
97 }
98
99 /// Every pairing this exporter computed that its map does not hold: the
100 /// commits of the changesets it exported, and the canonical trees and
101 /// the blobs it generated. [`GitMap::record`] adds them to a map, so that
102 /// importing these git objects later gives back the same braid objects.
103 pub fn pairings(&self) -> Pairings {
104 let mut commits: Vec<(GitOid, ObjectId)> = self
105 .commits
106 .iter()
107 .filter(|(changeset, _)| self.map.commit(changeset).is_none())
108 .map(|(changeset, oid)| (*oid, *changeset))
109 .collect();
110 let mut trees: Vec<(GitOid, ObjectId)> = self
111 .trees
112 .iter()
113 .filter(|(tree, _)| self.map.git_tree(tree).is_none())
114 .map(|(tree, oid)| (*oid, *tree))
115 .collect();
116 let mut blobs: Vec<(GitOid, ObjectId, u64)> = self
117 .blobs
118 .iter()
119 .filter(|(blob, _)| self.map.git_blob(blob).is_none())
120 .map(|(blob, (oid, size))| (*oid, *blob, *size))
121 .collect();
122 commits.sort_unstable();
123 trees.sort_unstable();
124 blobs.sort_unstable();
125 Pairings {
126 commits,
127 trees,
128 blobs,
129 }
130 }
131
132 /// The git commit of a changeset: its id and its bytes.
133 pub fn commit(&mut self, changeset: &ObjectId) -> Result<(GitOid, Vec<u8>), Error> {
134 let decoded = fetch::changeset(self.objects, changeset)?;
135 self.commit_of(changeset, &decoded)
136 }
137
138 /// The git id of a changeset's commit. Ancestors that were not imported
139 /// from git are exported first, parents before children.
140 pub fn commit_id(&mut self, changeset: &ObjectId) -> Result<GitOid, Error> {
141 if let Some(oid) = self.known_commit(changeset) {
142 return Ok(oid);
143 }
144 let mut stack = vec![(*changeset, fetch::changeset(self.objects, changeset)?)];
145 while let Some((id, decoded)) = stack.pop() {
146 if self.known_commit(&id).is_some() {
147 continue;
148 }
149 // A commit from git names its parents itself; a generated one
150 // needs theirs first.
151 let waiting = match decoded.git_origin {
152 Some(_) => None,
153 None => decoded
154 .parents
155 .iter()
156 .find(|parent| self.known_commit(parent).is_none())
157 .copied(),
158 };
159 match waiting {
160 Some(parent) => {
161 let parent_changeset = fetch::changeset(self.objects, &parent)?;
162 stack.push((id, decoded));
163 stack.push((parent, parent_changeset));
164 }
165 None => {
166 self.commit_of(&id, &decoded)?;
167 }
168 }
169 }
170 self.known_commit(changeset)
171 .ok_or_else(|| Error::NotMapped {
172 what: "changeset",
173 id: changeset.to_hex(),
174 })
175 }
176
177 fn known_commit(&self, changeset: &ObjectId) -> Option<GitOid> {
178 self.map
179 .commit(changeset)
180 .or_else(|| self.commits.get(changeset).copied())
181 }
182
183 fn commit_of(
184 &mut self,
185 id: &ObjectId,
186 changeset: &Changeset,
187 ) -> Result<(GitOid, Vec<u8>), Error> {
188 let (oid, bytes) = match &changeset.git_origin {
189 Some(origin) => self.origin_commit(id, changeset, origin)?,
190 None => {
191 let mut parents = Vec::with_capacity(changeset.parents.len());
192 for parent in &changeset.parents {
193 parents.push(self.commit_id(parent)?);
194 }
195 let tree = self.tree_id(&changeset.root)?;
196 let bytes = raw::encode_commit(
197 tree,
198 &parents,
199 &changeset.author,
200 &changeset.committer,
201 &changeset.extras,
202 &changeset.message,
203 )
204 .map_err(|detail| Error::Unrepresentable {
205 changeset: *id,
206 detail,
207 })?;
208 (GitOid::for_object(GitKind::Commit, &bytes)?, bytes)
209 }
210 };
211 self.commits.insert(*id, oid);
212 self.commit_sources.insert(oid, *id);
213 Ok((oid, bytes))
214 }
215
216 /// The original commit of a changeset imported from git, after checking
217 /// that what it names agrees with the changeset and the map.
218 fn origin_commit(
219 &self,
220 id: &ObjectId,
221 changeset: &Changeset,
222 origin: &ObjectId,
223 ) -> Result<(GitOid, Vec<u8>), Error> {
224 let mismatch = |detail: String| Error::OriginMismatch {
225 changeset: *id,
226 detail,
227 };
228 let bytes = fetch::get(self.objects, origin, Kind::Blob)?;
229 let fields = raw::parse_commit(&bytes)
230 .map_err(|reason| mismatch(format!("its git origin is not a commit: {reason}")))?;
231 match self.map.tree(&fields.tree) {
232 Some(root) if root == changeset.root => {}
233 Some(root) => {
234 return Err(mismatch(format!(
235 "its commit names tree {}, which the map links to {root}, not to its root {}",
236 fields.tree, changeset.root
237 )));
238 }
239 None => {
240 return Err(mismatch(format!(
241 "its commit names tree {}, which the map does not know",
242 fields.tree
243 )));
244 }
245 }
246 if fields.parents.len() != changeset.parents.len() {
247 return Err(mismatch(format!(
248 "its commit names {} parents, the changeset has {}",
249 fields.parents.len(),
250 changeset.parents.len()
251 )));
252 }
253 for (index, (git, braid)) in fields.parents.iter().zip(&changeset.parents).enumerate() {
254 if self.map.changeset(git) != Some(*braid) {
255 return Err(mismatch(format!(
256 "parent {index} of its commit is {git}, which the map does not link to {braid}"
257 )));
258 }
259 }
260 let oid = GitOid::for_object(GitKind::Commit, &bytes)?;
261 if let Some(known) = self.map.commit(id)
262 && known != oid
263 {
264 return Err(mismatch(format!(
265 "the map links it to commit {known}, but its git origin is commit {oid}"
266 )));
267 }
268 Ok((oid, bytes))
269 }
270
271 /// The canonical git tree of a braid tree: its id and its bytes.
272 pub fn tree(&mut self, tree: &ObjectId) -> Result<(GitOid, Vec<u8>), Error> {
273 let entries = self.entries(*tree)?;
274 self.tree_of(tree, &entries)
275 }
276
277 /// [`tree`](Self::tree) for the braid tree `tree` whose entries the caller
278 /// has already: those it was just built from, which is what reading it
279 /// back from the store gives.
280 pub(crate) fn tree_of(
281 &mut self,
282 tree: &ObjectId,
283 entries: &[Entry],
284 ) -> Result<(GitOid, Vec<u8>), Error> {
285 let bytes = self.encode_entries(tree, entries)?;
286 let oid = GitOid::for_object(GitKind::Tree, &bytes)?;
287 match self.known_tree(tree) {
288 Some(known) if known != oid => Err(Error::BadBraidObject {
289 id: *tree,
290 detail: format!("the map links it to git tree {known}, but it exports as {oid}"),
291 }),
292 Some(_) => Ok((oid, bytes)),
293 None => {
294 self.trees.insert(*tree, oid);
295 self.tree_sources.insert(oid, *tree);
296 Ok((oid, bytes))
297 }
298 }
299 }
300
301 /// The id of the canonical git tree of a braid tree.
302 pub fn tree_id(&mut self, tree: &ObjectId) -> Result<GitOid, Error> {
303 if let Some(oid) = self.known_tree(tree) {
304 return Ok(oid);
305 }
306 // Directories waiting for their subdirectories: id, entries, and the
307 // index of the next entry to look at.
308 let mut stack = vec![(*tree, self.entries(*tree)?, 0usize)];
309 while let Some((_, entries, next)) = stack.last_mut() {
310 let mut child = None;
311 while child.is_none() && *next < entries.len() {
312 if let EntryKind::Tree { tree } = &entries[*next].kind
313 && self.known_tree(tree).is_none()
314 {
315 child = Some(*tree);
316 }
317 *next += 1;
318 }
319 if let Some(child) = child {
320 let entries = self.entries(child)?;
321 stack.push((child, entries, 0));
322 continue;
323 }
324 let (id, entries, _) = stack.pop().expect("the loop runs on a non-empty stack");
325 if self.known_tree(&id).is_some() {
326 continue;
327 }
328 let bytes = self.encode_entries(&id, &entries)?;
329 let oid = GitOid::for_object(GitKind::Tree, &bytes)?;
330 self.trees.insert(id, oid);
331 self.tree_sources.insert(oid, id);
332 }
333 self.known_tree(tree).ok_or_else(|| Error::NotMapped {
334 what: "tree",
335 id: tree.to_hex(),
336 })
337 }
338
339 fn known_tree(&self, tree: &ObjectId) -> Option<GitOid> {
340 self.map
341 .git_tree(tree)
342 .or_else(|| self.trees.get(tree).copied())
343 }
344
345 /// The canonical bytes of a directory. Its subdirectories normally have
346 /// git ids already, so this does not recurse far.
347 fn encode_entries(&mut self, tree: &ObjectId, entries: &[Entry]) -> Result<Vec<u8>, Error> {
348 let mut items = Vec::with_capacity(entries.len());
349 for entry in entries {
350 let (kind, oid) = match &entry.kind {
351 EntryKind::File { blob, .. } => (EntryType::File, self.blob_id(blob)?),
352 EntryKind::Executable { blob, .. } => (EntryType::Executable, self.blob_id(blob)?),
353 EntryKind::Symlink { blob, .. } => (EntryType::Symlink, self.blob_id(blob)?),
354 EntryKind::Tree { tree } => (EntryType::Tree, self.tree_id(tree)?),
355 EntryKind::Gitlink {
356 commit: GitId::Sha1(bytes),
357 } => (EntryType::Gitlink, GitOid::from_bytes(*bytes)),
358 EntryKind::Gitlink {
359 commit: GitId::Sha256(_),
360 } => {
361 return Err(Error::BadBraidObject {
362 id: *tree,
363 detail: "a SHA-256 submodule cannot be written in a SHA-1 tree".into(),
364 });
365 }
366 };
367 items.push(TreeItem {
368 kind,
369 name: &entry.name,
370 oid,
371 });
372 }
373 Ok(raw::encode_tree(&mut items))
374 }
375
376 /// The git blob of a braid blob: its id and its content.
377 pub fn blob(&mut self, blob: &ObjectId) -> Result<(GitOid, Vec<u8>), Error> {
378 let bytes = fetch::get(self.objects, blob, Kind::Blob)?;
379 let oid = GitOid::for_object(GitKind::Blob, &bytes)?;
380 if let Some(known) = self.map.git_blob(blob)
381 && known != oid
382 {
383 return Err(Error::BadBraidObject {
384 id: *blob,
385 detail: format!("the map links it to git blob {known}, but its content is {oid}"),
386 });
387 }
388 self.blobs.insert(*blob, (oid, bytes.len() as u64));
389 self.blob_sources.insert(oid, *blob);
390 Ok((oid, bytes))
391 }
392
393 /// The id of the git blob of a braid blob.
394 pub fn blob_id(&mut self, blob: &ObjectId) -> Result<GitOid, Error> {
395 match self
396 .map
397 .git_blob(blob)
398 .or_else(|| self.blobs.get(blob).map(|(oid, _)| *oid))
399 {
400 Some(oid) => Ok(oid),
401 None => Ok(self.blob(blob)?.0),
402 }
403 }
404
405 /// Any git object the map or this exporter knows, by its git id: a commit,
406 /// a tree (raw or regenerated), a blob or an annotated tag. The bytes are
407 /// checked to hash to `oid`.
408 pub fn object(&mut self, oid: &GitOid) -> Result<(GitKind, Vec<u8>), Error> {
409 let (kind, bytes) = self.object_bytes(oid)?;
410 let found = GitOid::for_object(kind, &bytes)?;
411 if found != *oid {
412 return Err(Error::Verification {
413 oid: *oid,
414 kind,
415 detail: format!("exported as {found}"),
416 });
417 }
418 Ok((kind, bytes))
419 }
420
421 fn object_bytes(&mut self, oid: &GitOid) -> Result<(GitKind, Vec<u8>), Error> {
422 if let Some(changeset) = self
423 .map
424 .changeset(oid)
425 .or_else(|| self.commit_sources.get(oid).copied())
426 {
427 return Ok((GitKind::Commit, self.commit(&changeset)?.1));
428 }
429 if let Some(raw) = self.map.raw_tree(oid) {
430 return Ok((GitKind::Tree, fetch::get(self.objects, &raw, Kind::Blob)?));
431 }
432 if let Some(tree) = self
433 .map
434 .tree(oid)
435 .or_else(|| self.tree_sources.get(oid).copied())
436 {
437 return Ok((GitKind::Tree, self.tree(&tree)?.1));
438 }
439 if let Some(blob) = self
440 .map
441 .blob(oid)
442 .map(|(id, _)| id)
443 .or_else(|| self.blob_sources.get(oid).copied())
444 {
445 return Ok((GitKind::Blob, fetch::get(self.objects, &blob, Kind::Blob)?));
446 }
447 if let Some(entry) = self.map.tag(oid) {
448 let bytes = fetch::get(self.objects, &entry.raw, Kind::Blob)?;
449 if raw::parse_tag(&bytes).ok() != Some(entry.target) {
450 return Err(Error::Verification {
451 oid: *oid,
452 kind: GitKind::Tag,
453 detail: format!("its raw bytes do not point to {}", entry.target),
454 });
455 }
456 return Ok((GitKind::Tag, bytes));
457 }
458 Err(Error::NotMapped {
459 what: "git object",
460 id: oid.to_hex(),
461 })
462 }
463}
464
465/// The git commit of a changeset: its id and its bytes. See [`Exporter`].
466pub fn export_commit<O: Objects>(
467 objects: &O,
468 map: &GitMap,
469 changeset: &ObjectId,
470) -> Result<(GitOid, Vec<u8>), Error> {
471 Exporter::new(objects, map).commit(changeset)
472}
473
474/// The canonical git tree of a braid tree: its id and its bytes.
475pub fn export_tree<O: Objects>(
476 objects: &O,
477 map: &GitMap,
478 tree: &ObjectId,
479) -> Result<(GitOid, Vec<u8>), Error> {
480 Exporter::new(objects, map).tree(tree)
481}
482
483/// The git blob of a braid blob: its id and its content.
484pub fn export_blob<O: Objects>(
485 objects: &O,
486 map: &GitMap,
487 blob: &ObjectId,
488) -> Result<(GitOid, Vec<u8>), Error> {
489 Exporter::new(objects, map).blob(blob)
490}
491
492/// An imported git object, by its git id: its kind and its exact bytes.
493pub fn export_object<O: Objects>(
494 objects: &O,
495 map: &GitMap,
496 oid: &GitOid,
497) -> Result<(GitKind, Vec<u8>), Error> {
498 Exporter::new(objects, map).object(oid)
499}
500
501/// What a ref written by [`write_to_repo`] points to.
502#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
503pub enum RefTarget {
504 /// A changeset, written as a commit.
505 Changeset(ObjectId),
506 /// A git object the map knows: a commit, an annotated tag, a tree or a
507 /// blob.
508 Git(GitOid),
509}
510
511/// A ref to set in [`write_to_repo`], which overwrites it without a lease.
512#[derive(Clone, Debug, PartialEq, Eq, Hash)]
513pub struct RefUpdate {
514 /// The full ref name, such as `refs/heads/main`.
515 pub name: Vec<u8>,
516 /// What it points to.
517 pub target: RefTarget,
518}
519
520/// What [`write_to_repo`] did.
521#[derive(Clone, Debug, Default, PartialEq, Eq)]
522pub struct WriteReport {
523 /// Commits written.
524 pub commits: usize,
525 /// Trees written.
526 pub trees: usize,
527 /// Blobs written.
528 pub blobs: usize,
529 /// Annotated tags written.
530 pub tags: usize,
531 /// Each ref and the object it points to now.
532 pub refs: Vec<(Vec<u8>, GitOid)>,
533}
534
535/// Writes into the git repository at `git_repo` every object the refs need,
536/// then points the refs at them in one transaction.
537///
538/// Refs are overwritten, whatever they pointed to before: there is no lease
539/// and no fast-forward check here. That is meant for local exports and for a
540/// mirror; updating a shared repository with a lease, as a fast-forward, is
541/// the job of `braid git sync`, which pushes from such a mirror.
542///
543/// Objects the repository already has are not written again, and neither is
544/// anything they reach. Objects are written after everything they reach, so an
545/// interrupted write never leaves an object whose closure is missing.
546///
547/// The map is not changed: [`write_to_repo_recording`] also records what the
548/// export generated.
549pub fn write_to_repo<O: Objects>(
550 git_repo: &Path,
551 objects: &O,
552 map: &GitMap,
553 refs: &[RefUpdate],
554) -> Result<WriteReport, Error> {
555 write(git_repo, objects, map, refs).map(|(report, _)| report)
556}
557
558/// [`write_to_repo`], then records in `map` every commit, canonical tree and
559/// blob the export generated (see [`Exporter::pairings`]), so that importing
560/// them again, from this repository or from any other that received them,
561/// gives back the same braid objects instead of new ones.
562///
563/// Nothing is recorded when the write fails. The caller saves the map.
564pub fn write_to_repo_recording<O: Objects>(
565 git_repo: &Path,
566 objects: &O,
567 map: &mut GitMap,
568 refs: &[RefUpdate],
569) -> Result<WriteReport, Error> {
570 let (report, pairings) = write(git_repo, objects, map, refs)?;
571 map.record(&pairings);
572 Ok(report)
573}
574
575/// Writes the objects and the refs, and returns what the export generated.
576fn write<O: Objects>(
577 git_repo: &Path,
578 objects: &O,
579 map: &GitMap,
580 refs: &[RefUpdate],
581) -> Result<(WriteReport, Pairings), Error> {
582 let mut repo = GitRepo::open(git_repo)?;
583 let mut writer = Writer {
584 exporter: Exporter::new(objects, map),
585 repo: &repo,
586 written: HashSet::new(),
587 report: WriteReport::default(),
588 };
589 let mut targets = Vec::with_capacity(refs.len());
590 for update in refs {
591 let oid = match update.target {
592 RefTarget::Changeset(changeset) => writer.exporter.commit_id(&changeset)?,
593 RefTarget::Git(oid) => oid,
594 };
595 writer.write_closure(oid)?;
596 targets.push((update.name.clone(), oid));
597 }
598 let pairings = writer.exporter.pairings();
599 let mut report = writer.report;
600 repo.set_refs(&targets, "braid: export")?;
601 report.refs = targets;
602 Ok((report, pairings))
603}
604
605struct Writer<'r, 'a, O: Objects> {
606 exporter: Exporter<'a, O>,
607 repo: &'r GitRepo,
608 written: HashSet<GitOid>,
609 report: WriteReport,
610}
611
612/// An object waiting for what it reaches to be written.
613struct Pending {
614 oid: GitOid,
615 kind: GitKind,
616 bytes: Vec<u8>,
617 children: Vec<GitOid>,
618 next: usize,
619}
620
621impl<O: Objects> Writer<'_, '_, O> {
622 fn present(&self, oid: &GitOid) -> bool {
623 self.written.contains(oid) || self.repo.contains(oid)
624 }
625
626 fn pending(&mut self, oid: GitOid) -> Result<Pending, Error> {
627 let (kind, bytes) = self.exporter.object(&oid)?;
628 let children = reached(oid, kind, &bytes)?;
629 Ok(Pending {
630 oid,
631 kind,
632 bytes,
633 children,
634 next: 0,
635 })
636 }
637
638 fn write_closure(&mut self, root: GitOid) -> Result<(), Error> {
639 if self.present(&root) {
640 return Ok(());
641 }
642 let mut stack = vec![self.pending(root)?];
643 while let Some(top) = stack.last_mut() {
644 if top.next < top.children.len() {
645 let child = top.children[top.next];
646 top.next += 1;
647 if !self.present(&child) {
648 let pending = self.pending(child)?;
649 stack.push(pending);
650 }
651 continue;
652 }
653 let done = stack.pop().expect("the loop runs on a non-empty stack");
654 if self.present(&done.oid) {
655 continue;
656 }
657 let stored = self.repo.write(done.kind, &done.bytes)?;
658 if stored != done.oid {
659 return Err(Error::Verification {
660 oid: done.oid,
661 kind: done.kind,
662 detail: format!("the repository stored it as {stored}"),
663 });
664 }
665 self.written.insert(done.oid);
666 match done.kind {
667 GitKind::Commit => self.report.commits += 1,
668 GitKind::Tree => self.report.trees += 1,
669 GitKind::Blob => self.report.blobs += 1,
670 GitKind::Tag => self.report.tags += 1,
671 }
672 }
673 Ok(())
674 }
675}
676
677/// The objects a git object names: a commit's tree and parents, a tree's
678/// entries except submodules, a tag's target.
679pub(crate) fn reached(oid: GitOid, kind: GitKind, bytes: &[u8]) -> Result<Vec<GitOid>, Error> {
680 let malformed = |reason| Error::Malformed { oid, kind, reason };
681 Ok(match kind {
682 GitKind::Commit => {
683 let fields = raw::parse_commit(bytes).map_err(malformed)?;
684 let mut out = Vec::with_capacity(1 + fields.parents.len());
685 out.push(fields.tree);
686 out.extend(fields.parents);
687 out
688 }
689 GitKind::Tree => {
690 let mut out = Vec::new();
691 for entry in raw::parse_tree(bytes).map_err(malformed)? {
692 match EntryType::from_mode(entry.mode) {
693 Some(EntryType::Gitlink) => {}
694 Some(_) => out.push(entry.oid),
695 None => return Err(malformed("an entry has an unsupported mode")),
696 }
697 }
698 out
699 }
700 GitKind::Tag => vec![raw::parse_tag(bytes).map_err(malformed)?],
701 GitKind::Blob => Vec::new(),
702 })
703}