Elffuss BraidHub

utopia-ia/elffuss-braid public

f8f43175152e · 22.2 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, Entry, EntryKind, GitId, Kind, ObjectId, Objects, Signature, build_directory,
13 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)?;
129 }
130 _ => {
131 importer.import_blob(*oid)?;
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 of the changesets seen in this import.
186 roots: HashMap<ObjectId, 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}
207
208impl<O: Objects> Importer<'_, '_, '_, O> {
209 /// Follows a ref through annotated tags to a commit, a tree or a blob.
210 fn plan_ref(&mut self, oid: GitOid, plan: &mut Plan) -> Result<(), Error> {
211 let mut chain = Vec::new();
212 let mut current = oid;
213 loop {
214 match self.repo.kind(&current)? {
215 GitKind::Commit => {
216 plan.tips.push(current);
217 break;
218 }
219 kind @ (GitKind::Tree | GitKind::Blob) => {
220 plan.loose.push((current, kind));
221 break;
222 }
223 GitKind::Tag => {
224 // A tag already imported or planned has its target taken
225 // care of.
226 if self.map.tag(&current).is_some()
227 || plan.planned_tags.contains(&current)
228 || chain.contains(&current)
229 {
230 break;
231 }
232 chain.push(current);
233 let bytes = self.repo.read_kind(&current, GitKind::Tag)?;
234 current = raw::parse_tag(&bytes).map_err(|reason| Error::Malformed {
235 oid: current,
236 kind: GitKind::Tag,
237 reason,
238 })?;
239 }
240 }
241 }
242 for tag in chain.into_iter().rev() {
243 plan.planned_tags.insert(tag);
244 plan.tags.push(tag);
245 }
246 Ok(())
247 }
248
249 /// Every commit reachable from `tips` and not yet in the map, parents
250 /// before children. The walk is depth first along first parents, without
251 /// recursion.
252 fn commit_order(&self, tips: &[GitOid]) -> Result<Vec<GitOid>, Error> {
253 let mut order = Vec::new();
254 let mut seen = HashSet::new();
255 for tip in tips {
256 if self.map.changeset(tip).is_some() || !seen.insert(*tip) {
257 continue;
258 }
259 let mut stack = vec![(*tip, self.parents(tip)?, 0usize)];
260 while let Some((oid, parents, next)) = stack.last_mut() {
261 if let Some(parent) = parents.get(*next).copied() {
262 *next += 1;
263 if self.map.changeset(&parent).is_none() && seen.insert(parent) {
264 let grandparents = self.parents(&parent)?;
265 stack.push((parent, grandparents, 0));
266 }
267 continue;
268 }
269 order.push(*oid);
270 stack.pop();
271 }
272 }
273 Ok(order)
274 }
275
276 fn parents(&self, commit: &GitOid) -> Result<Vec<GitOid>, Error> {
277 let bytes = self.repo.read_kind(commit, GitKind::Commit)?;
278 let fields = raw::parse_commit(&bytes).map_err(|reason| Error::Malformed {
279 oid: *commit,
280 kind: GitKind::Commit,
281 reason,
282 })?;
283 Ok(fields.parents)
284 }
285
286 fn import_commit(&mut self, oid: GitOid) -> Result<(), Error> {
287 let bytes = self.repo.read_kind(&oid, GitKind::Commit)?;
288 let fields = raw::parse_commit(&bytes).map_err(|reason| Error::Malformed {
289 oid,
290 kind: GitKind::Commit,
291 reason,
292 })?;
293 let root = self.convert_tree(fields.tree, oid)?;
294 let mut parents = Vec::with_capacity(fields.parents.len());
295 for parent in &fields.parents {
296 parents.push(self.map.changeset(parent).ok_or_else(|| Error::NotMapped {
297 what: "commit",
298 id: parent.to_hex(),
299 })?);
300 }
301 let base = match parents.first() {
302 Some(parent) => Some(self.root_of(parent)?),
303 None => None,
304 };
305 let changes = diff::changes(self.objects, base, root)?;
306 let origin = fetch::put(self.objects, Kind::Blob, &bytes)?;
307 let unknown = || Signature {
308 name: Vec::new(),
309 email: Vec::new(),
310 seconds: 0,
311 offset_minutes: 0,
312 };
313 let assembled = ChangesetParts {
314 parents,
315 root,
316 changes,
317 author: fields.author.map_or_else(unknown, raw::parse_signature),
318 committer: fields.committer.map_or_else(unknown, raw::parse_signature),
319 message: fields.message.to_vec(),
320 extras: Vec::new(),
321 git_origin: Some(origin),
322 }
323 .assemble()
324 .map_err(|err| Error::Verification {
325 oid,
326 kind: GitKind::Commit,
327 detail: format!("its changeset cannot be assembled: {err}"),
328 })?;
329 if let Some((_, list)) = &assembled.external_list {
330 fetch::put(self.objects, Kind::Blob, list)?;
331 }
332 let changeset = fetch::put(self.objects, Kind::Changeset, &assembled.encoded)?;
333
334 // Export what was stored and compare. The commit enters the map only
335 // once it has passed, so a resumed import checks it again.
336 let verification = |detail: String| Error::Verification {
337 oid,
338 kind: GitKind::Commit,
339 detail,
340 };
341 let mut exporter = Exporter::new(self.objects, &*self.map);
342 let (exported, _) = exporter
343 .commit(&changeset)
344 .map_err(|err| verification(err.to_string()))?;
345 if exported != oid {
346 return Err(verification(format!("exported again as {exported}")));
347 }
348 exporter
349 .object(&fields.tree)
350 .map_err(|err| verification(format!("its tree: {err}")))?;
351
352 self.map.insert_commit(oid, changeset);
353 self.roots.insert(changeset, root);
354 self.report.commits += 1;
355 Ok(())
356 }
357
358 fn root_of(&mut self, changeset: &ObjectId) -> Result<ObjectId, Error> {
359 if let Some(root) = self.roots.get(changeset) {
360 return Ok(*root);
361 }
362 let root = fetch::changeset(self.objects, changeset)?.root;
363 self.roots.insert(*changeset, root);
364 Ok(root)
365 }
366
367 /// Converts a git tree and everything below it, and returns its braid
368 /// tree. `commit` names the commit (or the object a ref points to) in
369 /// errors. Subtrees are converted before their parents, without recursion.
370 fn convert_tree(&mut self, root: GitOid, commit: GitOid) -> Result<ObjectId, Error> {
371 if let Some(tree) = self.map.tree(&root) {
372 return Ok(tree);
373 }
374 let mut stack = vec![self.open_tree(root, Vec::new(), commit)?];
375 loop {
376 let top = stack
377 .last_mut()
378 .expect("the stack holds the root until it returns");
379 if let Some((kind, name, oid)) = top.entries.get(top.next).cloned() {
380 let kind = match kind {
381 EntryType::Tree => match self.map.tree(&oid) {
382 Some(tree) => {
383 top.canonical_subtrees &= self.map.raw_tree(&oid).is_none();
384 if tree == self.empty_tree {
385 top.dropped_empty = true;
386 top.next += 1;
387 continue;
388 }
389 EntryKind::Tree { tree }
390 }
391 None => {
392 let path = join(&top.path, &name);
393 let child = self.open_tree(oid, path, commit)?;
394 stack.push(child);
395 continue;
396 }
397 },
398 EntryType::Gitlink => EntryKind::Gitlink {
399 commit: GitId::from(oid),
400 },
401 EntryType::File | EntryType::Executable | EntryType::Symlink => {
402 let (blob, size) = self.import_blob(oid)?;
403 match kind {
404 EntryType::File => EntryKind::File { blob, size },
405 EntryType::Executable => EntryKind::Executable { blob, size },
406 _ => EntryKind::Symlink { blob, size },
407 }
408 }
409 };
410 top.done.push(Entry { name, kind });
411 top.next += 1;
412 continue;
413 }
414 let finished = stack
415 .pop()
416 .expect("the stack holds the root until it returns");
417 let tree = self.finish_tree(finished, commit)?;
418 match stack.last_mut() {
419 Some(parent) => {
420 let (_, name, oid) = parent.entries[parent.next].clone();
421 parent.canonical_subtrees &= self.map.raw_tree(&oid).is_none();
422 if tree == self.empty_tree {
423 // An empty directory, or one holding only empty
424 // ones: braid trees leave it out.
425 parent.dropped_empty = true;
426 } else {
427 parent.done.push(Entry {
428 name,
429 kind: EntryKind::Tree { tree },
430 });
431 }
432 parent.next += 1;
433 }
434 // A root may be empty.
435 None => return Ok(tree),
436 }
437 }
438 }
439
440 /// Reads a git tree and checks every entry's mode and name before any of
441 /// its content is read.
442 fn open_tree(&self, oid: GitOid, path: Vec<u8>, commit: GitOid) -> Result<Frame, Error> {
443 let raw = self.repo.read_kind(&oid, GitKind::Tree)?;
444 let parsed = raw::parse_tree(&raw).map_err(|reason| Error::Malformed {
445 oid,
446 kind: GitKind::Tree,
447 reason,
448 })?;
449 let mut entries = Vec::with_capacity(parsed.len());
450 for entry in &parsed {
451 let kind = EntryType::from_mode(entry.mode).ok_or_else(|| Error::UnsupportedMode {
452 commit,
453 path: join(&path, entry.name),
454 mode: entry.mode.to_vec(),
455 })?;
456 let refused = |reason: String| Error::RefusedPath {
457 commit,
458 path: join(&path, entry.name),
459 reason,
460 };
461 validate_name(entry.name).map_err(|err| refused(err.to_string()))?;
462 if kind == EntryType::Symlink && forbidden_as_symlink(entry.name) {
463 return Err(refused("this name must not be a symlink".into()));
464 }
465 entries.push((kind, entry.name.to_vec(), entry.oid));
466 }
467 let count = entries.len();
468 Ok(Frame {
469 oid,
470 raw,
471 path,
472 entries,
473 next: 0,
474 done: Vec::with_capacity(count),
475 canonical_subtrees: true,
476 dropped_empty: false,
477 })
478 }
479
480 /// Stores the braid tree of a converted git tree, decides whether the git
481 /// tree is canonical, and records it.
482 fn finish_tree(&mut self, frame: Frame, commit: GitOid) -> Result<ObjectId, Error> {
483 let Frame {
484 oid,
485 raw,
486 path,
487 done,
488 canonical_subtrees,
489 dropped_empty,
490 ..
491 } = frame;
492 // Braid names are unique: of duplicate entries, the last one written
493 // stays, which is the one git puts in the index and checks out. The
494 // raw bytes keep the others.
495 let written = done.len();
496 let mut names = HashSet::with_capacity(written);
497 let entries: Vec<Entry> = done
498 .into_iter()
499 .rev()
500 .filter(|entry| names.insert(entry.name.clone()))
501 .collect();
502 let unique = entries.len() == written;
503 for entry in &entries {
504 validate_entry(entry).map_err(|err| Error::RefusedPath {
505 commit,
506 path: join(&path, &entry.name),
507 reason: err.to_string(),
508 })?;
509 }
510 let directory = build_directory(entries).map_err(|err| Error::RefusedPath {
511 commit,
512 path: path.clone(),
513 reason: err.to_string(),
514 })?;
515 for (_, bytes) in &directory.nodes {
516 fetch::put(self.objects, Kind::Tree, bytes)?;
517 }
518 let tree = directory.root();
519
520 // Canonical means the export, reading back what was just stored,
521 // gives exactly these bytes. A tree naming a subtree that is not
522 // canonical cannot be: the subtree's canonical id differs. Neither can
523 // one that lost duplicates or empty directories.
524 let canonical = canonical_subtrees
525 && unique
526 && !dropped_empty
527 && Exporter::new(self.objects, &*self.map).tree(&tree)?.1 == raw;
528 let raw_blob = if canonical {
529 None
530 } else {
531 let blob = fetch::put(self.objects, Kind::Blob, &raw)?;
532 let stored = fetch::get(self.objects, &blob, Kind::Blob)?;
533 if GitOid::for_object(GitKind::Tree, &stored)? != oid {
534 return Err(Error::Verification {
535 oid,
536 kind: GitKind::Tree,
537 detail: "its raw bytes do not read back".into(),
538 });
539 }
540 Some(blob)
541 };
542 self.map.insert_tree(oid, tree, raw_blob);
543 self.report.trees += 1;
544 if raw_blob.is_some() {
545 self.report.raw_trees += 1;
546 }
547 Ok(tree)
548 }
549
550 fn import_blob(&mut self, oid: GitOid) -> Result<(ObjectId, u64), Error> {
551 if let Some(found) = self.map.blob(&oid) {
552 return Ok(found);
553 }
554 let bytes = self.repo.read_kind(&oid, GitKind::Blob)?;
555 let blob = fetch::put(self.objects, Kind::Blob, &bytes)?;
556 let size = bytes.len() as u64;
557 self.map.insert_blob(oid, blob, size);
558 self.report.blobs += 1;
559 Ok((blob, size))
560 }
561
562 fn import_tag(&mut self, oid: GitOid) -> Result<(), Error> {
563 if self.map.tag(&oid).is_some() {
564 return Ok(());
565 }
566 let bytes = self.repo.read_kind(&oid, GitKind::Tag)?;
567 let target = raw::parse_tag(&bytes).map_err(|reason| Error::Malformed {
568 oid,
569 kind: GitKind::Tag,
570 reason,
571 })?;
572 let target_kind = self.repo.kind(&target)?;
573 let imported = match target_kind {
574 GitKind::Commit => self.map.changeset(&target).is_some(),
575 GitKind::Tree => self.map.tree(&target).is_some(),
576 GitKind::Blob => self.map.blob(&target).is_some(),
577 GitKind::Tag => self.map.tag(&target).is_some(),
578 };
579 if !imported {
580 return Err(Error::NotMapped {
581 what: target_kind.name(),
582 id: target.to_hex(),
583 });
584 }
585 let raw = fetch::put(self.objects, Kind::Blob, &bytes)?;
586 let stored = fetch::get(self.objects, &raw, Kind::Blob)?;
587 if GitOid::for_object(GitKind::Tag, &stored)? != oid {
588 return Err(Error::Verification {
589 oid,
590 kind: GitKind::Tag,
591 detail: "its raw bytes do not read back".into(),
592 });
593 }
594 self.map.insert_tag(
595 oid,
596 TagEntry {
597 raw,
598 target,
599 target_kind,
600 },
601 );
602 self.report.tags += 1;
603 Ok(())
604 }
605}
606
607fn join(prefix: &[u8], name: &[u8]) -> Vec<u8> {
608 if prefix.is_empty() {
609 return name.to_vec();
610 }
611 let mut path = Vec::with_capacity(prefix.len() + 1 + name.len());
612 path.extend_from_slice(prefix);
613 path.push(b'/');
614 path.extend_from_slice(name);
615 path
616}