1use std::collections::{BTreeMap, BTreeSet, HashMap};
11use std::path::Path;
12
13use gix::ObjectId;
14use gix::bstr::ByteSlice;
15
16use brygge_ir::Storage;
17use brygge_ir::builder::{AtomDraft, IrBuilder};
18use brygge_ir::model::{
19 Annotation, AtomId, Content, CopyRecord, DropRecord, Extra, Identity, ImportProvenance, Ir,
20 LossBoundary, LossClass, MetadataClaims, PathOp, RefKind, RefRecord, Signature, SourceIdentity,
21 SourceKind, Text, Time,
22};
23use brygge_ir::status::{Derivation, DerivationKind, EpistemicStatus};
24
25use crate::{Error, Options, decoder_version, floor, open};
26
27type Snapshot = BTreeMap<String, (ObjectId, u32)>;
29
30type TagIdentity = (ObjectId, Vec<Signature>, Option<Annotation>);
33
34const DECODER: &str = "brygge-decode-git";
35
36#[derive(Debug, Clone, Copy)]
39pub(crate) struct Limits {
40 pub(crate) max_blob_bytes: u64,
43 pub(crate) max_commits: u64,
46 pub(crate) max_path_bytes: usize,
48 pub(crate) max_tree_depth: usize,
51 pub(crate) max_tag_chain: usize,
55 pub(crate) max_tree_entries: usize,
62}
63
64impl Default for Limits {
65 fn default() -> Self {
66 Self {
67 max_blob_bytes: 1024 * 1024 * 1024,
68 max_commits: 10_000_000,
69 max_path_bytes: 4096,
70 max_tree_depth: 256,
71 max_tag_chain: 32,
72 max_tree_entries: 10_000_000,
73 }
74 }
75}
76
77fn resource_limit(what: &str, ceiling: impl std::fmt::Display) -> Error {
78 Error::ResourceLimit {
79 what: what.to_string(),
80 ceiling: ceiling.to_string(),
81 }
82}
83
84fn read_err(e: impl std::fmt::Display) -> Error {
85 Error::Read(e.to_string())
86}
87
88fn find_verified_object(repo: &gix::Repository, id: ObjectId) -> Result<gix::Object<'_>, Error> {
94 let object = repo.find_object(id).map_err(read_err)?;
95 let computed =
96 gix::objs::compute_hash(repo.object_hash(), object.kind, &object.data).map_err(read_err)?;
97 if computed != id {
98 return Err(Error::Read(format!(
99 "object {id} does not match its content (corrupt or crafted repository)"
100 )));
101 }
102 Ok(object)
103}
104
105fn escape_invalid_utf8(bytes: &[u8]) -> String {
109 use std::fmt::Write as _;
110 let mut out = String::with_capacity(bytes.len());
111 let mut rest = bytes;
112 loop {
113 match std::str::from_utf8(rest) {
114 Ok(valid) => {
115 out.push_str(valid);
116 break;
117 }
118 Err(e) => {
119 let valid_up_to = e.valid_up_to();
120 let valid_prefix = rest.get(..valid_up_to).unwrap_or(&[]);
121 out.push_str(std::str::from_utf8(valid_prefix).unwrap_or_default());
122 let bad_len = e.error_len().unwrap_or(rest.len() - valid_up_to).max(1);
123 let bad_end = (valid_up_to + bad_len).min(rest.len());
124 for &b in rest.get(valid_up_to..bad_end).unwrap_or(&[]) {
125 let _ = write!(out, "\\x{b:02X}");
126 }
127 rest = rest.get(bad_end..).unwrap_or(&[]);
128 if rest.is_empty() {
129 break;
130 }
131 }
132 }
133 }
134 out
135}
136
137pub fn decode(path: &Path, opts: &Options) -> Result<Ir, Error> {
146 decode_with_storage(path, opts, &Storage::Memory)
147}
148
149pub fn decode_with_storage(path: &Path, opts: &Options, storage: &Storage) -> Result<Ir, Error> {
155 decode_with(path, opts, &Limits::default(), storage)
156}
157
158pub(crate) fn decode_with(
159 path: &Path,
160 opts: &Options,
161 limits: &Limits,
162 storage: &Storage,
163) -> Result<Ir, Error> {
164 for prefix in &opts.carry_extra_namespaces {
165 if !prefix.ends_with('/') {
166 return Err(Error::InvalidOptions(format!(
167 "carry_extra_namespaces: '{prefix}' does not end with '/', so it would match no ref"
168 )));
169 }
170 }
171 let repo = open::open(path)?;
172 open::check_repo_floor(&repo)?;
173
174 let (refs, symbolic_ref_count, nested_tag_objects, tagger_time_counts) =
175 scan_refs(&repo, limits, opts)?;
176
177 let carried_tips: Vec<ObjectId> = refs
183 .iter()
184 .filter(|r| {
185 matches!(
186 r.kind,
187 ScannedKind::Branch(_) | ScannedKind::Tag(_) | ScannedKind::Extra(_)
188 )
189 })
190 .filter_map(|r| r.commit)
191 .collect();
192 let mut set: BTreeSet<ObjectId> = BTreeSet::new();
193 if !carried_tips.is_empty() {
194 for info in repo
195 .rev_walk(carried_tips.clone())
196 .use_commit_graph(false)
201 .all()
202 .map_err(read_err)?
203 {
204 set.insert(info.map_err(read_err)?.id);
205 if set.len() as u64 > limits.max_commits {
206 return Err(resource_limit(
207 "the commit count",
208 format!("{} commits", limits.max_commits),
209 ));
210 }
211 }
212 }
213
214 let dropped_tips: Vec<ObjectId> = refs
222 .iter()
223 .filter(|r| matches!(r.kind, ScannedKind::Dropped(_)))
224 .filter_map(|r| r.commit)
225 .collect();
226 let dropped_only_commits = count_dropped_only_commits(&repo, dropped_tips, carried_tips);
227
228 let parents = commit_parents(&repo, &set)?;
229 let order = parent_first_order(&set, &parents)?;
230
231 let repo_id = order
233 .iter()
234 .filter(|id| parents.get(*id).is_none_or(Vec::is_empty))
235 .min()
236 .map(|id| id.as_bytes().to_vec())
237 .unwrap_or_default();
238
239 let provenance = ImportProvenance {
240 source: SourceIdentity {
241 kind: SourceKind::Git,
242 repo_id: repo_id.clone(),
243 atom_id: repo_id.clone(),
244 signatures: Vec::new(),
245 extras: Vec::new(),
246 },
247 brygge_version: decoder_version().to_string(),
248 decoder: DECODER.to_string(),
249 decoder_version: decoder_version().to_string(),
250 params: {
251 let mut params = opts.as_params();
252 params.insert("floor".to_string(), floor::joined());
253 params
254 },
255 };
256
257 let mut builder = IrBuilder::with_storage(provenance, storage).map_err(Error::Ir)?;
258 let mut sha_to_atom: HashMap<ObjectId, AtomId> = HashMap::new();
259 let mut snap_cache = SnapshotCache::new(count_snapshot_uses(&repo, &order, &parents));
261 let mut time_counts = ParseCounts::default();
262
263 for id in &order {
264 let commit = find_verified_object(&repo, *id)?
265 .try_into_commit()
266 .map_err(read_err)?;
267
268 let child_tree = commit.tree_id().map_err(read_err)?.detach();
269 let child_snap = snapshot(&repo, child_tree, *id, limits, &mut snap_cache)?;
270
271 let ps = parents.get(id).cloned().unwrap_or_default();
272 let mut base_tree: Option<ObjectId> = None;
273 let base_snap = match ps.first() {
274 Some(p0) => {
275 let p_commit = find_verified_object(&repo, *p0)?
276 .try_into_commit()
277 .map_err(read_err)?;
278 let p_tree = p_commit.tree_id().map_err(read_err)?.detach();
279 base_tree = Some(p_tree);
280 snapshot(&repo, p_tree, *p0, limits, &mut snap_cache)?
281 }
282 None => Snapshot::new(),
283 };
284
285 let parent_atoms: Vec<AtomId> = ps
286 .iter()
287 .filter_map(|p| sha_to_atom.get(p).copied())
288 .collect();
289 let (ops, copies) = diff_to_ops(
290 &repo,
291 &base_snap,
292 &child_snap,
293 opts,
294 limits,
295 &mut builder,
296 parent_atoms.first().copied(),
297 )?;
298 snap_cache.release(child_tree);
300 if let Some(t) = base_tree {
301 snap_cache.release(t);
302 }
303 let (metadata, counts) = build_metadata(&commit)?;
304 time_counts.unparseable_times += counts.unparseable_times;
305 time_counts.unparseable_offsets += counts.unparseable_offsets;
306 time_counts.undecodable_encodings += counts.undecodable_encodings;
307 let (signatures, extras) = signatures_and_extras(&commit, *id)?;
308
309 let atom_id = builder.add_atom(AtomDraft {
310 parents: parent_atoms,
311 ops,
312 copies,
313 metadata,
314 source: SourceIdentity {
315 kind: SourceKind::Git,
316 repo_id: repo_id.clone(),
317 atom_id: id.as_bytes().to_vec(),
318 signatures,
319 extras,
320 },
321 status: EpistemicStatus::Stated,
322 })?;
323 sha_to_atom.insert(*id, atom_id);
324 }
325
326 let mut dropped_namespace_counts: BTreeMap<&'static str, u64> = BTreeMap::new();
328 let mut non_commit_refs = 0u64;
329 for r in &refs {
330 match &r.kind {
331 ScannedKind::Branch(name) => {
332 match r.commit.and_then(|c| sha_to_atom.get(&c).copied()) {
333 Some(target) => {
334 builder.add_ref(RefRecord {
335 name: name.clone(),
336 kind: RefKind::Branch,
337 target,
338 status: EpistemicStatus::Stated,
339 source: None,
340 annotation: None,
341 })?;
342 }
343 None => non_commit_refs += 1,
345 }
346 }
347 ScannedKind::Tag(name) => match r.commit.and_then(|c| sha_to_atom.get(&c).copied()) {
348 Some(target) => {
349 let (source, annotation) = match &r.tag_identity {
353 Some((tag_id, signatures, annotation)) => (
354 Some(SourceIdentity {
355 kind: SourceKind::Git,
356 repo_id: repo_id.clone(),
357 atom_id: tag_id.as_bytes().to_vec(),
358 signatures: signatures.clone(),
359 extras: Vec::new(),
360 }),
361 annotation.clone(),
362 ),
363 None => (None, None),
364 };
365 builder.add_ref(RefRecord {
366 name: name.clone(),
367 kind: RefKind::Tag,
368 target,
369 status: EpistemicStatus::Stated,
370 source,
371 annotation,
372 })?;
373 }
374 None => non_commit_refs += 1,
376 },
377 ScannedKind::Extra(name) => {
378 match r.commit.and_then(|c| sha_to_atom.get(&c).copied()) {
379 Some(target) => {
380 builder.add_ref(RefRecord {
381 name: name.clone(),
382 kind: RefKind::Other("carry-extra-namespaces".to_string()),
383 target,
384 status: EpistemicStatus::Stated,
385 source: None,
386 annotation: None,
387 })?;
388 }
389 None => non_commit_refs += 1,
391 }
392 }
393 ScannedKind::Dropped(ns) => {
394 *dropped_namespace_counts.entry(ns).or_insert(0) += 1;
395 }
396 }
397 }
398
399 time_counts.unparseable_times += tagger_time_counts.unparseable_times;
400 time_counts.unparseable_offsets += tagger_time_counts.unparseable_offsets;
401
402 builder.set_loss(loss_boundary(
403 &dropped_namespace_counts,
404 dropped_only_commits,
405 non_commit_refs,
406 symbolic_ref_count,
407 time_counts,
408 nested_tag_objects,
409 ));
410 builder.finish().map_err(Error::Ir)
411}
412
413enum DroppedOnlyCommits {
415 Counted(u64),
417 Unavailable,
424}
425
426fn count_dropped_only_commits(
433 repo: &gix::Repository,
434 dropped_tips: Vec<ObjectId>,
435 carried_tips: Vec<ObjectId>,
436) -> DroppedOnlyCommits {
437 if dropped_tips.is_empty() {
438 return DroppedOnlyCommits::Counted(0);
439 }
440 let Ok(walk) = repo
441 .rev_walk(dropped_tips)
442 .with_hidden(carried_tips)
443 .use_commit_graph(false)
444 .all()
445 else {
446 return DroppedOnlyCommits::Unavailable;
447 };
448 let mut count = 0u64;
449 for info in walk {
450 if info.is_err() {
451 return DroppedOnlyCommits::Unavailable;
452 }
453 count += 1;
454 }
455 DroppedOnlyCommits::Counted(count)
456}
457
458struct ScannedRef {
460 kind: ScannedKind,
461 commit: Option<ObjectId>,
463 tag_identity: Option<TagIdentity>,
466}
467
468enum ScannedKind {
469 Branch(String),
470 Tag(String),
471 Extra(String),
474 Dropped(&'static str),
475}
476
477const HEADS_PREFIX: &[u8] = b"refs/heads/";
478const TAGS_PREFIX: &[u8] = b"refs/tags/";
479
480fn scan_refs(
485 repo: &gix::Repository,
486 limits: &Limits,
487 opts: &Options,
488) -> Result<(Vec<ScannedRef>, u64, u64, ParseCounts), Error> {
489 let mut out = Vec::new();
490 let mut symbolic_refs = 0u64;
491 let mut nested_tag_objects = 0u64;
492 let mut tagger_time_counts = ParseCounts::default();
493 let platform = repo.references().map_err(read_err)?;
494 for r in platform.all().map_err(read_err)? {
495 let mut r = r.map_err(read_err)?;
496 let raw_name: Vec<u8> = r.name().as_bstr().to_vec();
497 let name = raw_name.to_str_lossy(); if raw_name.starts_with(b"refs/replace/") {
501 return Err(Error::FloorRefusal {
502 feature: floor::REPLACE_REF.to_string(),
503 reason: format!(
504 "{} rewrites the object graph a reader would see; refused rather than \
505 importing the rewritten view silently",
506 escape_invalid_utf8(&raw_name)
507 ),
508 });
509 }
510
511 let Some(direct) = r.try_id().map(|id| id.detach()) else {
519 symbolic_refs += 1;
520 continue;
521 };
522
523 #[derive(Clone, Copy)]
527 enum Carried {
528 Branch,
529 Tag,
530 Extra,
531 }
532 let carried_suffix: Option<(&[u8], Carried)> = if raw_name.starts_with(HEADS_PREFIX) {
533 Some((
534 raw_name.get(HEADS_PREFIX.len()..).unwrap_or(&[]),
535 Carried::Branch,
536 ))
537 } else if raw_name.starts_with(TAGS_PREFIX) {
538 Some((
539 raw_name.get(TAGS_PREFIX.len()..).unwrap_or(&[]),
540 Carried::Tag,
541 ))
542 } else if let Some(prefix) = opts
543 .carry_extra_namespaces
544 .iter()
545 .find(|p| raw_name.starts_with(p.as_bytes()))
546 {
547 Some((raw_name.get(prefix.len()..).unwrap_or(&[]), Carried::Extra))
548 } else {
549 None
550 };
551 if let Some((suffix, _)) = carried_suffix {
552 if std::str::from_utf8(suffix).is_err() {
553 return Err(Error::FloorRefusal {
554 feature: floor::NON_UTF8_REF_NAME.to_string(),
555 reason: format!(
556 "ref name '{}' is not valid UTF-8 (invalid bytes shown as \\xNN)",
557 escape_invalid_utf8(&raw_name)
558 ),
559 });
560 }
561 }
562
563 let mut tag_identity = None;
564 let (kind, commit) = if let Some((suffix, carried)) = carried_suffix {
565 let suffix_str = std::str::from_utf8(suffix).unwrap_or_default().to_string();
567 match carried {
568 Carried::Branch | Carried::Extra => {
569 let (commit, nested) = peel_carried(repo, direct, limits, false)?;
573 nested_tag_objects += nested;
574 let kind = if matches!(carried, Carried::Branch) {
575 ScannedKind::Branch(suffix_str)
576 } else {
577 ScannedKind::Extra(suffix_str)
578 };
579 (kind, commit)
580 }
581 Carried::Tag => {
582 let (identity, counts) = annotated_tag_identity(repo, direct)?;
583 tag_identity = identity;
584 tagger_time_counts.unparseable_times += counts.unparseable_times;
585 tagger_time_counts.unparseable_offsets += counts.unparseable_offsets;
586 let (commit, nested) = peel_carried(repo, direct, limits, true)?;
587 nested_tag_objects += nested;
588 (ScannedKind::Tag(suffix_str), commit)
589 }
590 }
591 } else {
592 let dropped_kind = if name.starts_with("refs/remotes/") {
595 ScannedKind::Dropped("remote-tracking")
596 } else if name.starts_with("refs/notes/") {
597 ScannedKind::Dropped("notes")
598 } else if name == "refs/stash" {
599 ScannedKind::Dropped("stash")
600 } else {
601 ScannedKind::Dropped("other")
603 };
604 let lenient_commit = r.peel_to_id().ok().map(|id| id.detach()).filter(|id| {
605 repo.find_object(*id)
606 .is_ok_and(|o| matches!(o.kind, gix::objs::Kind::Commit))
607 });
608 (dropped_kind, lenient_commit)
609 };
610 out.push(ScannedRef {
611 kind,
612 commit,
613 tag_identity,
614 });
615 }
616 Ok((out, symbolic_refs, nested_tag_objects, tagger_time_counts))
617}
618
619fn peel_carried(
629 repo: &gix::Repository,
630 direct: ObjectId,
631 limits: &Limits,
632 direct_tag_is_carried: bool,
633) -> Result<(Option<ObjectId>, u64), Error> {
634 let mut current = direct;
635 let mut hops = 0usize;
636 let mut nested_tags = 0u64;
637 loop {
638 let object = find_verified_object(repo, current)?;
639 match object.kind {
640 gix::objs::Kind::Commit => return Ok((Some(current), nested_tags)),
641 gix::objs::Kind::Tag => {
642 hops += 1;
643 if hops > limits.max_tag_chain {
644 return Err(resource_limit(
645 "the tag chain",
646 format!("{} tag(s)", limits.max_tag_chain),
647 ));
648 }
649 if hops > 1 || !direct_tag_is_carried {
650 nested_tags += 1;
651 }
652 let tag = object.try_into_tag().map_err(read_err)?;
653 let decoded = tag.decode().map_err(read_err)?;
654 current = decoded.target();
655 }
656 _ => return Ok((None, nested_tags)),
657 }
658 }
659}
660
661fn annotated_tag_identity(
669 repo: &gix::Repository,
670 direct: ObjectId,
671) -> Result<(Option<TagIdentity>, ParseCounts), Error> {
672 let object = find_verified_object(repo, direct)?;
673 if !matches!(object.kind, gix::objs::Kind::Tag) {
674 return Ok((None, ParseCounts::default()));
675 }
676 let tag = object.try_into_tag().map_err(read_err)?;
677 let decoded = tag.decode().map_err(read_err)?;
678 let signatures = decoded
679 .signature
680 .map(|s| Signature {
681 label: "gpgsig".to_string(),
682 bytes: s.to_vec(),
683 })
684 .into_iter()
685 .collect();
686 let mut counts = ParseCounts::default();
687 let tagger_sig = decoded.tagger().map_err(read_err)?;
688 let tagger = tagger_sig.map(|sig| Identity {
689 name: Text {
690 bytes: sig.name.to_vec(),
691 encoding: None,
692 },
693 email: Some(Text {
694 bytes: sig.email.to_vec(),
695 encoding: None,
696 }),
697 });
698 let time = tagger_sig.and_then(|sig| {
699 let seconds = strict_seconds(sig.time);
700 if seconds.is_none() {
701 counts.unparseable_times += 1;
702 }
703 seconds.map(|seconds| {
704 let offset_minutes = strict_offset_minutes(sig.time);
705 if offset_minutes.is_none() {
706 counts.unparseable_offsets += 1;
707 }
708 Time {
709 seconds,
710 offset_minutes,
711 }
712 })
713 });
714 let message = Text {
715 bytes: decoded.message.to_vec(),
716 encoding: None,
717 };
718 let annotation = Annotation {
719 tagger,
720 time,
721 message: Some(message),
722 };
723 Ok((Some((direct, signatures, Some(annotation))), counts))
724}
725
726fn commit_parents(
734 repo: &gix::Repository,
735 set: &BTreeSet<ObjectId>,
736) -> Result<BTreeMap<ObjectId, Vec<ObjectId>>, Error> {
737 let mut parents = BTreeMap::new();
738 for id in set {
739 let commit = find_verified_object(repo, *id)?
740 .try_into_commit()
741 .map_err(read_err)?;
742 let mut ps = Vec::new();
743 for p in commit.parent_ids() {
744 let p = p.detach();
745 if !set.contains(&p) {
746 return Err(Error::Read(
747 "history walk disagrees with commit content".to_string(),
748 ));
749 }
750 ps.push(p);
751 }
752 parents.insert(*id, ps);
753 }
754 Ok(parents)
755}
756
757fn parent_first_order(
759 set: &BTreeSet<ObjectId>,
760 parents: &BTreeMap<ObjectId, Vec<ObjectId>>,
761) -> Result<Vec<ObjectId>, Error> {
762 let mut indeg: BTreeMap<ObjectId, usize> = set.iter().map(|id| (*id, 0usize)).collect();
763 let mut children: BTreeMap<ObjectId, Vec<ObjectId>> = BTreeMap::new();
764 for (id, ps) in parents {
765 for p in ps {
766 children.entry(*p).or_default().push(*id);
767 if let Some(d) = indeg.get_mut(id) {
768 *d += 1;
769 }
770 }
771 }
772 let mut ready: BTreeSet<ObjectId> = indeg
773 .iter()
774 .filter_map(|(id, d)| (*d == 0).then_some(*id))
775 .collect();
776 let mut order = Vec::with_capacity(set.len());
777 while let Some(id) = ready.iter().next().copied() {
778 ready.remove(&id);
779 order.push(id);
780 if let Some(kids) = children.get(&id) {
781 for kid in kids {
782 if let Some(d) = indeg.get_mut(kid) {
783 *d = d.saturating_sub(1);
784 if *d == 0 {
785 ready.insert(*kid);
786 }
787 }
788 }
789 }
790 }
791 if order.len() != set.len() {
792 return Err(Error::Read(
793 "commit graph contains a cycle (a Git history must be acyclic)".to_string(),
794 ));
795 }
796 Ok(order)
797}
798
799struct SnapshotCache {
812 snaps: HashMap<ObjectId, Snapshot>,
813 remaining: HashMap<ObjectId, usize>,
816}
817
818impl SnapshotCache {
819 fn new(uses: HashMap<ObjectId, usize>) -> Self {
820 Self {
821 snaps: HashMap::new(),
822 remaining: uses,
823 }
824 }
825
826 fn get_or_build(
828 &mut self,
829 tree_id: ObjectId,
830 build: impl FnOnce() -> Result<Snapshot, Error>,
831 ) -> Result<Snapshot, Error> {
832 if let Some(s) = self.snaps.get(&tree_id) {
833 return Ok(s.clone());
834 }
835 let out = build()?;
836 self.snaps.insert(tree_id, out.clone());
837 Ok(out)
838 }
839
840 fn release(&mut self, tree_id: ObjectId) {
842 if let Some(n) = self.remaining.get_mut(&tree_id) {
843 *n = n.saturating_sub(1);
844 if *n == 0 {
845 self.remaining.remove(&tree_id);
846 self.snaps.remove(&tree_id);
847 }
848 }
849 }
850
851 #[cfg(test)]
853 fn len(&self) -> usize {
854 self.snaps.len()
855 }
856}
857
858fn count_snapshot_uses(
863 repo: &gix::Repository,
864 order: &[ObjectId],
865 parents: &BTreeMap<ObjectId, Vec<ObjectId>>,
866) -> HashMap<ObjectId, usize> {
867 let mut tree_of: HashMap<ObjectId, ObjectId> = HashMap::with_capacity(order.len());
868 let mut uses: HashMap<ObjectId, usize> = HashMap::new();
869 for id in order {
870 let Some(tree) = find_verified_object(repo, *id)
871 .ok()
872 .and_then(|o| o.try_into_commit().ok())
873 .and_then(|c| c.tree_id().ok())
874 .map(gix::Id::detach)
875 else {
876 continue;
877 };
878 tree_of.insert(*id, tree);
879 *uses.entry(tree).or_insert(0) += 1;
880 if let Some(p0) = parents.get(id).and_then(|ps| ps.first()) {
881 if let Some(pt) = tree_of.get(p0) {
882 *uses.entry(*pt).or_insert(0) += 1;
883 }
884 }
885 }
886 uses
887}
888
889const GITLINK_MODE: u32 = 0o160_000;
895
896fn snapshot(
899 repo: &gix::Repository,
900 tree_id: ObjectId,
901 commit_id: ObjectId,
902 limits: &Limits,
903 cache: &mut SnapshotCache,
904) -> Result<Snapshot, Error> {
905 cache.get_or_build(tree_id, || {
906 let mut out = Snapshot::new();
907 walk_tree(repo, tree_id, commit_id, limits, &mut out)?;
908 Ok(out)
909 })
910}
911
912fn walk_tree(
918 repo: &gix::Repository,
919 root_tree_id: ObjectId,
920 commit_id: ObjectId,
921 limits: &Limits,
922 out: &mut Snapshot,
923) -> Result<(), Error> {
924 let mut stack: Vec<(ObjectId, String, usize)> = vec![(root_tree_id, String::new(), 1)];
926 let mut visited: usize = 0;
930 while let Some((tree_id, prefix, depth)) = stack.pop() {
931 let tree = find_verified_object(repo, tree_id)?
932 .try_into_tree()
933 .map_err(read_err)?;
934 for entry in tree.iter() {
935 visited = visited.saturating_add(1);
936 if visited > limits.max_tree_entries {
937 return Err(resource_limit(
938 "one tree in this repository",
939 format!("{} entries", limits.max_tree_entries),
940 ));
941 }
942 let entry = entry.map_err(read_err)?;
943 let raw_name = entry.filename(); let Ok(name) = std::str::from_utf8(raw_name) else {
945 return Err(Error::FloorRefusal {
946 feature: floor::NON_UTF8_PATH.to_string(),
947 reason: format!(
948 "commit {commit_id}: path '{prefix}{}{}' is not valid UTF-8 (invalid bytes \
949 shown as \\xNN)",
950 if prefix.is_empty() { "" } else { "/" },
951 escape_invalid_utf8(raw_name)
952 ),
953 });
954 };
955 let path = if prefix.is_empty() {
956 name.to_string()
957 } else {
958 format!("{prefix}/{name}")
959 };
960 if path.len() > limits.max_path_bytes {
961 return Err(resource_limit(
962 "a path",
963 format!("{} bytes", limits.max_path_bytes),
964 ));
965 }
966 let mode = entry.mode();
967 let oid = entry.oid().to_owned();
968 match mode.kind() {
969 gix::objs::tree::EntryKind::Tree => {
970 let child_depth = depth + 1;
971 if child_depth > limits.max_tree_depth {
972 return Err(resource_limit(
973 "the tree nesting",
974 format!("{} levels", limits.max_tree_depth),
975 ));
976 }
977 stack.push((oid, path, child_depth));
978 }
979 _ => {
985 if out.contains_key(&path) {
989 return Err(Error::Read(format!(
990 "commit {commit_id}: duplicate path '{path}' in tree snapshot"
991 )));
992 }
993 out.insert(path, (oid, u32::from(mode.value())));
994 }
995 }
996 }
997 }
998 Ok(())
999}
1000
1001fn diff_to_ops(
1006 repo: &gix::Repository,
1007 base: &Snapshot,
1008 child: &Snapshot,
1009 opts: &Options,
1010 limits: &Limits,
1011 builder: &mut IrBuilder,
1012 from_parent: Option<AtomId>,
1013) -> Result<(Vec<PathOp>, Vec<CopyRecord>), Error> {
1014 let mut ops = Vec::new();
1015 let mut added_by_oid: BTreeMap<ObjectId, Vec<String>> = BTreeMap::new();
1016 let mut deleted_by_oid: BTreeMap<ObjectId, Vec<String>> = BTreeMap::new();
1017
1018 for (path, (oid, mode)) in child {
1019 let child_is_submodule = *mode == GITLINK_MODE;
1020 match base.get(path) {
1021 None => {
1022 let content = content_for(repo, *oid, *mode, limits, builder)?;
1023 ops.push(PathOp::Add {
1024 path: path.clone(),
1025 content,
1026 status: EpistemicStatus::Stated,
1027 });
1028 if !child_is_submodule {
1032 added_by_oid.entry(*oid).or_default().push(path.clone());
1033 }
1034 }
1035 Some((base_oid, base_mode)) => {
1036 let base_is_submodule = *base_mode == GITLINK_MODE;
1037 if base_is_submodule != child_is_submodule {
1038 let content = content_for(repo, *oid, *mode, limits, builder)?;
1041 ops.push(PathOp::Replace {
1042 path: path.clone(),
1043 content,
1044 status: EpistemicStatus::Stated,
1045 });
1046 } else if base_oid != oid || base_mode != mode {
1047 let content = content_for(repo, *oid, *mode, limits, builder)?;
1048 ops.push(PathOp::Modify {
1049 path: path.clone(),
1050 content,
1051 status: EpistemicStatus::Stated,
1052 });
1053 }
1054 }
1055 }
1056 }
1057 for (path, (oid, mode)) in base {
1058 if !child.contains_key(path) {
1059 ops.push(PathOp::Delete {
1060 path: path.clone(),
1061 status: EpistemicStatus::Stated,
1062 });
1063 if *mode != GITLINK_MODE {
1064 deleted_by_oid.entry(*oid).or_default().push(path.clone());
1065 }
1066 }
1067 }
1068
1069 let mut copies = Vec::new();
1070 if opts.infer_renames {
1071 if let Some(from_atom) = from_parent {
1080 for (oid, froms) in &deleted_by_oid {
1081 let [from] = froms.as_slice() else {
1082 continue; };
1084 let Some([to]) = added_by_oid.get(oid).map(Vec::as_slice) else {
1085 continue; };
1087 copies.push(CopyRecord {
1088 from: from.clone(),
1089 from_atom,
1090 to: to.clone(),
1091 status: EpistemicStatus::Derived(Derivation {
1092 kind: DerivationKind::InferredRename,
1093 by: DECODER.to_string(),
1094 decoder_version: decoder_version().to_string(),
1095 params: opts.as_params(),
1096 confidence: Some(100),
1097 }),
1098 });
1099 }
1100 }
1101 }
1102 Ok((ops, copies))
1103}
1104
1105fn content_for(
1111 repo: &gix::Repository,
1112 oid: ObjectId,
1113 mode: u32,
1114 limits: &Limits,
1115 builder: &mut IrBuilder,
1116) -> Result<Content, Error> {
1117 if mode == GITLINK_MODE {
1118 Ok(Content::submodule(oid.as_bytes().to_vec()))
1119 } else {
1120 let blob = builder.add_blob(blob_bytes(repo, oid, limits)?)?;
1121 Ok(Content::blob(blob, mode))
1122 }
1123}
1124
1125fn blob_bytes(repo: &gix::Repository, oid: ObjectId, limits: &Limits) -> Result<Vec<u8>, Error> {
1129 let header = repo.find_header(oid).map_err(read_err)?;
1130 if header.size() > limits.max_blob_bytes {
1131 return Err(resource_limit(
1132 "a blob",
1133 format!("{} bytes", limits.max_blob_bytes),
1134 ));
1135 }
1136 Ok(find_verified_object(repo, oid)?
1137 .try_into_blob()
1138 .map_err(read_err)?
1139 .data
1140 .clone())
1141}
1142
1143fn strict_seconds(raw: &str) -> Option<i64> {
1150 let token = raw.split_whitespace().next()?;
1151 let digits = token.strip_prefix('-').unwrap_or(token);
1152 if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
1153 return None;
1154 }
1155 token.parse::<i64>().ok()
1156}
1157
1158fn strict_offset_minutes(raw: &str) -> Option<i16> {
1164 let mut tokens = raw.split_whitespace();
1165 let _seconds = tokens.next()?;
1166 let tz = tokens.next()?;
1167 let sign = match tz.as_bytes().first()? {
1168 b'+' => 1i32,
1169 b'-' => -1i32,
1170 _ => return None,
1171 };
1172 let digits = tz.get(1..)?;
1173 if digits.len() != 4 || !digits.bytes().all(|b| b.is_ascii_digit()) {
1174 return None;
1175 }
1176 let hh: i32 = digits.get(..2)?.parse().ok()?;
1177 let mm: i32 = digits.get(2..)?.parse().ok()?;
1178 if mm >= 60 {
1179 return None;
1180 }
1181 i16::try_from(sign * (hh * 60 + mm)).ok()
1182}
1183
1184fn build_metadata(commit: &gix::Commit<'_>) -> Result<(MetadataClaims, ParseCounts), Error> {
1194 let author = commit.author().map_err(read_err)?;
1195 let committer = commit.committer().map_err(read_err)?;
1196 let decoded = commit.decode().map_err(read_err)?;
1197 let message = decoded.message;
1198
1199 let mut counts = ParseCounts::default();
1200 let message_encoding = match decoded.encoding {
1201 Some(e) => match std::str::from_utf8(e) {
1202 Ok(s) => Some(s.to_string()),
1203 Err(_) => {
1204 counts.undecodable_encodings += 1;
1207 None
1208 }
1209 },
1210 None => None,
1211 };
1212 let author_time = strict_seconds(author.time);
1213 if author_time.is_none() {
1214 counts.unparseable_times += 1;
1215 }
1216 let author_offset = strict_offset_minutes(author.time);
1217 if author_time.is_some() && author_offset.is_none() {
1218 counts.unparseable_offsets += 1;
1219 }
1220 let commit_time = strict_seconds(committer.time);
1221 if commit_time.is_none() {
1222 counts.unparseable_times += 1;
1223 }
1224 let commit_offset = strict_offset_minutes(committer.time);
1225 if commit_time.is_some() && commit_offset.is_none() {
1226 counts.unparseable_offsets += 1;
1227 }
1228 let raw_text = |bytes: &[u8]| Text {
1229 bytes: bytes.to_vec(),
1230 encoding: None,
1231 };
1232 Ok((
1233 MetadataClaims {
1234 author: Some(Identity {
1235 name: raw_text(author.name.as_ref()),
1236 email: Some(raw_text(author.email.as_ref())),
1237 }),
1238 author_time: author_time.map(|seconds| Time {
1239 seconds,
1240 offset_minutes: author_offset,
1241 }),
1242 committer: Some(Identity {
1243 name: raw_text(committer.name.as_ref()),
1244 email: Some(raw_text(committer.email.as_ref())),
1245 }),
1246 commit_time: commit_time.map(|seconds| Time {
1247 seconds,
1248 offset_minutes: commit_offset,
1249 }),
1250 message: Some(Text {
1251 bytes: message.to_vec(),
1252 encoding: message_encoding,
1253 }),
1254 },
1255 counts,
1256 ))
1257}
1258
1259#[derive(Debug, Clone, Copy, Default)]
1263struct ParseCounts {
1264 unparseable_times: u64,
1265 unparseable_offsets: u64,
1266 undecodable_encodings: u64,
1267}
1268
1269fn signatures_and_extras(
1278 commit: &gix::Commit<'_>,
1279 id: ObjectId,
1280) -> Result<(Vec<Signature>, Vec<Extra>), Error> {
1281 let decoded = commit.decode().map_err(read_err)?;
1282 let mut signatures = Vec::new();
1283 let mut extras = Vec::new();
1284 for (name, value) in &decoded.extra_headers {
1285 let Ok(label) = std::str::from_utf8(name) else {
1286 return Err(Error::FloorRefusal {
1287 feature: floor::NON_UTF8_COMMIT_HEADER_NAME.to_string(),
1288 reason: format!(
1289 "commit {id}: header name '{}' is not valid UTF-8 (invalid bytes shown as \\xNN)",
1290 escape_invalid_utf8(name)
1291 ),
1292 });
1293 };
1294 match label {
1295 "gpgsig" | "gpgsig-sha256" => signatures.push(Signature {
1296 label: label.to_string(),
1297 bytes: value.to_vec(),
1298 }),
1299 _ => extras.push(Extra {
1300 label: label.to_string(),
1301 bytes: value.to_vec(),
1302 }),
1303 }
1304 }
1305 Ok((signatures, extras))
1306}
1307
1308fn loss_boundary(
1316 dropped_namespace_counts: &BTreeMap<&'static str, u64>,
1317 dropped_only_commits: DroppedOnlyCommits,
1318 non_commit_refs: u64,
1319 symbolic_refs: u64,
1320 time_counts: ParseCounts,
1321 nested_tag_objects: u64,
1322) -> LossBoundary {
1323 let mut dropped = vec![
1324 DropRecord {
1325 class: LossClass::Representation,
1326 what: "packfile and delta layout, physical object store".to_string(),
1327 reason: "representation not assertion; reconstructible from the objects".to_string(),
1328 step: None,
1329 },
1330 DropRecord {
1331 class: LossClass::Representation,
1332 what: "index and working tree".to_string(),
1333 reason: "local state, not history".to_string(),
1334 step: None,
1335 },
1336 DropRecord {
1337 class: LossClass::Representation,
1338 what: "reflogs".to_string(),
1339 reason: "local operation log, not history".to_string(),
1340 step: None,
1341 },
1342 ];
1343 for (ns, count) in dropped_namespace_counts {
1344 dropped.push(DropRecord {
1345 class: LossClass::Representation,
1346 what: format!("{ns} refs ({count})"),
1347 reason: "workflow/representation refs, not authored history".to_string(),
1348 step: None,
1349 });
1350 }
1351 match dropped_only_commits {
1352 DroppedOnlyCommits::Counted(0) => {}
1353 DroppedOnlyCommits::Counted(n) => {
1354 dropped.push(DropRecord {
1355 class: LossClass::Representation,
1356 what: format!("commits reachable only from dropped refs ({n})"),
1357 reason:
1358 "workflow state (stash, notes, remote-tracking), not authored history of a \
1359 carried ref"
1360 .to_string(),
1361 step: None,
1362 });
1363 }
1364 DroppedOnlyCommits::Unavailable => {
1365 dropped.push(DropRecord {
1366 class: LossClass::Representation,
1367 what: "commits reachable only from dropped refs (count unavailable)".to_string(),
1368 reason: "a commit in dropped-only history could not be read".to_string(),
1369 step: None,
1370 });
1371 }
1372 }
1373 if non_commit_refs > 0 {
1374 dropped.push(DropRecord {
1375 class: LossClass::Other,
1376 what: format!("refs to non-commit objects ({non_commit_refs})"),
1377 reason: "a tag or branch naming a tree or blob; the IR's refs point at history atoms"
1378 .to_string(),
1379 step: None,
1380 });
1381 }
1382 if symbolic_refs > 0 {
1383 dropped.push(DropRecord {
1384 class: LossClass::Representation,
1385 what: format!("symbolic refs ({symbolic_refs})"),
1386 reason:
1387 "an alias to another ref; the IR has no alias concept; the target ref is carried \
1388 on its own"
1389 .to_string(),
1390 step: None,
1391 });
1392 }
1393 if time_counts.unparseable_times > 0 {
1394 dropped.push(DropRecord {
1395 class: LossClass::Other,
1396 what: format!(
1397 "unparseable author/committer/tagger times ({})",
1398 time_counts.unparseable_times
1399 ),
1400 reason: "the source's time field could not be parsed; the claim is absent rather than \
1401 fabricated"
1402 .to_string(),
1403 step: None,
1404 });
1405 }
1406 if time_counts.unparseable_offsets > 0 {
1407 dropped.push(DropRecord {
1408 class: LossClass::Other,
1409 what: format!(
1410 "unparseable author/committer/tagger timezone offsets ({})",
1411 time_counts.unparseable_offsets
1412 ),
1413 reason: "the source's timezone offset could not be parsed strictly (`+HHMM`/`-HHMM`); \
1414 the time is carried without an offset rather than a fabricated or salvaged one"
1415 .to_string(),
1416 step: None,
1417 });
1418 }
1419 if time_counts.undecodable_encodings > 0 {
1420 dropped.push(DropRecord {
1421 class: LossClass::Other,
1422 what: format!(
1423 "undecodable encoding headers ({})",
1424 time_counts.undecodable_encodings
1425 ),
1426 reason:
1427 "the commit's declared `encoding` header value was not valid UTF-8, so it is not \
1428 carried on the message's `Text.encoding`"
1429 .to_string(),
1430 step: None,
1431 });
1432 }
1433 if nested_tag_objects > 0 {
1434 dropped.push(DropRecord {
1435 class: LossClass::Other,
1436 what: format!("nested tag objects not carried ({nested_tag_objects})"),
1437 reason: "an intermediate tag object in a tag-of-a-tag chain; only the outer tag's \
1438 annotation is carried"
1439 .to_string(),
1440 step: None,
1441 });
1442 }
1443 LossBoundary { dropped }
1444}
1445
1446#[cfg(test)]
1447mod tests;