Elffuss BraidHub

utopia-ia/elffuss-braid public

38b3e04f7d4a · 26.7 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! Import: git history into braid objects.
5
6use std::collections::{HashMap, HashSet};
7use std::path::Path;
8
9use braid_format::name::forbidden_as_symlink;
10use braid_format::tree::validate_entry;
11use braid_format::{
12 ChangesetParts, Directory, Entry, EntryKind, GitId, Kind, ObjectId, Objects, Signature,
13 build_directory, validate_name,
14};
15
16use crate::diff;
17use crate::error::Error;
18use crate::export::Exporter;
19use crate::fetch;
20use crate::map::{GitMap, TagEntry};
21use crate::oid::{GitKind, GitOid};
22use crate::raw::{self, EntryType};
23use crate::repo::GitRepo;
24
25/// What to import.
26#[derive(Clone, Debug, Default, PartialEq, Eq)]
27pub struct ImportOptions {
28 /// The refs to import, by full name such as `refs/heads/main` (a short
29 /// name is looked up the way git does). Empty means every branch and
30 /// every tag.
31 pub refs: Vec<Vec<u8>>,
32}
33
34/// A ref that was imported.
35#[derive(Clone, Debug, PartialEq, Eq, Hash)]
36pub struct ImportedRef {
37 /// Its full name.
38 pub name: Vec<u8>,
39 /// The git object it points to.
40 pub oid: GitOid,
41 /// The kind of that object.
42 pub kind: GitKind,
43 /// The braid object for it: the changeset of a commit, the blob with the
44 /// raw bytes of an annotated tag, the braid tree of a tree, the braid blob
45 /// of a blob.
46 pub braid: ObjectId,
47}
48
49/// What an import did. Counts are of objects new to the map.
50#[derive(Clone, Debug, Default, PartialEq, Eq)]
51pub struct ImportReport {
52 /// Commits imported.
53 pub commits: usize,
54 /// Git trees converted.
55 pub trees: usize,
56 /// Of those trees, the ones kept as raw bytes because they are not
57 /// canonical.
58 pub raw_trees: usize,
59 /// Blobs imported.
60 pub blobs: usize,
61 /// Annotated tags imported.
62 pub tags: usize,
63 /// Every ref that was asked for, sorted by name, new or not.
64 pub refs: Vec<ImportedRef>,
65}
66
67/// Imports the history of the git repository at `git_repo` into `objects`,
68/// recording every mapping in `map`.
69///
70/// Every commit reachable from the refs is imported, parents before
71/// children; commits already in `map` are skipped together with their
72/// history, so an import can be repeated to bring in new commits, or resumed
73/// after a failure. For each commit:
74///
75/// - its tree is converted, each git tree once: blobs keep their exact bytes,
76/// modes become file, executable, symlink, directory or submodule entries,
77/// and a git tree that the export cannot regenerate exactly keeps its raw
78/// bytes. Braid trees never hold an empty subdirectory, so empty
79/// directories, and directories holding only empty ones, are left out; a
80/// git tree that loses entries this way keeps its raw bytes too;
81/// - its raw bytes are stored and become the changeset's git origin, with the
82/// change list against its first parent, the parents, and the author,
83/// committer and message read from it;
84/// - it is exported again from what was stored, and the import stops with an
85/// error naming the commit unless the id is the same.
86///
87/// Annotated tags keep their raw bytes too, and are checked the same way.
88///
89/// Shallow clones and SHA-256 repositories are refused. Replacement objects
90/// and grafts are ignored, and objects are read raw: no filters, no
91/// line-ending conversion, no LFS. A tree holding a name that braid refuses,
92/// such as an alias of `.git`, stops the import with an error naming the
93/// commit and the path.
94pub fn import<O: Objects>(
95 git_repo: &Path,
96 objects: &O,
97 map: &mut GitMap,
98 options: &ImportOptions,
99) -> Result<ImportReport, Error> {
100 let repo = GitRepo::open(git_repo)?;
101 if repo.is_shallow()? {
102 return Err(Error::Shallow);
103 }
104 let refs = repo.refs(&options.refs)?;
105 let mut importer = Importer {
106 repo: &repo,
107 objects,
108 map,
109 report: ImportReport::default(),
110 roots: HashMap::new(),
111 empty_tree: build_directory(Vec::new())
112 .expect("the empty directory is valid")
113 .root(),
114 };
115
116 // What the refs point to: commits to walk from, trees and blobs that tags
117 // point to directly, and annotated tags, each after its target.
118 let mut plan = Plan::default();
119 for (_, oid) in &refs {
120 importer.plan_ref(*oid, &mut plan)?;
121 }
122 for commit in importer.commit_order(&plan.tips)? {
123 importer.import_commit(commit)?;
124 }
125 for (oid, kind) in &plan.loose {
126 match kind {
127 GitKind::Tree => {
128 importer.convert_tree(*oid, *oid, None)?;
129 }
130 _ => {
131 importer.import_blob(*oid, None)?;
132 }
133 }
134 }
135 for tag in &plan.tags {
136 importer.import_tag(*tag)?;
137 }
138
139 for (name, oid) in refs {
140 let kind = repo.kind(&oid)?;
141 let map = &mut *importer.map;
142 let braid = match kind {
143 GitKind::Commit => map.changeset(&oid),
144 GitKind::Tag => map.tag(&oid).map(|entry| entry.raw),
145 GitKind::Tree => map.tree(&oid),
146 GitKind::Blob => map.blob(&oid).map(|(id, _)| id),
147 }
148 .ok_or_else(|| Error::NotMapped {
149 what: kind.name(),
150 id: oid.to_hex(),
151 })?;
152 if name.starts_with(b"refs/tags/") {
153 match kind {
154 GitKind::Tag => map.set_tag_name(name.clone(), oid),
155 // The name may have pointed to an annotated tag before.
156 _ => map.remove_tag_name(&name),
157 }
158 }
159 importer.report.refs.push(ImportedRef {
160 name,
161 oid,
162 kind,
163 braid,
164 });
165 }
166 Ok(importer.report)
167}
168
169#[derive(Default)]
170struct Plan {
171 /// Commits to walk from.
172 tips: Vec<GitOid>,
173 /// Trees and blobs that refs or tags point to.
174 loose: Vec<(GitOid, GitKind)>,
175 /// Annotated tags to import, each after the tags it points to.
176 tags: Vec<GitOid>,
177 planned_tags: HashSet<GitOid>,
178}
179
180struct Importer<'r, 'o, 'm, O: Objects> {
181 repo: &'r GitRepo,
182 objects: &'o O,
183 map: &'m mut GitMap,
184 report: ImportReport,
185 /// Root trees and git origins of the changesets seen in this import.
186 roots: HashMap<ObjectId, (ObjectId, Option<ObjectId>)>,
187 /// The braid id of the empty directory.
188 empty_tree: ObjectId,
189}
190
191/// A git tree being converted, waiting for its subtrees.
192struct Frame {
193 oid: GitOid,
194 raw: Vec<u8>,
195 /// Path from the root of the commit's tree; empty for the root.
196 path: Vec<u8>,
197 /// The entries as written, with their types.
198 entries: Vec<(EntryType, Vec<u8>, GitOid)>,
199 next: usize,
200 /// Braid entries for the entries converted so far, in the same order.
201 done: Vec<Entry>,
202 /// Whether every subtree so far is canonical.
203 canonical_subtrees: bool,
204 /// Whether an empty directory was left out.
205 dropped_empty: bool,
206 /// The same path in the first parent, as hints for the store.
207 similar: Similar,
208}
209
210/// The braid tree at a path in the first parent of the commit being
211/// imported: what its new trees and blobs are probably close to.
212struct Similar {
213 tree: Option<ObjectId>,
214 /// Its entries, read on first use.
215 entries: Option<Vec<Entry>>,
216}
217
218impl Similar {
219 fn new(tree: Option<ObjectId>) -> Self {
220 Self {
221 tree,
222 entries: None,
223 }
224 }
225
226 /// The entry named `name`, reading the directory the first time.
227 fn entry<O: Objects>(&mut self, objects: &O, name: &[u8]) -> Result<Option<EntryKind>, Error> {
228 let entries = self.entries(objects)?;
229 Ok(entries
230 .binary_search_by(|entry| entry.name.as_slice().cmp(name))
231 .ok()
232 .map(|at| entries[at].kind.clone()))
233 }
234
235 fn entries<O: Objects>(&mut self, objects: &O) -> Result<&[Entry], Error> {
236 if self.entries.is_none() {
237 self.entries = Some(match self.tree {
238 Some(tree) => fetch::tree_entries(objects, tree)?,
239 None => Vec::new(),
240 });
241 }
242 Ok(self.entries.as_deref().unwrap_or_default())
243 }
244
245 /// The tree at `name` below this one.
246 fn subtree<O: Objects>(&mut self, objects: &O, name: &[u8]) -> Result<Similar, Error> {
247 Ok(Similar::new(match self.entry(objects, name)? {
248 Some(EntryKind::Tree { tree }) => Some(tree),
249 _ => None,
250 }))
251 }
252
253 /// The blob of the file, executable or symlink at `name`.
254 fn blob<O: Objects>(&mut self, objects: &O, name: &[u8]) -> Result<Option<ObjectId>, Error> {
255 Ok(match self.entry(objects, name)? {
256 Some(
257 EntryKind::File { blob, .. }
258 | EntryKind::Executable { blob, .. }
259 | EntryKind::Symlink { blob, .. },
260 ) => Some(blob),
261 _ => None,
262 })
263 }
264
265 /// For each node of the new directory `directory`, the node of this one
266 /// it most likely replaces. A split directory with as many nodes as
267 /// before pairs them in order, since boundaries depend only on names;
268 /// otherwise only the root is paired, with the old root.
269 fn nodes<O: Objects>(
270 &mut self,
271 objects: &O,
272 directory: &Directory,
273 ) -> Result<Vec<Option<ObjectId>>, Error> {
274 let count = directory.nodes.len();
275 let mut similar = vec![None; count];
276 let Some(tree) = self.tree else {
277 return Ok(similar);
278 };
279 if count > 1
280 && let Ok(old) = build_directory(self.entries(objects)?.to_vec())
281 && old.nodes.len() == count
282 {
283 return Ok(old.nodes.iter().map(|(id, _)| Some(*id)).collect());
284 }
285 if let Some(root) = similar.last_mut() {
286 *root = Some(tree);
287 }
288 Ok(similar)
289 }
290}
291
292impl<O: Objects> Importer<'_, '_, '_, O> {
293 /// Follows a ref through annotated tags to a commit, a tree or a blob.
294 fn plan_ref(&mut self, oid: GitOid, plan: &mut Plan) -> Result<(), Error> {
295 let mut chain = Vec::new();
296 let mut current = oid;
297 loop {
298 match self.repo.kind(&current)? {
299 GitKind::Commit => {
300 plan.tips.push(current);
301 break;
302 }
303 kind @ (GitKind::Tree | GitKind::Blob) => {
304 plan.loose.push((current, kind));
305 break;
306 }
307 GitKind::Tag => {
308 // A tag already imported or planned has its target taken
309 // care of.
310 if self.map.tag(&current).is_some()
311 || plan.planned_tags.contains(&current)
312 || chain.contains(&current)
313 {
314 break;
315 }
316 chain.push(current);
317 let bytes = self.repo.read_kind(&current, GitKind::Tag)?;
318 current = raw::parse_tag(&bytes).map_err(|reason| Error::Malformed {
319 oid: current,
320 kind: GitKind::Tag,
321 reason,
322 })?;
323 }
324 }
325 }
326 for tag in chain.into_iter().rev() {
327 plan.planned_tags.insert(tag);
328 plan.tags.push(tag);
329 }
330 Ok(())
331 }
332
333 /// Every commit reachable from `tips` and not yet in the map, parents
334 /// before children. The walk is depth first along first parents, without
335 /// recursion.
336 fn commit_order(&self, tips: &[GitOid]) -> Result<Vec<GitOid>, Error> {
337 let mut order = Vec::new();
338 let mut seen = HashSet::new();
339 for tip in tips {
340 if self.map.changeset(tip).is_some() || !seen.insert(*tip) {
341 continue;
342 }
343 let mut stack = vec![(*tip, self.parents(tip)?, 0usize)];
344 while let Some((oid, parents, next)) = stack.last_mut() {
345 if let Some(parent) = parents.get(*next).copied() {
346 *next += 1;
347 if self.map.changeset(&parent).is_none() && seen.insert(parent) {
348 let grandparents = self.parents(&parent)?;
349 stack.push((parent, grandparents, 0));
350 }
351 continue;
352 }
353 order.push(*oid);
354 stack.pop();
355 }
356 }
357 Ok(order)
358 }
359
360 fn parents(&self, commit: &GitOid) -> Result<Vec<GitOid>, Error> {
361 let bytes = self.repo.read_kind(commit, GitKind::Commit)?;
362 let fields = raw::parse_commit(&bytes).map_err(|reason| Error::Malformed {
363 oid: *commit,
364 kind: GitKind::Commit,
365 reason,
366 })?;
367 Ok(fields.parents)
368 }
369
370 fn import_commit(&mut self, oid: GitOid) -> Result<(), Error> {
371 let bytes = self.repo.read_kind(&oid, GitKind::Commit)?;
372 let fields = raw::parse_commit(&bytes).map_err(|reason| Error::Malformed {
373 oid,
374 kind: GitKind::Commit,
375 reason,
376 })?;
377 let mut parents = Vec::with_capacity(fields.parents.len());
378 for parent in &fields.parents {
379 parents.push(self.map.changeset(parent).ok_or_else(|| Error::NotMapped {
380 what: "commit",
381 id: parent.to_hex(),
382 })?);
383 }
384 let (base, base_origin) = match parents.first() {
385 Some(parent) => {
386 let (root, origin) = self.root_of(parent)?;
387 (Some(root), origin)
388 }
389 None => (None, None),
390 };
391 // What the first parent has at each path, and its own raw bytes, are
392 // what the store may keep new trees, blobs and bytes as deltas
393 // against.
394 let root = self.convert_tree(fields.tree, oid, base)?;
395 let changes = diff::changes(self.objects, base, root)?;
396 let origin = fetch::put_hinted(self.objects, Kind::Blob, &bytes, base_origin.as_ref())?;
397 let unknown = || Signature {
398 name: Vec::new(),
399 email: Vec::new(),
400 seconds: 0,
401 offset_minutes: 0,
402 };
403 let assembled = ChangesetParts {
404 parents,
405 root,
406 changes,
407 author: fields.author.map_or_else(unknown, raw::parse_signature),
408 committer: fields.committer.map_or_else(unknown, raw::parse_signature),
409 message: fields.message.to_vec(),
410 extras: Vec::new(),
411 git_origin: Some(origin),
412 }
413 .assemble()
414 .map_err(|err| Error::Verification {
415 oid,
416 kind: GitKind::Commit,
417 detail: format!("its changeset cannot be assembled: {err}"),
418 })?;
419 if let Some((_, list)) = &assembled.external_list {
420 fetch::put(self.objects, Kind::Blob, list)?;
421 }
422 let changeset = fetch::put(self.objects, Kind::Changeset, &assembled.encoded)?;
423
424 // Export what was stored and compare. The commit enters the map only
425 // once it has passed, so a resumed import checks it again.
426 let verification = |detail: String| Error::Verification {
427 oid,
428 kind: GitKind::Commit,
429 detail,
430 };
431 let mut exporter = Exporter::new(self.objects, &*self.map);
432 let (exported, _) = exporter
433 .commit(&changeset)
434 .map_err(|err| verification(err.to_string()))?;
435 if exported != oid {
436 return Err(verification(format!("exported again as {exported}")));
437 }
438 exporter
439 .object(&fields.tree)
440 .map_err(|err| verification(format!("its tree: {err}")))?;
441
442 self.map.insert_commit(oid, changeset);
443 self.roots.insert(changeset, (root, Some(origin)));
444 self.report.commits += 1;
445 Ok(())
446 }
447
448 /// The root tree and the git origin of a changeset.
449 fn root_of(&mut self, changeset: &ObjectId) -> Result<(ObjectId, Option<ObjectId>), Error> {
450 if let Some(found) = self.roots.get(changeset) {
451 return Ok(*found);
452 }
453 let read = fetch::changeset(self.objects, changeset)?;
454 let found = (read.root, read.git_origin);
455 self.roots.insert(*changeset, found);
456 Ok(found)
457 }
458
459 /// Converts a git tree and everything below it, and returns its braid
460 /// tree. `commit` names the commit (or the object a ref points to) in
461 /// errors, and `similar` is the braid tree of its first parent, if it
462 /// has one. Subtrees are converted before their parents, without
463 /// recursion.
464 fn convert_tree(
465 &mut self,
466 root: GitOid,
467 commit: GitOid,
468 similar: Option<ObjectId>,
469 ) -> Result<ObjectId, Error> {
470 if let Some(tree) = self.map.tree(&root) {
471 return Ok(tree);
472 }
473 let mut stack = vec![self.open_tree(root, Vec::new(), commit, Similar::new(similar))?];
474 loop {
475 let top = stack
476 .last_mut()
477 .expect("the stack holds the root until it returns");
478 if let Some((kind, name, oid)) = top.entries.get(top.next).cloned() {
479 let kind = match kind {
480 EntryType::Tree => match self.map.tree(&oid) {
481 Some(tree) => {
482 top.canonical_subtrees &= self.map.raw_tree(&oid).is_none();
483 if tree == self.empty_tree {
484 top.dropped_empty = true;
485 top.next += 1;
486 continue;
487 }
488 EntryKind::Tree { tree }
489 }
490 None => {
491 let path = join(&top.path, &name);
492 let similar = top.similar.subtree(self.objects, &name)?;
493 let child = self.open_tree(oid, path, commit, similar)?;
494 stack.push(child);
495 continue;
496 }
497 },
498 EntryType::Gitlink => EntryKind::Gitlink {
499 commit: GitId::from(oid),
500 },
501 EntryType::File | EntryType::Executable | EntryType::Symlink => {
502 let (blob, size) = match self.map.blob(&oid) {
503 Some(found) => found,
504 None => {
505 let similar = top.similar.blob(self.objects, &name)?;
506 self.import_blob(oid, similar)?
507 }
508 };
509 match kind {
510 EntryType::File => EntryKind::File { blob, size },
511 EntryType::Executable => EntryKind::Executable { blob, size },
512 _ => EntryKind::Symlink { blob, size },
513 }
514 }
515 };
516 top.done.push(Entry { name, kind });
517 top.next += 1;
518 continue;
519 }
520 let finished = stack
521 .pop()
522 .expect("the stack holds the root until it returns");
523 let tree = self.finish_tree(finished, commit)?;
524 match stack.last_mut() {
525 Some(parent) => {
526 let (_, name, oid) = parent.entries[parent.next].clone();
527 parent.canonical_subtrees &= self.map.raw_tree(&oid).is_none();
528 if tree == self.empty_tree {
529 // An empty directory, or one holding only empty
530 // ones: braid trees leave it out.
531 parent.dropped_empty = true;
532 } else {
533 parent.done.push(Entry {
534 name,
535 kind: EntryKind::Tree { tree },
536 });
537 }
538 parent.next += 1;
539 }
540 // A root may be empty.
541 None => return Ok(tree),
542 }
543 }
544 }
545
546 /// Reads a git tree and checks every entry's mode and name before any of
547 /// its content is read.
548 fn open_tree(
549 &self,
550 oid: GitOid,
551 path: Vec<u8>,
552 commit: GitOid,
553 similar: Similar,
554 ) -> Result<Frame, Error> {
555 let raw = self.repo.read_kind(&oid, GitKind::Tree)?;
556 let parsed = raw::parse_tree(&raw).map_err(|reason| Error::Malformed {
557 oid,
558 kind: GitKind::Tree,
559 reason,
560 })?;
561 let mut entries = Vec::with_capacity(parsed.len());
562 for entry in &parsed {
563 let kind = EntryType::from_mode(entry.mode).ok_or_else(|| Error::UnsupportedMode {
564 commit,
565 path: join(&path, entry.name),
566 mode: entry.mode.to_vec(),
567 })?;
568 let refused = |reason: String| Error::RefusedPath {
569 commit,
570 path: join(&path, entry.name),
571 reason,
572 };
573 validate_name(entry.name).map_err(|err| refused(err.to_string()))?;
574 if kind == EntryType::Symlink && forbidden_as_symlink(entry.name) {
575 return Err(refused("this name must not be a symlink".into()));
576 }
577 entries.push((kind, entry.name.to_vec(), entry.oid));
578 }
579 let count = entries.len();
580 Ok(Frame {
581 oid,
582 raw,
583 path,
584 entries,
585 next: 0,
586 done: Vec::with_capacity(count),
587 canonical_subtrees: true,
588 dropped_empty: false,
589 similar,
590 })
591 }
592
593 /// Stores the braid tree of a converted git tree, decides whether the git
594 /// tree is canonical, and records it.
595 fn finish_tree(&mut self, frame: Frame, commit: GitOid) -> Result<ObjectId, Error> {
596 let Frame {
597 oid,
598 raw,
599 path,
600 done,
601 canonical_subtrees,
602 dropped_empty,
603 mut similar,
604 ..
605 } = frame;
606 // Braid names are unique: of duplicate entries, the last one written
607 // stays, which is the one git puts in the index and checks out. The
608 // raw bytes keep the others.
609 let written = done.len();
610 let mut names = HashSet::with_capacity(written);
611 let entries: Vec<Entry> = done
612 .into_iter()
613 .rev()
614 .filter(|entry| names.insert(entry.name.clone()))
615 .collect();
616 let unique = entries.len() == written;
617 for entry in &entries {
618 validate_entry(entry).map_err(|err| Error::RefusedPath {
619 commit,
620 path: join(&path, &entry.name),
621 reason: err.to_string(),
622 })?;
623 }
624 let directory = build_directory(entries).map_err(|err| Error::RefusedPath {
625 commit,
626 path: path.clone(),
627 reason: err.to_string(),
628 })?;
629 let hints = similar.nodes(self.objects, &directory)?;
630 for ((id, bytes), hint) in directory.nodes.iter().zip(hints) {
631 // A node that did not change is its own old version: no hint.
632 let hint = hint.filter(|hint| hint != id);
633 fetch::put_hinted(self.objects, Kind::Tree, bytes, hint.as_ref())?;
634 }
635 let tree = directory.root();
636
637 // Canonical means the export, reading back what was just stored,
638 // gives exactly these bytes. A tree naming a subtree that is not
639 // canonical cannot be: the subtree's canonical id differs. Neither can
640 // one that lost duplicates or empty directories.
641 let canonical = canonical_subtrees
642 && unique
643 && !dropped_empty
644 && Exporter::new(self.objects, &*self.map).tree(&tree)?.1 == raw;
645 let raw_blob = if canonical {
646 None
647 } else {
648 let blob = fetch::put(self.objects, Kind::Blob, &raw)?;
649 let stored = fetch::get(self.objects, &blob, Kind::Blob)?;
650 if GitOid::for_object(GitKind::Tree, &stored)? != oid {
651 return Err(Error::Verification {
652 oid,
653 kind: GitKind::Tree,
654 detail: "its raw bytes do not read back".into(),
655 });
656 }
657 Some(blob)
658 };
659 self.map.insert_tree(oid, tree, raw_blob);
660 self.report.trees += 1;
661 if raw_blob.is_some() {
662 self.report.raw_trees += 1;
663 }
664 Ok(tree)
665 }
666
667 /// Imports a blob, with the first parent's blob at the same path, if
668 /// any, as a hint for the store.
669 fn import_blob(
670 &mut self,
671 oid: GitOid,
672 similar: Option<ObjectId>,
673 ) -> Result<(ObjectId, u64), Error> {
674 if let Some(found) = self.map.blob(&oid) {
675 return Ok(found);
676 }
677 let bytes = self.repo.read_kind(&oid, GitKind::Blob)?;
678 let blob = fetch::put_hinted(self.objects, Kind::Blob, &bytes, similar.as_ref())?;
679 let size = bytes.len() as u64;
680 self.map.insert_blob(oid, blob, size);
681 self.report.blobs += 1;
682 Ok((blob, size))
683 }
684
685 fn import_tag(&mut self, oid: GitOid) -> Result<(), Error> {
686 if self.map.tag(&oid).is_some() {
687 return Ok(());
688 }
689 let bytes = self.repo.read_kind(&oid, GitKind::Tag)?;
690 let target = raw::parse_tag(&bytes).map_err(|reason| Error::Malformed {
691 oid,
692 kind: GitKind::Tag,
693 reason,
694 })?;
695 let target_kind = self.repo.kind(&target)?;
696 let imported = match target_kind {
697 GitKind::Commit => self.map.changeset(&target).is_some(),
698 GitKind::Tree => self.map.tree(&target).is_some(),
699 GitKind::Blob => self.map.blob(&target).is_some(),
700 GitKind::Tag => self.map.tag(&target).is_some(),
701 };
702 if !imported {
703 return Err(Error::NotMapped {
704 what: target_kind.name(),
705 id: target.to_hex(),
706 });
707 }
708 let raw = fetch::put(self.objects, Kind::Blob, &bytes)?;
709 let stored = fetch::get(self.objects, &raw, Kind::Blob)?;
710 if GitOid::for_object(GitKind::Tag, &stored)? != oid {
711 return Err(Error::Verification {
712 oid,
713 kind: GitKind::Tag,
714 detail: "its raw bytes do not read back".into(),
715 });
716 }
717 self.map.insert_tag(
718 oid,
719 TagEntry {
720 raw,
721 target,
722 target_kind,
723 },
724 );
725 self.report.tags += 1;
726 Ok(())
727 }
728}
729
730fn join(prefix: &[u8], name: &[u8]) -> Vec<u8> {
731 if prefix.is_empty() {
732 return name.to_vec();
733 }
734 let mut path = Vec::with_capacity(prefix.len() + 1 + name.len());
735 path.extend_from_slice(prefix);
736 path.push(b'/');
737 path.extend_from_slice(name);
738 path
739}