1use std::collections::{BTreeMap, BTreeSet, HashMap};
11use std::path::Path;
12
13use gix::ObjectId;
14use gix::bstr::ByteSlice;
15
16use brygge_ir::builder::{AtomDraft, IrBuilder};
17use brygge_ir::model::{
18 Annotation, AtomId, CopyRecord, DropRecord, Extra, Identity, ImportProvenance, Ir,
19 LossBoundary, LossClass, MetadataClaims, PathOp, RefKind, RefRecord, Signature, SourceIdentity,
20 SourceKind, Text, Time,
21};
22use brygge_ir::status::{Derivation, DerivationKind, EpistemicStatus};
23
24use crate::{Error, Options, decoder_version, floor, open};
25
26type Snapshot = BTreeMap<String, (ObjectId, u32)>;
28
29type TagIdentity = (ObjectId, Vec<Signature>, Option<Annotation>);
32
33const DECODER: &str = "brygge-decode-git";
34
35#[derive(Debug, Clone, Copy)]
38pub(crate) struct Limits {
39 pub(crate) max_blob_bytes: u64,
42 pub(crate) max_commits: u64,
45 pub(crate) max_path_bytes: usize,
47 pub(crate) max_tree_depth: usize,
50 pub(crate) max_tag_chain: usize,
54}
55
56impl Default for Limits {
57 fn default() -> Self {
58 Self {
59 max_blob_bytes: 1024 * 1024 * 1024,
60 max_commits: 10_000_000,
61 max_path_bytes: 4096,
62 max_tree_depth: 256,
63 max_tag_chain: 32,
64 }
65 }
66}
67
68fn resource_limit(what: &str, ceiling: impl std::fmt::Display) -> Error {
69 Error::ResourceLimit {
70 what: what.to_string(),
71 ceiling: ceiling.to_string(),
72 }
73}
74
75fn read_err(e: impl std::fmt::Display) -> Error {
76 Error::Read(e.to_string())
77}
78
79fn find_verified_object(repo: &gix::Repository, id: ObjectId) -> Result<gix::Object<'_>, Error> {
85 let object = repo.find_object(id).map_err(read_err)?;
86 let computed =
87 gix::objs::compute_hash(repo.object_hash(), object.kind, &object.data).map_err(read_err)?;
88 if computed != id {
89 return Err(Error::Read(format!(
90 "object {id} does not match its content (corrupt or crafted repository)"
91 )));
92 }
93 Ok(object)
94}
95
96fn escape_invalid_utf8(bytes: &[u8]) -> String {
100 use std::fmt::Write as _;
101 let mut out = String::with_capacity(bytes.len());
102 let mut rest = bytes;
103 loop {
104 match std::str::from_utf8(rest) {
105 Ok(valid) => {
106 out.push_str(valid);
107 break;
108 }
109 Err(e) => {
110 let valid_up_to = e.valid_up_to();
111 let valid_prefix = rest.get(..valid_up_to).unwrap_or(&[]);
112 out.push_str(std::str::from_utf8(valid_prefix).unwrap_or_default());
113 let bad_len = e.error_len().unwrap_or(rest.len() - valid_up_to).max(1);
114 let bad_end = (valid_up_to + bad_len).min(rest.len());
115 for &b in rest.get(valid_up_to..bad_end).unwrap_or(&[]) {
116 let _ = write!(out, "\\x{b:02X}");
117 }
118 rest = rest.get(bad_end..).unwrap_or(&[]);
119 if rest.is_empty() {
120 break;
121 }
122 }
123 }
124 }
125 out
126}
127
128pub fn decode(path: &Path, opts: &Options) -> Result<Ir, Error> {
136 decode_with(path, opts, &Limits::default())
137}
138
139pub(crate) fn decode_with(path: &Path, opts: &Options, limits: &Limits) -> Result<Ir, Error> {
140 let repo = open::open(path)?;
141 open::check_repo_floor(&repo)?;
142
143 let (refs, symbolic_ref_count, nested_tag_objects, tagger_time_counts) =
144 scan_refs(&repo, limits)?;
145
146 let carried_tips: Vec<ObjectId> = refs
152 .iter()
153 .filter(|r| matches!(r.kind, ScannedKind::Branch(_) | ScannedKind::Tag(_)))
154 .filter_map(|r| r.commit)
155 .collect();
156 let mut set: BTreeSet<ObjectId> = BTreeSet::new();
157 if !carried_tips.is_empty() {
158 for info in repo
159 .rev_walk(carried_tips.clone())
160 .use_commit_graph(false)
165 .all()
166 .map_err(read_err)?
167 {
168 set.insert(info.map_err(read_err)?.id);
169 if set.len() as u64 > limits.max_commits {
170 return Err(resource_limit(
171 "the commit count",
172 format!("{} commits", limits.max_commits),
173 ));
174 }
175 }
176 }
177
178 let dropped_tips: Vec<ObjectId> = refs
186 .iter()
187 .filter(|r| matches!(r.kind, ScannedKind::Dropped(_)))
188 .filter_map(|r| r.commit)
189 .collect();
190 let dropped_only_commits = count_dropped_only_commits(&repo, dropped_tips, carried_tips);
191
192 let parents = commit_parents(&repo, &set)?;
193 let order = parent_first_order(&set, &parents)?;
194
195 let repo_id = order
197 .iter()
198 .filter(|id| parents.get(*id).is_none_or(Vec::is_empty))
199 .min()
200 .map(|id| id.as_bytes().to_vec())
201 .unwrap_or_default();
202
203 let provenance = ImportProvenance {
204 source: SourceIdentity {
205 kind: SourceKind::Git,
206 repo_id: repo_id.clone(),
207 atom_id: repo_id.clone(),
208 signatures: Vec::new(),
209 extras: Vec::new(),
210 },
211 brygge_version: decoder_version().to_string(),
212 decoder: DECODER.to_string(),
213 decoder_version: decoder_version().to_string(),
214 params: {
215 let mut params = opts.as_params();
216 params.insert("floor".to_string(), floor::joined());
217 params
218 },
219 };
220
221 let mut builder = IrBuilder::new(provenance);
222 let mut sha_to_atom: HashMap<ObjectId, AtomId> = HashMap::new();
223 let mut snap_cache = SnapshotCache::new(count_snapshot_uses(&repo, &order, &parents));
225 let mut time_counts = ParseCounts::default();
226
227 for id in &order {
228 let commit = find_verified_object(&repo, *id)?
229 .try_into_commit()
230 .map_err(read_err)?;
231
232 let child_tree = commit.tree_id().map_err(read_err)?.detach();
233 let child_snap = snapshot(&repo, child_tree, *id, limits, &mut snap_cache)?;
234
235 let ps = parents.get(id).cloned().unwrap_or_default();
236 let mut base_tree: Option<ObjectId> = None;
237 let base_snap = match ps.first() {
238 Some(p0) => {
239 let p_commit = find_verified_object(&repo, *p0)?
240 .try_into_commit()
241 .map_err(read_err)?;
242 let p_tree = p_commit.tree_id().map_err(read_err)?.detach();
243 base_tree = Some(p_tree);
244 snapshot(&repo, p_tree, *p0, limits, &mut snap_cache)?
245 }
246 None => Snapshot::new(),
247 };
248
249 let parent_atoms: Vec<AtomId> = ps
250 .iter()
251 .filter_map(|p| sha_to_atom.get(p).copied())
252 .collect();
253 let (ops, copies) = diff_to_ops(
254 &repo,
255 &base_snap,
256 &child_snap,
257 opts,
258 limits,
259 &mut builder,
260 parent_atoms.first().copied(),
261 )?;
262 snap_cache.release(child_tree);
264 if let Some(t) = base_tree {
265 snap_cache.release(t);
266 }
267 let (metadata, counts) = build_metadata(&commit)?;
268 time_counts.unparseable_times += counts.unparseable_times;
269 time_counts.unparseable_offsets += counts.unparseable_offsets;
270 time_counts.undecodable_encodings += counts.undecodable_encodings;
271 let (signatures, extras) = signatures_and_extras(&commit, *id)?;
272
273 let atom_id = builder.add_atom(AtomDraft {
274 parents: parent_atoms,
275 ops,
276 copies,
277 metadata,
278 source: SourceIdentity {
279 kind: SourceKind::Git,
280 repo_id: repo_id.clone(),
281 atom_id: id.as_bytes().to_vec(),
282 signatures,
283 extras,
284 },
285 status: EpistemicStatus::Stated,
286 })?;
287 sha_to_atom.insert(*id, atom_id);
288 }
289
290 let mut dropped_namespace_counts: BTreeMap<&'static str, u64> = BTreeMap::new();
292 let mut non_commit_refs = 0u64;
293 for r in &refs {
294 match &r.kind {
295 ScannedKind::Branch(name) => {
296 match r.commit.and_then(|c| sha_to_atom.get(&c).copied()) {
297 Some(target) => {
298 builder.add_ref(RefRecord {
299 name: name.clone(),
300 kind: RefKind::Branch,
301 target,
302 status: EpistemicStatus::Stated,
303 source: None,
304 annotation: None,
305 })?;
306 }
307 None => non_commit_refs += 1,
309 }
310 }
311 ScannedKind::Tag(name) => match r.commit.and_then(|c| sha_to_atom.get(&c).copied()) {
312 Some(target) => {
313 let (source, annotation) = match &r.tag_identity {
317 Some((tag_id, signatures, annotation)) => (
318 Some(SourceIdentity {
319 kind: SourceKind::Git,
320 repo_id: repo_id.clone(),
321 atom_id: tag_id.as_bytes().to_vec(),
322 signatures: signatures.clone(),
323 extras: Vec::new(),
324 }),
325 annotation.clone(),
326 ),
327 None => (None, None),
328 };
329 builder.add_ref(RefRecord {
330 name: name.clone(),
331 kind: RefKind::Tag,
332 target,
333 status: EpistemicStatus::Stated,
334 source,
335 annotation,
336 })?;
337 }
338 None => non_commit_refs += 1,
340 },
341 ScannedKind::Dropped(ns) => {
342 *dropped_namespace_counts.entry(ns).or_insert(0) += 1;
343 }
344 }
345 }
346
347 time_counts.unparseable_times += tagger_time_counts.unparseable_times;
348 time_counts.unparseable_offsets += tagger_time_counts.unparseable_offsets;
349
350 builder.set_loss(loss_boundary(
351 &dropped_namespace_counts,
352 dropped_only_commits,
353 non_commit_refs,
354 symbolic_ref_count,
355 time_counts,
356 nested_tag_objects,
357 ));
358 builder.finish().map_err(Error::Ir)
359}
360
361enum DroppedOnlyCommits {
363 Counted(u64),
365 Unavailable,
372}
373
374fn count_dropped_only_commits(
381 repo: &gix::Repository,
382 dropped_tips: Vec<ObjectId>,
383 carried_tips: Vec<ObjectId>,
384) -> DroppedOnlyCommits {
385 if dropped_tips.is_empty() {
386 return DroppedOnlyCommits::Counted(0);
387 }
388 let Ok(walk) = repo
389 .rev_walk(dropped_tips)
390 .with_hidden(carried_tips)
391 .use_commit_graph(false)
392 .all()
393 else {
394 return DroppedOnlyCommits::Unavailable;
395 };
396 let mut count = 0u64;
397 for info in walk {
398 if info.is_err() {
399 return DroppedOnlyCommits::Unavailable;
400 }
401 count += 1;
402 }
403 DroppedOnlyCommits::Counted(count)
404}
405
406struct ScannedRef {
408 kind: ScannedKind,
409 commit: Option<ObjectId>,
411 tag_identity: Option<TagIdentity>,
414}
415
416enum ScannedKind {
417 Branch(String),
418 Tag(String),
419 Dropped(&'static str),
420}
421
422const HEADS_PREFIX: &[u8] = b"refs/heads/";
423const TAGS_PREFIX: &[u8] = b"refs/tags/";
424
425fn scan_refs(
430 repo: &gix::Repository,
431 limits: &Limits,
432) -> Result<(Vec<ScannedRef>, u64, u64, ParseCounts), Error> {
433 let mut out = Vec::new();
434 let mut symbolic_refs = 0u64;
435 let mut nested_tag_objects = 0u64;
436 let mut tagger_time_counts = ParseCounts::default();
437 let platform = repo.references().map_err(read_err)?;
438 for r in platform.all().map_err(read_err)? {
439 let mut r = r.map_err(read_err)?;
440 let raw_name: Vec<u8> = r.name().as_bstr().to_vec();
441 let name = raw_name.to_str_lossy(); if raw_name.starts_with(b"refs/replace/") {
445 return Err(Error::FloorRefusal {
446 feature: floor::REPLACE_REF.to_string(),
447 reason: format!(
448 "{} rewrites the object graph a reader would see; refused rather than \
449 importing the rewritten view silently",
450 escape_invalid_utf8(&raw_name)
451 ),
452 });
453 }
454
455 let Some(direct) = r.try_id().map(|id| id.detach()) else {
463 symbolic_refs += 1;
464 continue;
465 };
466
467 let carried_suffix: Option<(&[u8], bool)> = if raw_name.starts_with(HEADS_PREFIX) {
471 Some((raw_name.get(HEADS_PREFIX.len()..).unwrap_or(&[]), true))
472 } else if raw_name.starts_with(TAGS_PREFIX) {
473 Some((raw_name.get(TAGS_PREFIX.len()..).unwrap_or(&[]), false))
474 } else {
475 None
476 };
477 if let Some((suffix, _)) = carried_suffix {
478 if std::str::from_utf8(suffix).is_err() {
479 return Err(Error::FloorRefusal {
480 feature: floor::NON_UTF8_REF_NAME.to_string(),
481 reason: format!(
482 "ref name '{}' is not valid UTF-8 (invalid bytes shown as \\xNN)",
483 escape_invalid_utf8(&raw_name)
484 ),
485 });
486 }
487 }
488
489 let mut tag_identity = None;
490 let (kind, commit) = if let Some((suffix, is_branch)) = carried_suffix {
491 let suffix_str = std::str::from_utf8(suffix).unwrap_or_default().to_string();
493 if is_branch {
494 let (commit, nested) = peel_carried(repo, direct, limits, false)?;
497 nested_tag_objects += nested;
498 (ScannedKind::Branch(suffix_str), commit)
499 } else {
500 let (identity, counts) = annotated_tag_identity(repo, direct)?;
501 tag_identity = identity;
502 tagger_time_counts.unparseable_times += counts.unparseable_times;
503 tagger_time_counts.unparseable_offsets += counts.unparseable_offsets;
504 let (commit, nested) = peel_carried(repo, direct, limits, true)?;
505 nested_tag_objects += nested;
506 (ScannedKind::Tag(suffix_str), commit)
507 }
508 } else {
509 let dropped_kind = if name.starts_with("refs/remotes/") {
512 ScannedKind::Dropped("remote-tracking")
513 } else if name.starts_with("refs/notes/") {
514 ScannedKind::Dropped("notes")
515 } else if name == "refs/stash" {
516 ScannedKind::Dropped("stash")
517 } else {
518 ScannedKind::Dropped("other")
520 };
521 let lenient_commit = r.peel_to_id().ok().map(|id| id.detach()).filter(|id| {
522 repo.find_object(*id)
523 .is_ok_and(|o| matches!(o.kind, gix::objs::Kind::Commit))
524 });
525 (dropped_kind, lenient_commit)
526 };
527 out.push(ScannedRef {
528 kind,
529 commit,
530 tag_identity,
531 });
532 }
533 Ok((out, symbolic_refs, nested_tag_objects, tagger_time_counts))
534}
535
536fn peel_carried(
546 repo: &gix::Repository,
547 direct: ObjectId,
548 limits: &Limits,
549 direct_tag_is_carried: bool,
550) -> Result<(Option<ObjectId>, u64), Error> {
551 let mut current = direct;
552 let mut hops = 0usize;
553 let mut nested_tags = 0u64;
554 loop {
555 let object = find_verified_object(repo, current)?;
556 match object.kind {
557 gix::objs::Kind::Commit => return Ok((Some(current), nested_tags)),
558 gix::objs::Kind::Tag => {
559 hops += 1;
560 if hops > limits.max_tag_chain {
561 return Err(resource_limit(
562 "the tag chain",
563 format!("{} tag(s)", limits.max_tag_chain),
564 ));
565 }
566 if hops > 1 || !direct_tag_is_carried {
567 nested_tags += 1;
568 }
569 let tag = object.try_into_tag().map_err(read_err)?;
570 let decoded = tag.decode().map_err(read_err)?;
571 current = decoded.target();
572 }
573 _ => return Ok((None, nested_tags)),
574 }
575 }
576}
577
578fn annotated_tag_identity(
586 repo: &gix::Repository,
587 direct: ObjectId,
588) -> Result<(Option<TagIdentity>, ParseCounts), Error> {
589 let object = find_verified_object(repo, direct)?;
590 if !matches!(object.kind, gix::objs::Kind::Tag) {
591 return Ok((None, ParseCounts::default()));
592 }
593 let tag = object.try_into_tag().map_err(read_err)?;
594 let decoded = tag.decode().map_err(read_err)?;
595 let signatures = decoded
596 .signature
597 .map(|s| Signature {
598 label: "gpgsig".to_string(),
599 bytes: s.to_vec(),
600 })
601 .into_iter()
602 .collect();
603 let mut counts = ParseCounts::default();
604 let tagger_sig = decoded.tagger().map_err(read_err)?;
605 let tagger = tagger_sig.map(|sig| Identity {
606 name: Text {
607 bytes: sig.name.to_vec(),
608 encoding: None,
609 },
610 email: Some(Text {
611 bytes: sig.email.to_vec(),
612 encoding: None,
613 }),
614 });
615 let time = tagger_sig.and_then(|sig| {
616 let seconds = strict_seconds(sig.time);
617 if seconds.is_none() {
618 counts.unparseable_times += 1;
619 }
620 seconds.map(|seconds| {
621 let offset_minutes = strict_offset_minutes(sig.time);
622 if offset_minutes.is_none() {
623 counts.unparseable_offsets += 1;
624 }
625 Time {
626 seconds,
627 offset_minutes,
628 }
629 })
630 });
631 let message = Text {
632 bytes: decoded.message.to_vec(),
633 encoding: None,
634 };
635 let annotation = Annotation {
636 tagger,
637 time,
638 message: Some(message),
639 };
640 Ok((Some((direct, signatures, Some(annotation))), counts))
641}
642
643fn commit_parents(
651 repo: &gix::Repository,
652 set: &BTreeSet<ObjectId>,
653) -> Result<BTreeMap<ObjectId, Vec<ObjectId>>, Error> {
654 let mut parents = BTreeMap::new();
655 for id in set {
656 let commit = find_verified_object(repo, *id)?
657 .try_into_commit()
658 .map_err(read_err)?;
659 let mut ps = Vec::new();
660 for p in commit.parent_ids() {
661 let p = p.detach();
662 if !set.contains(&p) {
663 return Err(Error::Read(
664 "history walk disagrees with commit content".to_string(),
665 ));
666 }
667 ps.push(p);
668 }
669 parents.insert(*id, ps);
670 }
671 Ok(parents)
672}
673
674fn parent_first_order(
676 set: &BTreeSet<ObjectId>,
677 parents: &BTreeMap<ObjectId, Vec<ObjectId>>,
678) -> Result<Vec<ObjectId>, Error> {
679 let mut indeg: BTreeMap<ObjectId, usize> = set.iter().map(|id| (*id, 0usize)).collect();
680 let mut children: BTreeMap<ObjectId, Vec<ObjectId>> = BTreeMap::new();
681 for (id, ps) in parents {
682 for p in ps {
683 children.entry(*p).or_default().push(*id);
684 if let Some(d) = indeg.get_mut(id) {
685 *d += 1;
686 }
687 }
688 }
689 let mut ready: BTreeSet<ObjectId> = indeg
690 .iter()
691 .filter_map(|(id, d)| (*d == 0).then_some(*id))
692 .collect();
693 let mut order = Vec::with_capacity(set.len());
694 while let Some(id) = ready.iter().next().copied() {
695 ready.remove(&id);
696 order.push(id);
697 if let Some(kids) = children.get(&id) {
698 for kid in kids {
699 if let Some(d) = indeg.get_mut(kid) {
700 *d = d.saturating_sub(1);
701 if *d == 0 {
702 ready.insert(*kid);
703 }
704 }
705 }
706 }
707 }
708 if order.len() != set.len() {
709 return Err(Error::Read(
710 "commit graph contains a cycle (a Git history must be acyclic)".to_string(),
711 ));
712 }
713 Ok(order)
714}
715
716struct SnapshotCache {
729 snaps: HashMap<ObjectId, Snapshot>,
730 remaining: HashMap<ObjectId, usize>,
733}
734
735impl SnapshotCache {
736 fn new(uses: HashMap<ObjectId, usize>) -> Self {
737 Self {
738 snaps: HashMap::new(),
739 remaining: uses,
740 }
741 }
742
743 fn get_or_build(
745 &mut self,
746 tree_id: ObjectId,
747 build: impl FnOnce() -> Result<Snapshot, Error>,
748 ) -> Result<Snapshot, Error> {
749 if let Some(s) = self.snaps.get(&tree_id) {
750 return Ok(s.clone());
751 }
752 let out = build()?;
753 self.snaps.insert(tree_id, out.clone());
754 Ok(out)
755 }
756
757 fn release(&mut self, tree_id: ObjectId) {
759 if let Some(n) = self.remaining.get_mut(&tree_id) {
760 *n = n.saturating_sub(1);
761 if *n == 0 {
762 self.remaining.remove(&tree_id);
763 self.snaps.remove(&tree_id);
764 }
765 }
766 }
767
768 #[cfg(test)]
770 fn len(&self) -> usize {
771 self.snaps.len()
772 }
773}
774
775fn count_snapshot_uses(
780 repo: &gix::Repository,
781 order: &[ObjectId],
782 parents: &BTreeMap<ObjectId, Vec<ObjectId>>,
783) -> HashMap<ObjectId, usize> {
784 let mut tree_of: HashMap<ObjectId, ObjectId> = HashMap::with_capacity(order.len());
785 let mut uses: HashMap<ObjectId, usize> = HashMap::new();
786 for id in order {
787 let Some(tree) = find_verified_object(repo, *id)
788 .ok()
789 .and_then(|o| o.try_into_commit().ok())
790 .and_then(|c| c.tree_id().ok())
791 .map(gix::Id::detach)
792 else {
793 continue;
794 };
795 tree_of.insert(*id, tree);
796 *uses.entry(tree).or_insert(0) += 1;
797 if let Some(p0) = parents.get(id).and_then(|ps| ps.first()) {
798 if let Some(pt) = tree_of.get(p0) {
799 *uses.entry(*pt).or_insert(0) += 1;
800 }
801 }
802 }
803 uses
804}
805
806fn snapshot(
809 repo: &gix::Repository,
810 tree_id: ObjectId,
811 commit_id: ObjectId,
812 limits: &Limits,
813 cache: &mut SnapshotCache,
814) -> Result<Snapshot, Error> {
815 cache.get_or_build(tree_id, || {
816 let mut out = Snapshot::new();
817 walk_tree(repo, tree_id, commit_id, limits, &mut out)?;
818 Ok(out)
819 })
820}
821
822fn walk_tree(
828 repo: &gix::Repository,
829 root_tree_id: ObjectId,
830 commit_id: ObjectId,
831 limits: &Limits,
832 out: &mut Snapshot,
833) -> Result<(), Error> {
834 let mut stack: Vec<(ObjectId, String, usize)> = vec![(root_tree_id, String::new(), 1)];
836 while let Some((tree_id, prefix, depth)) = stack.pop() {
837 let tree = find_verified_object(repo, tree_id)?
838 .try_into_tree()
839 .map_err(read_err)?;
840 for entry in tree.iter() {
841 let entry = entry.map_err(read_err)?;
842 let raw_name = entry.filename(); let Ok(name) = std::str::from_utf8(raw_name) else {
844 return Err(Error::FloorRefusal {
845 feature: floor::NON_UTF8_PATH.to_string(),
846 reason: format!(
847 "commit {commit_id}: path '{prefix}{}{}' is not valid UTF-8 (invalid bytes \
848 shown as \\xNN)",
849 if prefix.is_empty() { "" } else { "/" },
850 escape_invalid_utf8(raw_name)
851 ),
852 });
853 };
854 let path = if prefix.is_empty() {
855 name.to_string()
856 } else {
857 format!("{prefix}/{name}")
858 };
859 if path.len() > limits.max_path_bytes {
860 return Err(resource_limit(
861 "a path",
862 format!("{} bytes", limits.max_path_bytes),
863 ));
864 }
865 let mode = entry.mode();
866 let oid = entry.oid().to_owned();
867 match mode.kind() {
868 gix::objs::tree::EntryKind::Tree => {
869 let child_depth = depth + 1;
870 if child_depth > limits.max_tree_depth {
871 return Err(resource_limit(
872 "the tree nesting",
873 format!("{} levels", limits.max_tree_depth),
874 ));
875 }
876 stack.push((oid, path, child_depth));
877 }
878 gix::objs::tree::EntryKind::Commit => {
879 return Err(Error::FloorRefusal {
880 feature: floor::SUBMODULE.to_string(),
881 reason: format!(
882 "submodule (gitlink) at '{path}' points outside this repository; refused \
883 rather than approximated"
884 ),
885 });
886 }
887 _ => {
888 if out.contains_key(&path) {
892 return Err(Error::Read(format!(
893 "commit {commit_id}: duplicate path '{path}' in tree snapshot"
894 )));
895 }
896 out.insert(path, (oid, u32::from(mode.value())));
897 }
898 }
899 }
900 }
901 Ok(())
902}
903
904fn diff_to_ops(
909 repo: &gix::Repository,
910 base: &Snapshot,
911 child: &Snapshot,
912 opts: &Options,
913 limits: &Limits,
914 builder: &mut IrBuilder,
915 from_parent: Option<AtomId>,
916) -> Result<(Vec<PathOp>, Vec<CopyRecord>), Error> {
917 let mut ops = Vec::new();
918 let mut added_by_oid: BTreeMap<ObjectId, Vec<String>> = BTreeMap::new();
919 let mut deleted_by_oid: BTreeMap<ObjectId, Vec<String>> = BTreeMap::new();
920
921 for (path, (oid, mode)) in child {
922 match base.get(path) {
923 None => {
924 let blob = builder.add_blob(blob_bytes(repo, *oid, limits)?);
925 ops.push(PathOp::Add {
926 path: path.clone(),
927 blob,
928 mode: *mode,
929 status: EpistemicStatus::Stated,
930 });
931 added_by_oid.entry(*oid).or_default().push(path.clone());
932 }
933 Some((base_oid, base_mode)) => {
934 if base_oid != oid || base_mode != mode {
935 let blob = builder.add_blob(blob_bytes(repo, *oid, limits)?);
936 ops.push(PathOp::Modify {
937 path: path.clone(),
938 blob,
939 mode: *mode,
940 status: EpistemicStatus::Stated,
941 });
942 }
943 }
944 }
945 }
946 for (path, (oid, _)) in base {
947 if !child.contains_key(path) {
948 ops.push(PathOp::Delete {
949 path: path.clone(),
950 status: EpistemicStatus::Stated,
951 });
952 deleted_by_oid.entry(*oid).or_default().push(path.clone());
953 }
954 }
955
956 let mut copies = Vec::new();
957 if opts.infer_renames {
958 if let Some(from_atom) = from_parent {
967 for (oid, froms) in &deleted_by_oid {
968 let [from] = froms.as_slice() else {
969 continue; };
971 let Some([to]) = added_by_oid.get(oid).map(Vec::as_slice) else {
972 continue; };
974 copies.push(CopyRecord {
975 from: from.clone(),
976 from_atom,
977 to: to.clone(),
978 status: EpistemicStatus::Derived(Derivation {
979 kind: DerivationKind::InferredRename,
980 by: DECODER.to_string(),
981 decoder_version: decoder_version().to_string(),
982 params: opts.as_params(),
983 confidence: Some(100),
984 }),
985 });
986 }
987 }
988 }
989 Ok((ops, copies))
990}
991
992fn blob_bytes(repo: &gix::Repository, oid: ObjectId, limits: &Limits) -> Result<Vec<u8>, Error> {
996 let header = repo.find_header(oid).map_err(read_err)?;
997 if header.size() > limits.max_blob_bytes {
998 return Err(resource_limit(
999 "a blob",
1000 format!("{} bytes", limits.max_blob_bytes),
1001 ));
1002 }
1003 Ok(find_verified_object(repo, oid)?
1004 .try_into_blob()
1005 .map_err(read_err)?
1006 .data
1007 .clone())
1008}
1009
1010fn strict_seconds(raw: &str) -> Option<i64> {
1017 let token = raw.split_whitespace().next()?;
1018 let digits = token.strip_prefix('-').unwrap_or(token);
1019 if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
1020 return None;
1021 }
1022 token.parse::<i64>().ok()
1023}
1024
1025fn strict_offset_minutes(raw: &str) -> Option<i16> {
1031 let mut tokens = raw.split_whitespace();
1032 let _seconds = tokens.next()?;
1033 let tz = tokens.next()?;
1034 let sign = match tz.as_bytes().first()? {
1035 b'+' => 1i32,
1036 b'-' => -1i32,
1037 _ => return None,
1038 };
1039 let digits = tz.get(1..)?;
1040 if digits.len() != 4 || !digits.bytes().all(|b| b.is_ascii_digit()) {
1041 return None;
1042 }
1043 let hh: i32 = digits.get(..2)?.parse().ok()?;
1044 let mm: i32 = digits.get(2..)?.parse().ok()?;
1045 if mm >= 60 {
1046 return None;
1047 }
1048 i16::try_from(sign * (hh * 60 + mm)).ok()
1049}
1050
1051fn build_metadata(commit: &gix::Commit<'_>) -> Result<(MetadataClaims, ParseCounts), Error> {
1061 let author = commit.author().map_err(read_err)?;
1062 let committer = commit.committer().map_err(read_err)?;
1063 let decoded = commit.decode().map_err(read_err)?;
1064 let message = decoded.message;
1065
1066 let mut counts = ParseCounts::default();
1067 let message_encoding = match decoded.encoding {
1068 Some(e) => match std::str::from_utf8(e) {
1069 Ok(s) => Some(s.to_string()),
1070 Err(_) => {
1071 counts.undecodable_encodings += 1;
1074 None
1075 }
1076 },
1077 None => None,
1078 };
1079 let author_time = strict_seconds(author.time);
1080 if author_time.is_none() {
1081 counts.unparseable_times += 1;
1082 }
1083 let author_offset = strict_offset_minutes(author.time);
1084 if author_time.is_some() && author_offset.is_none() {
1085 counts.unparseable_offsets += 1;
1086 }
1087 let commit_time = strict_seconds(committer.time);
1088 if commit_time.is_none() {
1089 counts.unparseable_times += 1;
1090 }
1091 let commit_offset = strict_offset_minutes(committer.time);
1092 if commit_time.is_some() && commit_offset.is_none() {
1093 counts.unparseable_offsets += 1;
1094 }
1095 let raw_text = |bytes: &[u8]| Text {
1096 bytes: bytes.to_vec(),
1097 encoding: None,
1098 };
1099 Ok((
1100 MetadataClaims {
1101 author: Some(Identity {
1102 name: raw_text(author.name.as_ref()),
1103 email: Some(raw_text(author.email.as_ref())),
1104 }),
1105 author_time: author_time.map(|seconds| Time {
1106 seconds,
1107 offset_minutes: author_offset,
1108 }),
1109 committer: Some(Identity {
1110 name: raw_text(committer.name.as_ref()),
1111 email: Some(raw_text(committer.email.as_ref())),
1112 }),
1113 commit_time: commit_time.map(|seconds| Time {
1114 seconds,
1115 offset_minutes: commit_offset,
1116 }),
1117 message: Some(Text {
1118 bytes: message.to_vec(),
1119 encoding: message_encoding,
1120 }),
1121 },
1122 counts,
1123 ))
1124}
1125
1126#[derive(Debug, Clone, Copy, Default)]
1130struct ParseCounts {
1131 unparseable_times: u64,
1132 unparseable_offsets: u64,
1133 undecodable_encodings: u64,
1134}
1135
1136fn signatures_and_extras(
1145 commit: &gix::Commit<'_>,
1146 id: ObjectId,
1147) -> Result<(Vec<Signature>, Vec<Extra>), Error> {
1148 let decoded = commit.decode().map_err(read_err)?;
1149 let mut signatures = Vec::new();
1150 let mut extras = Vec::new();
1151 for (name, value) in &decoded.extra_headers {
1152 let Ok(label) = std::str::from_utf8(name) else {
1153 return Err(Error::FloorRefusal {
1154 feature: floor::NON_UTF8_COMMIT_HEADER_NAME.to_string(),
1155 reason: format!(
1156 "commit {id}: header name '{}' is not valid UTF-8 (invalid bytes shown as \\xNN)",
1157 escape_invalid_utf8(name)
1158 ),
1159 });
1160 };
1161 match label {
1162 "gpgsig" | "gpgsig-sha256" => signatures.push(Signature {
1163 label: label.to_string(),
1164 bytes: value.to_vec(),
1165 }),
1166 _ => extras.push(Extra {
1167 label: label.to_string(),
1168 bytes: value.to_vec(),
1169 }),
1170 }
1171 }
1172 Ok((signatures, extras))
1173}
1174
1175fn loss_boundary(
1183 dropped_namespace_counts: &BTreeMap<&'static str, u64>,
1184 dropped_only_commits: DroppedOnlyCommits,
1185 non_commit_refs: u64,
1186 symbolic_refs: u64,
1187 time_counts: ParseCounts,
1188 nested_tag_objects: u64,
1189) -> LossBoundary {
1190 let mut dropped = vec![
1191 DropRecord {
1192 class: LossClass::Representation,
1193 what: "packfile and delta layout, physical object store".to_string(),
1194 reason: "representation not assertion; reconstructible from the objects".to_string(),
1195 },
1196 DropRecord {
1197 class: LossClass::Representation,
1198 what: "index and working tree".to_string(),
1199 reason: "local state, not history".to_string(),
1200 },
1201 DropRecord {
1202 class: LossClass::Representation,
1203 what: "reflogs".to_string(),
1204 reason: "local operation log, not history".to_string(),
1205 },
1206 ];
1207 for (ns, count) in dropped_namespace_counts {
1208 dropped.push(DropRecord {
1209 class: LossClass::Representation,
1210 what: format!("{ns} refs ({count})"),
1211 reason: "workflow/representation refs, not authored history".to_string(),
1212 });
1213 }
1214 match dropped_only_commits {
1215 DroppedOnlyCommits::Counted(0) => {}
1216 DroppedOnlyCommits::Counted(n) => {
1217 dropped.push(DropRecord {
1218 class: LossClass::Representation,
1219 what: format!("commits reachable only from dropped refs ({n})"),
1220 reason:
1221 "workflow state (stash, notes, remote-tracking), not authored history of a \
1222 carried ref"
1223 .to_string(),
1224 });
1225 }
1226 DroppedOnlyCommits::Unavailable => {
1227 dropped.push(DropRecord {
1228 class: LossClass::Representation,
1229 what: "commits reachable only from dropped refs (count unavailable)".to_string(),
1230 reason: "a commit in dropped-only history could not be read".to_string(),
1231 });
1232 }
1233 }
1234 if non_commit_refs > 0 {
1235 dropped.push(DropRecord {
1236 class: LossClass::Other,
1237 what: format!("refs to non-commit objects ({non_commit_refs})"),
1238 reason: "a tag or branch naming a tree or blob; the IR's refs point at history atoms"
1239 .to_string(),
1240 });
1241 }
1242 if symbolic_refs > 0 {
1243 dropped.push(DropRecord {
1244 class: LossClass::Representation,
1245 what: format!("symbolic refs ({symbolic_refs})"),
1246 reason:
1247 "an alias to another ref; the IR has no alias concept; the target ref is carried \
1248 on its own"
1249 .to_string(),
1250 });
1251 }
1252 if time_counts.unparseable_times > 0 {
1253 dropped.push(DropRecord {
1254 class: LossClass::Other,
1255 what: format!(
1256 "unparseable author/committer/tagger times ({})",
1257 time_counts.unparseable_times
1258 ),
1259 reason: "the source's time field could not be parsed; the claim is absent rather than \
1260 fabricated"
1261 .to_string(),
1262 });
1263 }
1264 if time_counts.unparseable_offsets > 0 {
1265 dropped.push(DropRecord {
1266 class: LossClass::Other,
1267 what: format!(
1268 "unparseable author/committer/tagger timezone offsets ({})",
1269 time_counts.unparseable_offsets
1270 ),
1271 reason: "the source's timezone offset could not be parsed strictly (`+HHMM`/`-HHMM`); \
1272 the time is carried without an offset rather than a fabricated or salvaged one"
1273 .to_string(),
1274 });
1275 }
1276 if time_counts.undecodable_encodings > 0 {
1277 dropped.push(DropRecord {
1278 class: LossClass::Other,
1279 what: format!(
1280 "undecodable encoding headers ({})",
1281 time_counts.undecodable_encodings
1282 ),
1283 reason:
1284 "the commit's declared `encoding` header value was not valid UTF-8, so it is not \
1285 carried on the message's `Text.encoding`"
1286 .to_string(),
1287 });
1288 }
1289 if nested_tag_objects > 0 {
1290 dropped.push(DropRecord {
1291 class: LossClass::Other,
1292 what: format!("nested tag objects not carried ({nested_tag_objects})"),
1293 reason: "an intermediate tag object in a tag-of-a-tag chain; only the outer tag's \
1294 annotation is carried"
1295 .to_string(),
1296 });
1297 }
1298 LossBoundary { dropped }
1299}
1300
1301#[cfg(test)]
1302mod tests;