use std::collections::{BTreeMap, HashMap, HashSet};
use std::io::Write;
use brygge_ir::{
AtomId, BlobId, Content, Ir, LossClass, PathOp, RefKind, RefRecord, SourceKind, TransformRecord,
};
mod check;
mod trailers;
pub(crate) use check::{Comparison, GitRef, GitRefTarget, compare_git_target};
use trailers::{Altered, Supplied};
const SCRATCH_REF: &str = "refs/heads/brygge-encode-git-scratch";
fn is_writable_mode(mode: u32) -> bool {
matches!(mode, 0o100_644 | 0o100_755 | 0o120_000)
}
fn git_mode_str(mode: u32) -> &'static str {
match mode {
0o100_644 => "100644",
0o100_755 => "100755",
0o120_000 => "120000",
_ => unreachable!("is_writable_mode must be checked first"),
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Refusal {
BadMode {
atom_source_id: String,
path: String,
mode: u32,
},
RefCollision {
git_ref: String,
first: (String, String),
second: (String, String),
},
NonUtf8TagMessage {
name: String,
},
InvalidRefName {
git_ref: String,
reason: String,
},
UnreachableAtoms {
count: usize,
first: Vec<String>,
fix: String,
},
}
impl std::fmt::Display for Refusal {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::BadMode {
atom_source_id,
path,
mode,
} => write!(
f,
"atom {atom_source_id}: path {path:?} has mode {mode:#o}, which Git cannot write (only \
100644, 100755 and 120000 are accepted)"
),
Self::RefCollision {
git_ref,
first,
second,
} => write!(
f,
"two IR refs both map to Git ref {git_ref:?}: {:?} ({}) and {:?} ({})",
first.0, first.1, second.0, second.1
),
Self::NonUtf8TagMessage { name } => write!(
f,
"tag {name:?}: its annotation message is not UTF-8, which git fast-import cannot carry \
for a tag (only a commit message keeps a declared encoding)"
),
Self::InvalidRefName { git_ref, reason } => {
write!(f, "ref {git_ref:?} is not a valid Git ref name: {reason}")
}
Self::UnreachableAtoms { count, first, fix } => write!(
f,
"{count} atom(s) are not reachable from any ref, starting with {} — {fix}",
first.join(", ")
),
}
}
}
fn ref_kind_label(kind: &RefKind) -> String {
match kind {
RefKind::Branch => "Branch".to_string(),
RefKind::Tag => "Tag".to_string(),
RefKind::Bookmark => "Bookmark".to_string(),
RefKind::NamedBranch => "NamedBranch".to_string(),
RefKind::Other(label) => format!("Other({label})"),
}
}
fn is_branch_like(kind: &RefKind) -> bool {
matches!(
kind,
RefKind::Branch | RefKind::Bookmark | RefKind::NamedBranch
)
}
pub(crate) const OTHER_NAMESPACE: &str = "refs/brygge/other/";
pub(crate) fn git_ref_path(rf: &RefRecord) -> String {
match rf.kind {
RefKind::Tag => format!("refs/tags/{}", rf.name),
RefKind::Branch | RefKind::Bookmark | RefKind::NamedBranch => {
format!("refs/heads/{}", rf.name)
}
RefKind::Other(_) => format!("{OTHER_NAMESPACE}{}", rf.name),
}
}
fn ref_collisions(refs: &[RefRecord]) -> Vec<Refusal> {
let mut seen: BTreeMap<String, (String, String)> = BTreeMap::new();
let mut out = Vec::new();
for rf in refs {
let path = git_ref_path(rf);
let label = ref_kind_label(&rf.kind);
if let Some(first) = seen.get(&path) {
out.push(Refusal::RefCollision {
git_ref: path,
first: first.clone(),
second: (rf.name.clone(), label),
});
} else {
seen.insert(path, (rf.name.clone(), label));
}
}
out
}
fn bad_modes(ir: &Ir) -> Vec<Refusal> {
let mut out = Vec::new();
for atom in &ir.atoms {
for op in &atom.ops {
let (path, mode) = match op {
PathOp::Add { path, content, .. }
| PathOp::Modify { path, content, .. }
| PathOp::Replace { path, content, .. } => match content {
Content::Blob { mode, .. } => (path, *mode),
Content::Submodule { .. } => continue,
},
PathOp::Delete { .. } => continue,
};
if !is_writable_mode(mode) {
out.push(Refusal::BadMode {
atom_source_id: trailers::truncate_for_refusal(&trailers::source_id_text(
&atom.source.kind,
&atom.source.atom_id,
)),
path: path.clone(),
mode,
});
}
}
}
out
}
fn non_utf8_tag_messages(ir: &Ir) -> Vec<Refusal> {
let mut out = Vec::new();
for rf in &ir.refs {
if rf.kind != RefKind::Tag {
continue;
}
if let Some(annotation) = &rf.annotation {
if let Some(message) = &annotation.message {
if message.as_utf8().is_none() {
out.push(Refusal::NonUtf8TagMessage {
name: rf.name.clone(),
});
}
}
}
}
out
}
fn reachability_fix_hint(ir: &Ir) -> String {
let refs_present = !ir.refs.is_empty();
match &ir.provenance.source.kind {
SourceKind::Svn | SourceKind::Cvs => {
if refs_present {
"no reconstructed ref reaches these atoms".to_string()
} else {
"decode with --reconstruct-refs, which is needed to give this history any ref at all"
.to_string()
}
}
SourceKind::Git | SourceKind::Hg => {
let step = ir
.loss
.dropped
.iter()
.find(|d| d.class == LossClass::Transform && d.what.starts_with("ref "))
.and_then(|d| d.step);
match step {
Some(step) => format!("a ref was removed by a transform (step {step})"),
None => "a ref was removed by a transform".to_string(),
}
}
SourceKind::Other(_) => {
if refs_present {
"no ref reaches these atoms".to_string()
} else {
"decode with whichever option reconstructs refs for this source, if one exists"
.to_string()
}
}
}
}
fn unreachable_atoms(ir: &Ir) -> Vec<Refusal> {
let by_id: HashMap<AtomId, &brygge_ir::ChangeAtom> =
ir.atoms.iter().map(|a| (a.id, a)).collect();
let mut reachable: HashSet<AtomId> = HashSet::new();
let mut stack: Vec<AtomId> = ir.refs.iter().map(|rf| rf.target).collect();
while let Some(id) = stack.pop() {
if reachable.insert(id) {
if let Some(atom) = by_id.get(&id) {
stack.extend(atom.parents.iter().copied());
}
}
}
let unreachable: Vec<&brygge_ir::ChangeAtom> = ir
.atoms
.iter()
.filter(|a| !reachable.contains(&a.id))
.collect();
if unreachable.is_empty() {
return Vec::new();
}
vec![Refusal::UnreachableAtoms {
count: unreachable.len(),
first: unreachable
.iter()
.take(5)
.map(|a| {
trailers::truncate_for_refusal(&trailers::source_id_text(
&a.source.kind,
&a.source.atom_id,
))
})
.collect(),
fix: reachability_fix_hint(ir),
}]
}
#[must_use]
pub(crate) fn preflight(ir: &Ir) -> Vec<Refusal> {
let mut out = bad_modes(ir);
out.extend(ref_collisions(&ir.refs));
out.extend(unreachable_atoms(ir));
out.extend(non_utf8_tag_messages(ir));
out
}
pub(crate) struct DefaultBranch {
pub(crate) name: String,
pub(crate) existed: bool,
}
#[must_use]
pub(crate) fn choose_default_branch(ir: &Ir) -> DefaultBranch {
for candidate in ["trunk", "main", "master", "default"] {
if ir
.refs
.iter()
.any(|rf| is_branch_like(&rf.kind) && rf.name == candidate)
{
return DefaultBranch {
name: candidate.to_string(),
existed: true,
};
}
}
if let Some(rf) = ir.refs.iter().find(|rf| is_branch_like(&rf.kind)) {
return DefaultBranch {
name: rf.name.clone(),
existed: true,
};
}
DefaultBranch {
name: "main".to_string(),
existed: false,
}
}
#[derive(Debug, Default)]
pub(crate) struct Summary {
pub(crate) commits: u64,
pub(crate) tags: u64,
pub(crate) refs: u64,
pub(crate) supplied: BTreeMap<String, u64>,
pub(crate) altered: BTreeMap<String, u64>,
pub(crate) unplaced_ref_transforms: Vec<String>,
}
struct Context<'a> {
digest_hex: &'a str,
brygge_version: &'a str,
source_label: &'a str,
}
fn fold_u64_map<K: Ord>(into: &mut BTreeMap<K, u64>, from: BTreeMap<K, u64>) {
for (k, v) in from {
*into.entry(k).or_insert(0) += v;
}
}
fn fold_supplied(summary: &mut Summary, supplied: &Supplied) {
supplied.fold_into(&mut summary.supplied);
}
fn fold_altered(summary: &mut Summary, altered: &Altered) {
let mut totals: BTreeMap<String, u64> = BTreeMap::new();
altered.fold_into(&mut totals);
fold_u64_map(&mut summary.altered, totals);
}
pub(crate) fn write_stream<W: Write>(
ir: &Ir,
digest: &[u8; 32],
out: &mut W,
) -> std::io::Result<Summary> {
let mut next_mark: u64 = 1;
let mut blob_marks: BTreeMap<BlobId, u64> = BTreeMap::new();
let mut atom_marks: BTreeMap<AtomId, u64> = BTreeMap::new();
let digest_hex = trailers::to_hex(digest);
let brygge_version = env!("CARGO_PKG_VERSION");
let mut summary = Summary::default();
let source_label = trailers::source_kind_label(&ir.provenance.source.kind);
let ctx = Context {
digest_hex: &digest_hex,
brygge_version,
source_label: &source_label,
};
for blob in brygge_ir::artifact::store_order(ir) {
let mark = next_mark;
next_mark += 1;
blob_marks.insert(blob, mark);
let bytes = ir
.content
.get(&blob)
.map_err(std::io::Error::other)?
.ok_or_else(|| {
std::io::Error::other(format!("blob {blob} indexed but not readable"))
})?;
writeln!(out, "blob")?;
writeln!(out, "mark :{mark}")?;
writeln!(out, "data {}", bytes.len())?;
out.write_all(&bytes)?;
writeln!(out)?;
}
for atom in &ir.atoms {
let mut supplied = Supplied::default();
let mut altered = Altered::default();
let author_line = trailers::identity_line(
atom.metadata.author.as_ref(),
&mut supplied,
&mut altered,
"author",
);
let author_when = trailers::when(
atom.metadata.author_time,
&mut supplied,
"author-time",
"author-time-zone",
);
let (committer_line, committer_when) =
match (&atom.metadata.committer, atom.metadata.commit_time) {
(None, None) => {
supplied.mark("committer");
supplied.mark("commit-time");
(author_line.clone(), author_when.clone())
}
(committer, commit_time) => {
let committer_line = if committer.is_some() {
trailers::identity_line(
committer.as_ref(),
&mut supplied,
&mut altered,
"committer",
)
} else {
supplied.mark("committer");
author_line.clone()
};
let committer_when = if commit_time.is_some() {
trailers::when(
commit_time,
&mut supplied,
"commit-time",
"commit-time-zone",
)
} else {
supplied.mark("commit-time");
author_when.clone()
};
(committer_line, committer_when)
}
};
let message = atom
.metadata
.message
.as_ref()
.map(|t| t.bytes.clone())
.unwrap_or_default();
let source_id = trailers::source_id_text(&atom.source.kind, &atom.source.atom_id);
let mut trailer_lines = vec![
format!("Brygge-Encoded: brygge {brygge_version} from {source_label}"),
format!("Brygge-Source-Id: {source_id}"),
];
if let Some(line) = supplied.trailer() {
trailer_lines.push(line);
}
if let Some(line) = altered.trailer() {
trailer_lines.push(line);
}
trailer_lines.extend(trailers::status_trailers(atom, &ir.transforms));
trailer_lines.push(format!("Brygge-Artifact: sha256:{digest_hex}"));
fold_supplied(&mut summary, &supplied);
fold_altered(&mut summary, &altered);
let mut body = message;
if !body.ends_with(b"\n") {
body.push(b'\n');
}
body.push(b'\n');
body.extend(trailer_lines.join("\n").into_bytes());
let mark = next_mark;
next_mark += 1;
atom_marks.insert(atom.id, mark);
writeln!(out, "commit {SCRATCH_REF}")?;
writeln!(out, "mark :{mark}")?;
writeln!(out, "author {author_line} {author_when}")?;
writeln!(out, "committer {committer_line} {committer_when}")?;
if let Some(encoding) = atom
.metadata
.message
.as_ref()
.and_then(|t| t.encoding.as_deref())
{
writeln!(out, "encoding {encoding}")?;
}
writeln!(out, "data {}", body.len())?;
out.write_all(&body)?;
writeln!(out)?;
let mut parents = atom.parents.iter();
if let Some(first) = parents.next() {
let parent_mark = atom_marks.get(first).copied().ok_or_else(|| {
std::io::Error::other(format!(
"atom {first} is not yet encoded (not canonically ordered)"
))
})?;
writeln!(out, "from :{parent_mark}")?;
}
for other in parents {
let parent_mark = atom_marks.get(other).copied().ok_or_else(|| {
std::io::Error::other(format!(
"atom {other} is not yet encoded (not canonically ordered)"
))
})?;
writeln!(out, "merge :{parent_mark}")?;
}
for op in &atom.ops {
match op {
PathOp::Add { path, content, .. }
| PathOp::Modify { path, content, .. }
| PathOp::Replace { path, content, .. } => match content {
Content::Blob { blob, mode } => {
#[allow(clippy::expect_used)]
let blob_mark = *blob_marks.get(blob).expect(
"every blob an op references was just emitted above, in this same atom",
);
writeln!(
out,
"M {} :{blob_mark} {}",
git_mode_str(*mode),
trailers::path_token(path)
)?;
}
Content::Submodule { commit } => {
writeln!(
out,
"M 160000 {} {}",
trailers::to_hex(commit),
trailers::path_token(path)
)?;
}
},
PathOp::Delete { path, .. } => {
writeln!(out, "D {}", trailers::path_token(path))?;
}
}
}
summary.commits += 1;
}
if !ir.atoms.is_empty() {
for rf in &ir.refs {
#[allow(clippy::expect_used)]
let mark = *atom_marks
.get(&rf.target)
.expect("verify already confirmed every ref targets a written atom");
let is_tag = write_ref(out, rf, mark, &ir.transforms, &ctx, &mut summary)?;
if is_tag {
summary.tags += 1;
}
summary.refs += 1;
}
writeln!(out, "reset {SCRATCH_REF}")?;
}
writeln!(out, "done")?;
Ok(summary)
}
fn write_ref<W: Write>(
out: &mut W,
rf: &RefRecord,
mark: u64,
transforms: &[TransformRecord],
ctx: &Context<'_>,
summary: &mut Summary,
) -> std::io::Result<bool> {
let transform_lines = if matches!(rf.status, brygge_ir::EpistemicStatus::Transformed { .. }) {
trailers::status_chain_trailers(&format!("ref:{}", rf.name), &rf.status, transforms)
} else {
Vec::new()
};
match (&rf.kind, &rf.annotation) {
(RefKind::Tag, Some(annotation)) => {
let mut supplied = Supplied::default();
let mut altered = Altered::default();
let tagger_line = trailers::identity_line(
annotation.tagger.as_ref(),
&mut supplied,
&mut altered,
"tagger",
);
let tagger_when =
trailers::when(annotation.time, &mut supplied, "tag-time", "tag-time-zone");
let mut message = annotation
.message
.as_ref()
.map(|t| t.bytes.clone())
.unwrap_or_default();
let mut trailer_lines = vec![format!(
"Brygge-Encoded: brygge {} from {}",
ctx.brygge_version, ctx.source_label
)];
if let Some(line) = supplied.trailer() {
trailer_lines.push(line);
}
if let Some(line) = altered.trailer() {
trailer_lines.push(line);
}
trailer_lines.extend(transform_lines);
trailer_lines.push(format!("Brygge-Artifact: sha256:{}", ctx.digest_hex));
if !message.ends_with(b"\n") {
message.push(b'\n');
}
message.push(b'\n');
message.extend(trailer_lines.join("\n").into_bytes());
fold_supplied(summary, &supplied);
fold_altered(summary, &altered);
writeln!(out, "tag {}", rf.name)?;
writeln!(out, "from :{mark}")?;
writeln!(out, "tagger {tagger_line} {tagger_when}")?;
writeln!(out, "data {}", message.len())?;
out.write_all(&message)?;
writeln!(out)?;
Ok(true)
}
(RefKind::Tag, None) => {
for line in &transform_lines {
summary
.unplaced_ref_transforms
.push(format!("ref {:?}: {line}", rf.name));
}
writeln!(out, "reset refs/tags/{}", rf.name)?;
writeln!(out, "from :{mark}")?;
Ok(true)
}
_ => {
for line in &transform_lines {
summary
.unplaced_ref_transforms
.push(format!("ref {:?}: {line}", rf.name));
}
let path = git_ref_path(rf);
writeln!(out, "reset {path}")?;
writeln!(out, "from :{mark}")?;
Ok(false)
}
}
}
#[cfg(test)]
mod tests;