use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::path::Path;
use gix::ObjectId;
use gix::bstr::ByteSlice;
use brygge_ir::Storage;
use brygge_ir::builder::{AtomDraft, IrBuilder};
use brygge_ir::model::{
Annotation, AtomId, Content, CopyRecord, DropRecord, Extra, Identity, ImportProvenance, Ir,
LossBoundary, LossClass, MetadataClaims, PathOp, RefKind, RefRecord, Signature, SourceIdentity,
SourceKind, Text, Time,
};
use brygge_ir::status::{Derivation, DerivationKind, EpistemicStatus};
use crate::{Error, Options, decoder_version, floor, open};
type Snapshot = BTreeMap<String, (ObjectId, u32)>;
type TagIdentity = (ObjectId, Vec<Signature>, Option<Annotation>);
const DECODER: &str = "brygge-decode-git";
#[derive(Debug, Clone, Copy)]
pub(crate) struct Limits {
pub(crate) max_blob_bytes: u64,
pub(crate) max_commits: u64,
pub(crate) max_path_bytes: usize,
pub(crate) max_tree_depth: usize,
pub(crate) max_tag_chain: usize,
pub(crate) max_tree_entries: usize,
}
impl Default for Limits {
fn default() -> Self {
Self {
max_blob_bytes: 1024 * 1024 * 1024,
max_commits: 10_000_000,
max_path_bytes: 4096,
max_tree_depth: 256,
max_tag_chain: 32,
max_tree_entries: 10_000_000,
}
}
}
fn resource_limit(what: &str, ceiling: impl std::fmt::Display) -> Error {
Error::ResourceLimit {
what: what.to_string(),
ceiling: ceiling.to_string(),
}
}
fn read_err(e: impl std::fmt::Display) -> Error {
Error::Read(e.to_string())
}
fn find_verified_object(repo: &gix::Repository, id: ObjectId) -> Result<gix::Object<'_>, Error> {
let object = repo.find_object(id).map_err(read_err)?;
let computed =
gix::objs::compute_hash(repo.object_hash(), object.kind, &object.data).map_err(read_err)?;
if computed != id {
return Err(Error::Read(format!(
"object {id} does not match its content (corrupt or crafted repository)"
)));
}
Ok(object)
}
fn escape_invalid_utf8(bytes: &[u8]) -> String {
use std::fmt::Write as _;
let mut out = String::with_capacity(bytes.len());
let mut rest = bytes;
loop {
match std::str::from_utf8(rest) {
Ok(valid) => {
out.push_str(valid);
break;
}
Err(e) => {
let valid_up_to = e.valid_up_to();
let valid_prefix = rest.get(..valid_up_to).unwrap_or(&[]);
out.push_str(std::str::from_utf8(valid_prefix).unwrap_or_default());
let bad_len = e.error_len().unwrap_or(rest.len() - valid_up_to).max(1);
let bad_end = (valid_up_to + bad_len).min(rest.len());
for &b in rest.get(valid_up_to..bad_end).unwrap_or(&[]) {
let _ = write!(out, "\\x{b:02X}");
}
rest = rest.get(bad_end..).unwrap_or(&[]);
if rest.is_empty() {
break;
}
}
}
}
out
}
pub fn decode(path: &Path, opts: &Options) -> Result<Ir, Error> {
decode_with_storage(path, opts, &Storage::Memory)
}
pub fn decode_with_storage(path: &Path, opts: &Options, storage: &Storage) -> Result<Ir, Error> {
decode_with(path, opts, &Limits::default(), storage)
}
pub(crate) fn decode_with(
path: &Path,
opts: &Options,
limits: &Limits,
storage: &Storage,
) -> Result<Ir, Error> {
for prefix in &opts.carry_extra_namespaces {
if !prefix.ends_with('/') {
return Err(Error::InvalidOptions(format!(
"carry_extra_namespaces: '{prefix}' does not end with '/', so it would match no ref"
)));
}
}
let repo = open::open(path)?;
open::check_repo_floor(&repo)?;
let (refs, symbolic_ref_count, nested_tag_objects, tagger_time_counts) =
scan_refs(&repo, limits, opts)?;
let carried_tips: Vec<ObjectId> = refs
.iter()
.filter(|r| {
matches!(
r.kind,
ScannedKind::Branch(_) | ScannedKind::Tag(_) | ScannedKind::Extra(_)
)
})
.filter_map(|r| r.commit)
.collect();
let mut set: BTreeSet<ObjectId> = BTreeSet::new();
if !carried_tips.is_empty() {
for info in repo
.rev_walk(carried_tips.clone())
.use_commit_graph(false)
.all()
.map_err(read_err)?
{
set.insert(info.map_err(read_err)?.id);
if set.len() as u64 > limits.max_commits {
return Err(resource_limit(
"the commit count",
format!("{} commits", limits.max_commits),
));
}
}
}
let dropped_tips: Vec<ObjectId> = refs
.iter()
.filter(|r| matches!(r.kind, ScannedKind::Dropped(_)))
.filter_map(|r| r.commit)
.collect();
let dropped_only_commits = count_dropped_only_commits(&repo, dropped_tips, carried_tips);
let parents = commit_parents(&repo, &set)?;
let order = parent_first_order(&set, &parents)?;
let repo_id = order
.iter()
.filter(|id| parents.get(*id).is_none_or(Vec::is_empty))
.min()
.map(|id| id.as_bytes().to_vec())
.unwrap_or_default();
let provenance = ImportProvenance {
source: SourceIdentity {
kind: SourceKind::Git,
repo_id: repo_id.clone(),
atom_id: repo_id.clone(),
signatures: Vec::new(),
extras: Vec::new(),
},
brygge_version: decoder_version().to_string(),
decoder: DECODER.to_string(),
decoder_version: decoder_version().to_string(),
params: {
let mut params = opts.as_params();
params.insert("floor".to_string(), floor::joined());
params
},
};
let mut builder = IrBuilder::with_storage(provenance, storage).map_err(Error::Ir)?;
let mut sha_to_atom: HashMap<ObjectId, AtomId> = HashMap::new();
let mut snap_cache = SnapshotCache::new(count_snapshot_uses(&repo, &order, &parents));
let mut time_counts = ParseCounts::default();
for id in &order {
let commit = find_verified_object(&repo, *id)?
.try_into_commit()
.map_err(read_err)?;
let child_tree = commit.tree_id().map_err(read_err)?.detach();
let child_snap = snapshot(&repo, child_tree, *id, limits, &mut snap_cache)?;
let ps = parents.get(id).cloned().unwrap_or_default();
let mut base_tree: Option<ObjectId> = None;
let base_snap = match ps.first() {
Some(p0) => {
let p_commit = find_verified_object(&repo, *p0)?
.try_into_commit()
.map_err(read_err)?;
let p_tree = p_commit.tree_id().map_err(read_err)?.detach();
base_tree = Some(p_tree);
snapshot(&repo, p_tree, *p0, limits, &mut snap_cache)?
}
None => Snapshot::new(),
};
let parent_atoms: Vec<AtomId> = ps
.iter()
.filter_map(|p| sha_to_atom.get(p).copied())
.collect();
let (ops, copies) = diff_to_ops(
&repo,
&base_snap,
&child_snap,
opts,
limits,
&mut builder,
parent_atoms.first().copied(),
)?;
snap_cache.release(child_tree);
if let Some(t) = base_tree {
snap_cache.release(t);
}
let (metadata, counts) = build_metadata(&commit)?;
time_counts.unparseable_times += counts.unparseable_times;
time_counts.unparseable_offsets += counts.unparseable_offsets;
time_counts.undecodable_encodings += counts.undecodable_encodings;
let (signatures, extras) = signatures_and_extras(&commit, *id)?;
let atom_id = builder.add_atom(AtomDraft {
parents: parent_atoms,
ops,
copies,
metadata,
source: SourceIdentity {
kind: SourceKind::Git,
repo_id: repo_id.clone(),
atom_id: id.as_bytes().to_vec(),
signatures,
extras,
},
status: EpistemicStatus::Stated,
})?;
sha_to_atom.insert(*id, atom_id);
}
let mut dropped_namespace_counts: BTreeMap<&'static str, u64> = BTreeMap::new();
let mut non_commit_refs = 0u64;
for r in &refs {
match &r.kind {
ScannedKind::Branch(name) => {
match r.commit.and_then(|c| sha_to_atom.get(&c).copied()) {
Some(target) => {
builder.add_ref(RefRecord {
name: name.clone(),
kind: RefKind::Branch,
target,
status: EpistemicStatus::Stated,
source: None,
annotation: None,
})?;
}
None => non_commit_refs += 1,
}
}
ScannedKind::Tag(name) => match r.commit.and_then(|c| sha_to_atom.get(&c).copied()) {
Some(target) => {
let (source, annotation) = match &r.tag_identity {
Some((tag_id, signatures, annotation)) => (
Some(SourceIdentity {
kind: SourceKind::Git,
repo_id: repo_id.clone(),
atom_id: tag_id.as_bytes().to_vec(),
signatures: signatures.clone(),
extras: Vec::new(),
}),
annotation.clone(),
),
None => (None, None),
};
builder.add_ref(RefRecord {
name: name.clone(),
kind: RefKind::Tag,
target,
status: EpistemicStatus::Stated,
source,
annotation,
})?;
}
None => non_commit_refs += 1,
},
ScannedKind::Extra(name) => {
match r.commit.and_then(|c| sha_to_atom.get(&c).copied()) {
Some(target) => {
builder.add_ref(RefRecord {
name: name.clone(),
kind: RefKind::Other("carry-extra-namespaces".to_string()),
target,
status: EpistemicStatus::Stated,
source: None,
annotation: None,
})?;
}
None => non_commit_refs += 1,
}
}
ScannedKind::Dropped(ns) => {
*dropped_namespace_counts.entry(ns).or_insert(0) += 1;
}
}
}
time_counts.unparseable_times += tagger_time_counts.unparseable_times;
time_counts.unparseable_offsets += tagger_time_counts.unparseable_offsets;
builder.set_loss(loss_boundary(
&dropped_namespace_counts,
dropped_only_commits,
non_commit_refs,
symbolic_ref_count,
time_counts,
nested_tag_objects,
));
builder.finish().map_err(Error::Ir)
}
enum DroppedOnlyCommits {
Counted(u64),
Unavailable,
}
fn count_dropped_only_commits(
repo: &gix::Repository,
dropped_tips: Vec<ObjectId>,
carried_tips: Vec<ObjectId>,
) -> DroppedOnlyCommits {
if dropped_tips.is_empty() {
return DroppedOnlyCommits::Counted(0);
}
let Ok(walk) = repo
.rev_walk(dropped_tips)
.with_hidden(carried_tips)
.use_commit_graph(false)
.all()
else {
return DroppedOnlyCommits::Unavailable;
};
let mut count = 0u64;
for info in walk {
if info.is_err() {
return DroppedOnlyCommits::Unavailable;
}
count += 1;
}
DroppedOnlyCommits::Counted(count)
}
struct ScannedRef {
kind: ScannedKind,
commit: Option<ObjectId>,
tag_identity: Option<TagIdentity>,
}
enum ScannedKind {
Branch(String),
Tag(String),
Extra(String),
Dropped(&'static str),
}
const HEADS_PREFIX: &[u8] = b"refs/heads/";
const TAGS_PREFIX: &[u8] = b"refs/tags/";
fn scan_refs(
repo: &gix::Repository,
limits: &Limits,
opts: &Options,
) -> Result<(Vec<ScannedRef>, u64, u64, ParseCounts), Error> {
let mut out = Vec::new();
let mut symbolic_refs = 0u64;
let mut nested_tag_objects = 0u64;
let mut tagger_time_counts = ParseCounts::default();
let platform = repo.references().map_err(read_err)?;
for r in platform.all().map_err(read_err)? {
let mut r = r.map_err(read_err)?;
let raw_name: Vec<u8> = r.name().as_bstr().to_vec();
let name = raw_name.to_str_lossy();
if raw_name.starts_with(b"refs/replace/") {
return Err(Error::FloorRefusal {
feature: floor::REPLACE_REF.to_string(),
reason: format!(
"{} rewrites the object graph a reader would see; refused rather than \
importing the rewritten view silently",
escape_invalid_utf8(&raw_name)
),
});
}
let Some(direct) = r.try_id().map(|id| id.detach()) else {
symbolic_refs += 1;
continue;
};
#[derive(Clone, Copy)]
enum Carried {
Branch,
Tag,
Extra,
}
let carried_suffix: Option<(&[u8], Carried)> = if raw_name.starts_with(HEADS_PREFIX) {
Some((
raw_name.get(HEADS_PREFIX.len()..).unwrap_or(&[]),
Carried::Branch,
))
} else if raw_name.starts_with(TAGS_PREFIX) {
Some((
raw_name.get(TAGS_PREFIX.len()..).unwrap_or(&[]),
Carried::Tag,
))
} else if let Some(prefix) = opts
.carry_extra_namespaces
.iter()
.find(|p| raw_name.starts_with(p.as_bytes()))
{
Some((raw_name.get(prefix.len()..).unwrap_or(&[]), Carried::Extra))
} else {
None
};
if let Some((suffix, _)) = carried_suffix {
if std::str::from_utf8(suffix).is_err() {
return Err(Error::FloorRefusal {
feature: floor::NON_UTF8_REF_NAME.to_string(),
reason: format!(
"ref name '{}' is not valid UTF-8 (invalid bytes shown as \\xNN)",
escape_invalid_utf8(&raw_name)
),
});
}
}
let mut tag_identity = None;
let (kind, commit) = if let Some((suffix, carried)) = carried_suffix {
let suffix_str = std::str::from_utf8(suffix).unwrap_or_default().to_string();
match carried {
Carried::Branch | Carried::Extra => {
let (commit, nested) = peel_carried(repo, direct, limits, false)?;
nested_tag_objects += nested;
let kind = if matches!(carried, Carried::Branch) {
ScannedKind::Branch(suffix_str)
} else {
ScannedKind::Extra(suffix_str)
};
(kind, commit)
}
Carried::Tag => {
let (identity, counts) = annotated_tag_identity(repo, direct)?;
tag_identity = identity;
tagger_time_counts.unparseable_times += counts.unparseable_times;
tagger_time_counts.unparseable_offsets += counts.unparseable_offsets;
let (commit, nested) = peel_carried(repo, direct, limits, true)?;
nested_tag_objects += nested;
(ScannedKind::Tag(suffix_str), commit)
}
}
} else {
let dropped_kind = if name.starts_with("refs/remotes/") {
ScannedKind::Dropped("remote-tracking")
} else if name.starts_with("refs/notes/") {
ScannedKind::Dropped("notes")
} else if name == "refs/stash" {
ScannedKind::Dropped("stash")
} else {
ScannedKind::Dropped("other")
};
let lenient_commit = r.peel_to_id().ok().map(|id| id.detach()).filter(|id| {
repo.find_object(*id)
.is_ok_and(|o| matches!(o.kind, gix::objs::Kind::Commit))
});
(dropped_kind, lenient_commit)
};
out.push(ScannedRef {
kind,
commit,
tag_identity,
});
}
Ok((out, symbolic_refs, nested_tag_objects, tagger_time_counts))
}
fn peel_carried(
repo: &gix::Repository,
direct: ObjectId,
limits: &Limits,
direct_tag_is_carried: bool,
) -> Result<(Option<ObjectId>, u64), Error> {
let mut current = direct;
let mut hops = 0usize;
let mut nested_tags = 0u64;
loop {
let object = find_verified_object(repo, current)?;
match object.kind {
gix::objs::Kind::Commit => return Ok((Some(current), nested_tags)),
gix::objs::Kind::Tag => {
hops += 1;
if hops > limits.max_tag_chain {
return Err(resource_limit(
"the tag chain",
format!("{} tag(s)", limits.max_tag_chain),
));
}
if hops > 1 || !direct_tag_is_carried {
nested_tags += 1;
}
let tag = object.try_into_tag().map_err(read_err)?;
let decoded = tag.decode().map_err(read_err)?;
current = decoded.target();
}
_ => return Ok((None, nested_tags)),
}
}
}
fn annotated_tag_identity(
repo: &gix::Repository,
direct: ObjectId,
) -> Result<(Option<TagIdentity>, ParseCounts), Error> {
let object = find_verified_object(repo, direct)?;
if !matches!(object.kind, gix::objs::Kind::Tag) {
return Ok((None, ParseCounts::default()));
}
let tag = object.try_into_tag().map_err(read_err)?;
let decoded = tag.decode().map_err(read_err)?;
let signatures = decoded
.signature
.map(|s| Signature {
label: "gpgsig".to_string(),
bytes: s.to_vec(),
})
.into_iter()
.collect();
let mut counts = ParseCounts::default();
let tagger_sig = decoded.tagger().map_err(read_err)?;
let tagger = tagger_sig.map(|sig| Identity {
name: Text {
bytes: sig.name.to_vec(),
encoding: None,
},
email: Some(Text {
bytes: sig.email.to_vec(),
encoding: None,
}),
});
let time = tagger_sig.and_then(|sig| {
let seconds = strict_seconds(sig.time);
if seconds.is_none() {
counts.unparseable_times += 1;
}
seconds.map(|seconds| {
let offset_minutes = strict_offset_minutes(sig.time);
if offset_minutes.is_none() {
counts.unparseable_offsets += 1;
}
Time {
seconds,
offset_minutes,
}
})
});
let message = Text {
bytes: decoded.message.to_vec(),
encoding: None,
};
let annotation = Annotation {
tagger,
time,
message: Some(message),
};
Ok((Some((direct, signatures, Some(annotation))), counts))
}
fn commit_parents(
repo: &gix::Repository,
set: &BTreeSet<ObjectId>,
) -> Result<BTreeMap<ObjectId, Vec<ObjectId>>, Error> {
let mut parents = BTreeMap::new();
for id in set {
let commit = find_verified_object(repo, *id)?
.try_into_commit()
.map_err(read_err)?;
let mut ps = Vec::new();
for p in commit.parent_ids() {
let p = p.detach();
if !set.contains(&p) {
return Err(Error::Read(
"history walk disagrees with commit content".to_string(),
));
}
ps.push(p);
}
parents.insert(*id, ps);
}
Ok(parents)
}
fn parent_first_order(
set: &BTreeSet<ObjectId>,
parents: &BTreeMap<ObjectId, Vec<ObjectId>>,
) -> Result<Vec<ObjectId>, Error> {
let mut indeg: BTreeMap<ObjectId, usize> = set.iter().map(|id| (*id, 0usize)).collect();
let mut children: BTreeMap<ObjectId, Vec<ObjectId>> = BTreeMap::new();
for (id, ps) in parents {
for p in ps {
children.entry(*p).or_default().push(*id);
if let Some(d) = indeg.get_mut(id) {
*d += 1;
}
}
}
let mut ready: BTreeSet<ObjectId> = indeg
.iter()
.filter_map(|(id, d)| (*d == 0).then_some(*id))
.collect();
let mut order = Vec::with_capacity(set.len());
while let Some(id) = ready.iter().next().copied() {
ready.remove(&id);
order.push(id);
if let Some(kids) = children.get(&id) {
for kid in kids {
if let Some(d) = indeg.get_mut(kid) {
*d = d.saturating_sub(1);
if *d == 0 {
ready.insert(*kid);
}
}
}
}
}
if order.len() != set.len() {
return Err(Error::Read(
"commit graph contains a cycle (a Git history must be acyclic)".to_string(),
));
}
Ok(order)
}
struct SnapshotCache {
snaps: HashMap<ObjectId, Snapshot>,
remaining: HashMap<ObjectId, usize>,
}
impl SnapshotCache {
fn new(uses: HashMap<ObjectId, usize>) -> Self {
Self {
snaps: HashMap::new(),
remaining: uses,
}
}
fn get_or_build(
&mut self,
tree_id: ObjectId,
build: impl FnOnce() -> Result<Snapshot, Error>,
) -> Result<Snapshot, Error> {
if let Some(s) = self.snaps.get(&tree_id) {
return Ok(s.clone());
}
let out = build()?;
self.snaps.insert(tree_id, out.clone());
Ok(out)
}
fn release(&mut self, tree_id: ObjectId) {
if let Some(n) = self.remaining.get_mut(&tree_id) {
*n = n.saturating_sub(1);
if *n == 0 {
self.remaining.remove(&tree_id);
self.snaps.remove(&tree_id);
}
}
}
#[cfg(test)]
fn len(&self) -> usize {
self.snaps.len()
}
}
fn count_snapshot_uses(
repo: &gix::Repository,
order: &[ObjectId],
parents: &BTreeMap<ObjectId, Vec<ObjectId>>,
) -> HashMap<ObjectId, usize> {
let mut tree_of: HashMap<ObjectId, ObjectId> = HashMap::with_capacity(order.len());
let mut uses: HashMap<ObjectId, usize> = HashMap::new();
for id in order {
let Some(tree) = find_verified_object(repo, *id)
.ok()
.and_then(|o| o.try_into_commit().ok())
.and_then(|c| c.tree_id().ok())
.map(gix::Id::detach)
else {
continue;
};
tree_of.insert(*id, tree);
*uses.entry(tree).or_insert(0) += 1;
if let Some(p0) = parents.get(id).and_then(|ps| ps.first()) {
if let Some(pt) = tree_of.get(p0) {
*uses.entry(*pt).or_insert(0) += 1;
}
}
}
uses
}
const GITLINK_MODE: u32 = 0o160_000;
fn snapshot(
repo: &gix::Repository,
tree_id: ObjectId,
commit_id: ObjectId,
limits: &Limits,
cache: &mut SnapshotCache,
) -> Result<Snapshot, Error> {
cache.get_or_build(tree_id, || {
let mut out = Snapshot::new();
walk_tree(repo, tree_id, commit_id, limits, &mut out)?;
Ok(out)
})
}
fn walk_tree(
repo: &gix::Repository,
root_tree_id: ObjectId,
commit_id: ObjectId,
limits: &Limits,
out: &mut Snapshot,
) -> Result<(), Error> {
let mut stack: Vec<(ObjectId, String, usize)> = vec![(root_tree_id, String::new(), 1)];
let mut visited: usize = 0;
while let Some((tree_id, prefix, depth)) = stack.pop() {
let tree = find_verified_object(repo, tree_id)?
.try_into_tree()
.map_err(read_err)?;
for entry in tree.iter() {
visited = visited.saturating_add(1);
if visited > limits.max_tree_entries {
return Err(resource_limit(
"one tree in this repository",
format!("{} entries", limits.max_tree_entries),
));
}
let entry = entry.map_err(read_err)?;
let raw_name = entry.filename(); let Ok(name) = std::str::from_utf8(raw_name) else {
return Err(Error::FloorRefusal {
feature: floor::NON_UTF8_PATH.to_string(),
reason: format!(
"commit {commit_id}: path '{prefix}{}{}' is not valid UTF-8 (invalid bytes \
shown as \\xNN)",
if prefix.is_empty() { "" } else { "/" },
escape_invalid_utf8(raw_name)
),
});
};
let path = if prefix.is_empty() {
name.to_string()
} else {
format!("{prefix}/{name}")
};
if path.len() > limits.max_path_bytes {
return Err(resource_limit(
"a path",
format!("{} bytes", limits.max_path_bytes),
));
}
let mode = entry.mode();
let oid = entry.oid().to_owned();
match mode.kind() {
gix::objs::tree::EntryKind::Tree => {
let child_depth = depth + 1;
if child_depth > limits.max_tree_depth {
return Err(resource_limit(
"the tree nesting",
format!("{} levels", limits.max_tree_depth),
));
}
stack.push((oid, path, child_depth));
}
_ => {
if out.contains_key(&path) {
return Err(Error::Read(format!(
"commit {commit_id}: duplicate path '{path}' in tree snapshot"
)));
}
out.insert(path, (oid, u32::from(mode.value())));
}
}
}
}
Ok(())
}
fn diff_to_ops(
repo: &gix::Repository,
base: &Snapshot,
child: &Snapshot,
opts: &Options,
limits: &Limits,
builder: &mut IrBuilder,
from_parent: Option<AtomId>,
) -> Result<(Vec<PathOp>, Vec<CopyRecord>), Error> {
let mut ops = Vec::new();
let mut added_by_oid: BTreeMap<ObjectId, Vec<String>> = BTreeMap::new();
let mut deleted_by_oid: BTreeMap<ObjectId, Vec<String>> = BTreeMap::new();
for (path, (oid, mode)) in child {
let child_is_submodule = *mode == GITLINK_MODE;
match base.get(path) {
None => {
let content = content_for(repo, *oid, *mode, limits, builder)?;
ops.push(PathOp::Add {
path: path.clone(),
content,
status: EpistemicStatus::Stated,
});
if !child_is_submodule {
added_by_oid.entry(*oid).or_default().push(path.clone());
}
}
Some((base_oid, base_mode)) => {
let base_is_submodule = *base_mode == GITLINK_MODE;
if base_is_submodule != child_is_submodule {
let content = content_for(repo, *oid, *mode, limits, builder)?;
ops.push(PathOp::Replace {
path: path.clone(),
content,
status: EpistemicStatus::Stated,
});
} else if base_oid != oid || base_mode != mode {
let content = content_for(repo, *oid, *mode, limits, builder)?;
ops.push(PathOp::Modify {
path: path.clone(),
content,
status: EpistemicStatus::Stated,
});
}
}
}
}
for (path, (oid, mode)) in base {
if !child.contains_key(path) {
ops.push(PathOp::Delete {
path: path.clone(),
status: EpistemicStatus::Stated,
});
if *mode != GITLINK_MODE {
deleted_by_oid.entry(*oid).or_default().push(path.clone());
}
}
}
let mut copies = Vec::new();
if opts.infer_renames {
if let Some(from_atom) = from_parent {
for (oid, froms) in &deleted_by_oid {
let [from] = froms.as_slice() else {
continue; };
let Some([to]) = added_by_oid.get(oid).map(Vec::as_slice) else {
continue; };
copies.push(CopyRecord {
from: from.clone(),
from_atom,
to: to.clone(),
status: EpistemicStatus::Derived(Derivation {
kind: DerivationKind::InferredRename,
by: DECODER.to_string(),
decoder_version: decoder_version().to_string(),
params: opts.as_params(),
confidence: Some(100),
}),
});
}
}
}
Ok((ops, copies))
}
fn content_for(
repo: &gix::Repository,
oid: ObjectId,
mode: u32,
limits: &Limits,
builder: &mut IrBuilder,
) -> Result<Content, Error> {
if mode == GITLINK_MODE {
Ok(Content::submodule(oid.as_bytes().to_vec()))
} else {
let blob = builder.add_blob(blob_bytes(repo, oid, limits)?)?;
Ok(Content::blob(blob, mode))
}
}
fn blob_bytes(repo: &gix::Repository, oid: ObjectId, limits: &Limits) -> Result<Vec<u8>, Error> {
let header = repo.find_header(oid).map_err(read_err)?;
if header.size() > limits.max_blob_bytes {
return Err(resource_limit(
"a blob",
format!("{} bytes", limits.max_blob_bytes),
));
}
Ok(find_verified_object(repo, oid)?
.try_into_blob()
.map_err(read_err)?
.data
.clone())
}
fn strict_seconds(raw: &str) -> Option<i64> {
let token = raw.split_whitespace().next()?;
let digits = token.strip_prefix('-').unwrap_or(token);
if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
token.parse::<i64>().ok()
}
fn strict_offset_minutes(raw: &str) -> Option<i16> {
let mut tokens = raw.split_whitespace();
let _seconds = tokens.next()?;
let tz = tokens.next()?;
let sign = match tz.as_bytes().first()? {
b'+' => 1i32,
b'-' => -1i32,
_ => return None,
};
let digits = tz.get(1..)?;
if digits.len() != 4 || !digits.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
let hh: i32 = digits.get(..2)?.parse().ok()?;
let mm: i32 = digits.get(2..)?.parse().ok()?;
if mm >= 60 {
return None;
}
i16::try_from(sign * (hh * 60 + mm)).ok()
}
fn build_metadata(commit: &gix::Commit<'_>) -> Result<(MetadataClaims, ParseCounts), Error> {
let author = commit.author().map_err(read_err)?;
let committer = commit.committer().map_err(read_err)?;
let decoded = commit.decode().map_err(read_err)?;
let message = decoded.message;
let mut counts = ParseCounts::default();
let message_encoding = match decoded.encoding {
Some(e) => match std::str::from_utf8(e) {
Ok(s) => Some(s.to_string()),
Err(_) => {
counts.undecodable_encodings += 1;
None
}
},
None => None,
};
let author_time = strict_seconds(author.time);
if author_time.is_none() {
counts.unparseable_times += 1;
}
let author_offset = strict_offset_minutes(author.time);
if author_time.is_some() && author_offset.is_none() {
counts.unparseable_offsets += 1;
}
let commit_time = strict_seconds(committer.time);
if commit_time.is_none() {
counts.unparseable_times += 1;
}
let commit_offset = strict_offset_minutes(committer.time);
if commit_time.is_some() && commit_offset.is_none() {
counts.unparseable_offsets += 1;
}
let raw_text = |bytes: &[u8]| Text {
bytes: bytes.to_vec(),
encoding: None,
};
Ok((
MetadataClaims {
author: Some(Identity {
name: raw_text(author.name.as_ref()),
email: Some(raw_text(author.email.as_ref())),
}),
author_time: author_time.map(|seconds| Time {
seconds,
offset_minutes: author_offset,
}),
committer: Some(Identity {
name: raw_text(committer.name.as_ref()),
email: Some(raw_text(committer.email.as_ref())),
}),
commit_time: commit_time.map(|seconds| Time {
seconds,
offset_minutes: commit_offset,
}),
message: Some(Text {
bytes: message.to_vec(),
encoding: message_encoding,
}),
},
counts,
))
}
#[derive(Debug, Clone, Copy, Default)]
struct ParseCounts {
unparseable_times: u64,
unparseable_offsets: u64,
undecodable_encodings: u64,
}
fn signatures_and_extras(
commit: &gix::Commit<'_>,
id: ObjectId,
) -> Result<(Vec<Signature>, Vec<Extra>), Error> {
let decoded = commit.decode().map_err(read_err)?;
let mut signatures = Vec::new();
let mut extras = Vec::new();
for (name, value) in &decoded.extra_headers {
let Ok(label) = std::str::from_utf8(name) else {
return Err(Error::FloorRefusal {
feature: floor::NON_UTF8_COMMIT_HEADER_NAME.to_string(),
reason: format!(
"commit {id}: header name '{}' is not valid UTF-8 (invalid bytes shown as \\xNN)",
escape_invalid_utf8(name)
),
});
};
match label {
"gpgsig" | "gpgsig-sha256" => signatures.push(Signature {
label: label.to_string(),
bytes: value.to_vec(),
}),
_ => extras.push(Extra {
label: label.to_string(),
bytes: value.to_vec(),
}),
}
}
Ok((signatures, extras))
}
fn loss_boundary(
dropped_namespace_counts: &BTreeMap<&'static str, u64>,
dropped_only_commits: DroppedOnlyCommits,
non_commit_refs: u64,
symbolic_refs: u64,
time_counts: ParseCounts,
nested_tag_objects: u64,
) -> LossBoundary {
let mut dropped = vec![
DropRecord {
class: LossClass::Representation,
what: "packfile and delta layout, physical object store".to_string(),
reason: "representation not assertion; reconstructible from the objects".to_string(),
step: None,
},
DropRecord {
class: LossClass::Representation,
what: "index and working tree".to_string(),
reason: "local state, not history".to_string(),
step: None,
},
DropRecord {
class: LossClass::Representation,
what: "reflogs".to_string(),
reason: "local operation log, not history".to_string(),
step: None,
},
];
for (ns, count) in dropped_namespace_counts {
dropped.push(DropRecord {
class: LossClass::Representation,
what: format!("{ns} refs ({count})"),
reason: "workflow/representation refs, not authored history".to_string(),
step: None,
});
}
match dropped_only_commits {
DroppedOnlyCommits::Counted(0) => {}
DroppedOnlyCommits::Counted(n) => {
dropped.push(DropRecord {
class: LossClass::Representation,
what: format!("commits reachable only from dropped refs ({n})"),
reason:
"workflow state (stash, notes, remote-tracking), not authored history of a \
carried ref"
.to_string(),
step: None,
});
}
DroppedOnlyCommits::Unavailable => {
dropped.push(DropRecord {
class: LossClass::Representation,
what: "commits reachable only from dropped refs (count unavailable)".to_string(),
reason: "a commit in dropped-only history could not be read".to_string(),
step: None,
});
}
}
if non_commit_refs > 0 {
dropped.push(DropRecord {
class: LossClass::Other,
what: format!("refs to non-commit objects ({non_commit_refs})"),
reason: "a tag or branch naming a tree or blob; the IR's refs point at history atoms"
.to_string(),
step: None,
});
}
if symbolic_refs > 0 {
dropped.push(DropRecord {
class: LossClass::Representation,
what: format!("symbolic refs ({symbolic_refs})"),
reason:
"an alias to another ref; the IR has no alias concept; the target ref is carried \
on its own"
.to_string(),
step: None,
});
}
if time_counts.unparseable_times > 0 {
dropped.push(DropRecord {
class: LossClass::Other,
what: format!(
"unparseable author/committer/tagger times ({})",
time_counts.unparseable_times
),
reason: "the source's time field could not be parsed; the claim is absent rather than \
fabricated"
.to_string(),
step: None,
});
}
if time_counts.unparseable_offsets > 0 {
dropped.push(DropRecord {
class: LossClass::Other,
what: format!(
"unparseable author/committer/tagger timezone offsets ({})",
time_counts.unparseable_offsets
),
reason: "the source's timezone offset could not be parsed strictly (`+HHMM`/`-HHMM`); \
the time is carried without an offset rather than a fabricated or salvaged one"
.to_string(),
step: None,
});
}
if time_counts.undecodable_encodings > 0 {
dropped.push(DropRecord {
class: LossClass::Other,
what: format!(
"undecodable encoding headers ({})",
time_counts.undecodable_encodings
),
reason:
"the commit's declared `encoding` header value was not valid UTF-8, so it is not \
carried on the message's `Text.encoding`"
.to_string(),
step: None,
});
}
if nested_tag_objects > 0 {
dropped.push(DropRecord {
class: LossClass::Other,
what: format!("nested tag objects not carried ({nested_tag_objects})"),
reason: "an intermediate tag object in a tag-of-a-tag chain; only the outer tag's \
annotation is carried"
.to_string(),
step: None,
});
}
LossBoundary { dropped }
}
#[cfg(test)]
mod tests;