use std::collections::{BTreeSet, HashMap, HashSet};
use std::fmt::Write as _;
use std::io::Write as IoWrite;
use std::path::{Path, PathBuf};
use std::process::{Command as Subprocess, Stdio};
use brygge_decode_cvs::{Error as CvsError, Options as CvsOptions, Source as CvsSource};
use brygge_decode_git::Error as GitError;
use brygge_decode_hg::Error as HgError;
use brygge_decode_svn::{
Error as SvnError, LayoutPolicy, Options as SvnOptions, Source as SvnSource,
};
use brygge_ir::model::{AtomId, ChangedPart, FlagKind, PathOp, RefKind, Text};
use brygge_ir::status::{Derivation, DerivationKind, EpistemicStatus};
use brygge_ir::{Decoded, Ir, LossClass};
use crate::authors;
use crate::cli::{AUTHORS_TRANSFORM, Format, GIT_TARGET, SourceKind};
use crate::display;
use crate::encode_git;
use crate::exit;
use crate::output;
use crate::plugin;
const VERIFY_VERSION: u32 = 5;
const INSPECT_VERSION: u32 = 4;
const INSPECT_AUTHORS_VERSION: u32 = 1;
fn hex(bytes: &[u8]) -> String {
let mut s = String::with_capacity(bytes.len() * 2);
for b in bytes {
let _ = write!(s, "{b:02x}");
}
s
}
fn short_hex(bytes: &[u8]) -> String {
let h = hex(bytes);
h.get(..12).unwrap_or(&h).to_string()
}
fn ref_kind_label(kind: &RefKind) -> &'static str {
match kind {
RefKind::Branch => "branch",
RefKind::Tag => "tag",
RefKind::Bookmark => "bookmark",
RefKind::NamedBranch => "named-branch",
RefKind::Other(_) => "other",
}
}
fn ref_kind_other(kind: &RefKind) -> Option<&str> {
match kind {
RefKind::Other(name) => Some(name),
_ => None,
}
}
fn status_other(s: &EpistemicStatus) -> Option<&str> {
match s {
EpistemicStatus::Derived(d) => match &d.kind {
DerivationKind::Other(name) => Some(name),
_ => None,
},
EpistemicStatus::Stated | EpistemicStatus::Transformed { .. } => None,
}
}
fn loss_class_label(class: LossClass) -> &'static str {
match class {
LossClass::Representation => "representation",
LossClass::AdvisoryUnreliable => "advisory-unreliable",
LossClass::Other => "other",
LossClass::Transform => "transform",
}
}
fn flag_kind_label(kind: FlagKind) -> &'static str {
match kind {
FlagKind::ConventionViolation => "convention-violation",
FlagKind::BelowConfidenceFloor => "below-confidence-floor",
}
}
fn status_label_machine(s: &EpistemicStatus) -> String {
match s {
EpistemicStatus::Stated => "stated".to_string(),
EpistemicStatus::Derived(d) => format!("derived:{}", d.kind.label()),
EpistemicStatus::Transformed { step, .. } => format!("transformed:{step}"),
}
}
fn status_label_human(s: &EpistemicStatus) -> String {
match s {
EpistemicStatus::Stated => "stated".to_string(),
EpistemicStatus::Transformed {
step,
changed,
prior,
} => {
let parts = changed
.iter()
.map(ChangedPart::as_str)
.collect::<Vec<_>>()
.join(", ");
format!(
"transformed at {step} ({parts}) ← {}",
status_label_human(prior)
)
}
EpistemicStatus::Derived(d) => {
let mut out = format!("derived:{}", d.kind.label());
if d.params.is_empty() && d.confidence.is_none() {
return out;
}
out.push_str(" {");
let mut first = true;
for (k, v) in &d.params {
if !first {
out.push_str(", ");
}
first = false;
let _ = write!(out, "{k}={}", display::human(v));
}
if let Some(c) = d.confidence {
if !first {
out.push_str(", ");
}
let _ = write!(out, "confidence={c}");
}
out.push('}');
out
}
}
}
fn op_status(op: &PathOp) -> &EpistemicStatus {
match op {
PathOp::Add { status, .. }
| PathOp::Modify { status, .. }
| PathOp::Delete { status, .. }
| PathOp::Replace { status, .. } => status,
}
}
fn message_subject(message: Option<&Text>) -> String {
message
.and_then(Text::as_utf8)
.and_then(|s| s.lines().next())
.map(|s| display::human(s).into_owned())
.unwrap_or_default()
}
fn read_ir(path: &Path) -> Result<Decoded, String> {
brygge_ir::from_file(path).map_err(|e| format!("{}: {e}", path.display()))
}
fn infer_renames_from_provenance(ir: &Ir) -> bool {
ir.provenance
.params
.get("infer_renames")
.map(|v| v == "true")
.unwrap_or(false)
}
fn source_kind_of(ir: &Ir) -> Option<SourceKind> {
match ir.provenance.source.kind {
brygge_ir::SourceKind::Git => Some(SourceKind::Git),
brygge_ir::SourceKind::Hg => Some(SourceKind::Hg),
brygge_ir::SourceKind::Svn => Some(SourceKind::Svn),
brygge_ir::SourceKind::Cvs => Some(SourceKind::Cvs),
brygge_ir::SourceKind::Other(_) => None,
}
}
fn cvs_window_from_provenance(ir: &Ir) -> u64 {
ir.provenance
.params
.get("window_secs")
.and_then(|v| v.parse().ok())
.unwrap_or_else(|| CvsOptions::default().window_secs)
}
fn cvs_floor_from_provenance(ir: &Ir) -> u8 {
ir.provenance
.params
.get("confidence_floor")
.and_then(|v| v.parse().ok())
.unwrap_or_else(|| CvsOptions::default().confidence_floor)
}
fn reconstruct_refs_from_provenance(ir: &Ir) -> bool {
ir.provenance
.params
.get("reconstruct_refs")
.map(|v| v == "true")
.unwrap_or(false)
}
fn branch_lines_from_provenance(ir: &Ir) -> bool {
ir.provenance
.params
.get("branch_lines")
.map(|v| v == "true")
.unwrap_or(false)
}
fn layout_from_provenance(ir: &Ir) -> LayoutPolicy {
ir.provenance
.params
.get("layout")
.and_then(|l| LayoutPolicy::from_label(l))
.unwrap_or_default()
}
struct SourceOpts {
infer_renames: bool,
reconstruct_refs: bool,
branch_lines: bool,
carry_extra_namespaces: Vec<String>,
layout: LayoutPolicy,
cvs_window: u64,
cvs_floor: u8,
}
fn guard_decoder<T>(f: impl FnOnce() -> T) -> Result<T, String> {
std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).map_err(|payload| {
let detail = payload
.downcast_ref::<&str>()
.map(|s| (*s).to_string())
.or_else(|| payload.downcast_ref::<String>().cloned());
match detail {
Some(msg) => {
format!("internal decoder fault: {msg} — this is a brygge bug; please report it")
}
None => "internal decoder fault — this is a brygge bug; please report it".to_string(),
}
})
}
fn resource_limit_message(what: &str, ceiling: &str) -> String {
format!("refused: {what} exceeds brygge's ceiling ({ceiling})")
}
fn map_cvs_error(e: CvsError) -> (i32, String) {
match e {
CvsError::FloorRefusal { feature, reason } => (
exit::FLOOR_REFUSAL,
format!("refused CVS feature '{feature}' below the floor: {reason}"),
),
CvsError::ResourceLimit { what, ceiling } => {
(exit::FLOOR_REFUSAL, resource_limit_message(&what, &ceiling))
}
other => (exit::FAILURE, format!("decode failed: {other}")),
}
}
fn map_svn_error(e: SvnError) -> (i32, String) {
match e {
SvnError::FloorRefusal { feature, reason } => (
exit::FLOOR_REFUSAL,
format!("refused Subversion feature '{feature}' below the floor: {reason}"),
),
SvnError::UnsupportedFormat { what, reason } => (
exit::FLOOR_REFUSAL,
format!("unsupported Subversion dump form '{what}': {reason}"),
),
SvnError::ResourceLimit { what, ceiling } => {
(exit::FLOOR_REFUSAL, resource_limit_message(&what, &ceiling))
}
e @ SvnError::BranchLinesNoLayout => (exit::FLOOR_REFUSAL, e.to_string()),
other => (exit::FAILURE, format!("decode failed: {other}")),
}
}
fn map_git_error(e: GitError) -> (i32, String) {
match e {
GitError::FloorRefusal { feature, reason } => (
exit::FLOOR_REFUSAL,
format!("refused Git feature '{feature}' below the floor: {reason}"),
),
GitError::ResourceLimit { what, ceiling } => {
(exit::FLOOR_REFUSAL, resource_limit_message(&what, &ceiling))
}
other => (exit::FAILURE, format!("decode failed: {other}")),
}
}
fn map_hg_error(e: HgError) -> (i32, String) {
match e {
HgError::FloorRefusal { feature, reason } => (
exit::FLOOR_REFUSAL,
format!("refused Mercurial feature '{feature}' below the floor: {reason}"),
),
HgError::UnsupportedFormat {
requirement,
reason,
} => (
exit::FLOOR_REFUSAL,
format!("unsupported Mercurial format '{requirement}': {reason}"),
),
HgError::ResourceLimit { what, ceiling } => {
(exit::FLOOR_REFUSAL, resource_limit_message(&what, &ceiling))
}
other => (exit::FAILURE, format!("decode failed: {other}")),
}
}
fn decode_source(
kind: SourceKind,
repo: &Path,
opts: &SourceOpts,
storage: &brygge_ir::Storage,
) -> Result<Ir, (i32, String)> {
match kind {
SourceKind::Cvs => {
let src = CvsSource::LocalRepo(repo.to_path_buf());
let cvs = CvsOptions {
window_secs: opts.cvs_window,
confidence_floor: opts.cvs_floor,
reconstruct_refs: opts.reconstruct_refs,
};
guard_decoder(|| brygge_decode_cvs::decode_with_storage(&src, &cvs, storage))
.map_err(|fault| (exit::FAILURE, fault))?
.map_err(map_cvs_error)
}
SourceKind::Svn => {
let src = if repo.is_file() {
SvnSource::DumpFile(repo.to_path_buf())
} else {
SvnSource::LocalRepo(repo.to_path_buf())
};
let svn = SvnOptions {
reconstruct_refs: opts.reconstruct_refs,
layout: opts.layout.clone(),
branch_lines: opts.branch_lines,
};
guard_decoder(|| brygge_decode_svn::decode_with_storage(&src, &svn, storage))
.map_err(|fault| (exit::FAILURE, fault))?
.map_err(map_svn_error)
}
SourceKind::Git => {
let git = brygge_decode_git::Options {
infer_renames: opts.infer_renames,
rename_threshold: 100,
carry_extra_namespaces: opts.carry_extra_namespaces.clone(),
};
guard_decoder(|| brygge_decode_git::decode_with_storage(repo, &git, storage))
.map_err(|fault| (exit::FAILURE, fault))?
.map_err(map_git_error)
}
SourceKind::Hg => {
let hg = brygge_decode_hg::Options::default();
guard_decoder(|| brygge_decode_hg::decode_with_storage(repo, &hg, storage))
.map_err(|fault| (exit::FAILURE, fault))?
.map_err(map_hg_error)
}
}
}
#[must_use]
pub fn faithfulness_statement(kind: SourceKind) -> &'static str {
match kind {
SourceKind::Git => {
"Git: content, history and messages are carried as the source recorded them. Renames are \
inferred only with --infer-renames, and are then marked derived. Authorship is Unverifiable."
}
SourceKind::Hg => {
"Mercurial: content, history and messages are carried as recorded, including renames the \
source recorded. Authorship is Unverifiable. Secret and hidden (obsolete) changesets are \
not imported: brygge imports what the repository would publish. Tags are carried as the \
.hgtags file, not as refs."
}
SourceKind::Svn => {
"Subversion: revisions are carried as recorded. Branches and tags are only a directory \
convention; with --reconstruct-refs they are reconstructed and marked derived. Authorship is \
Unverifiable."
}
SourceKind::Cvs => {
"CVS has no atomic commits: every changeset is brygge's reconstruction (derived), and a \
changeset cannot be checked against the source. File contents and per-file history are \
carried as recorded. Authorship is Unverifiable. Branch history is imported only with \
--reconstruct-refs (a branch is identified by its symbol name); otherwise the main line is."
}
}
}
fn atomic_write(
out: &Path,
write_body: impl FnOnce(&mut std::fs::File) -> std::io::Result<u64>,
) -> std::io::Result<u64> {
let dir = out
.parent()
.filter(|p| !p.as_os_str().is_empty())
.unwrap_or_else(|| Path::new("."));
let mut tmp_name = std::ffi::OsString::from(".");
tmp_name.push(out.file_name().unwrap_or_else(|| "artifact".as_ref()));
tmp_name.push(format!(".brygge-tmp-{}", std::process::id()));
let tmp = dir.join(tmp_name);
let mut f = std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&tmp)?;
let result = (|| -> std::io::Result<u64> {
let len = write_body(&mut f)?;
f.sync_all()?;
std::fs::rename(&tmp, out)?;
if let Ok(d) = std::fs::File::open(dir) {
let _ = d.sync_all();
}
Ok(len)
})();
if result.is_err() {
let _ = std::fs::remove_file(&tmp);
}
result
}
#[allow(clippy::too_many_arguments)] pub fn run_decode(
kind: SourceKind,
source: &Path,
out: &Path,
infer_renames: bool,
reconstruct_refs: bool,
branch_lines: bool,
spill_dir: Option<&Path>,
format: Format,
) -> i32 {
output::stderr(faithfulness_statement(kind));
let dir = match spill_dir {
Some(dir) => {
if !dir.is_dir() {
output::stderr(&format!(
"--spill-dir {} does not exist or is not a directory",
dir.display()
));
return exit::USAGE;
}
dir.to_path_buf()
}
None => out
.parent()
.filter(|p| !p.as_os_str().is_empty())
.unwrap_or_else(|| Path::new("."))
.to_path_buf(),
};
let storage = brygge_ir::Storage::Spill(dir);
let default_cvs = brygge_decode_cvs::Options::default();
let ir = match decode_source(
kind,
source,
&SourceOpts {
infer_renames,
reconstruct_refs,
branch_lines,
carry_extra_namespaces: Vec::new(),
layout: LayoutPolicy::default(),
cvs_window: default_cvs.window_secs,
cvs_floor: default_cvs.confidence_floor,
},
&storage,
) {
Ok(ir) => ir,
Err((code, msg)) => {
output::stderr(&display::human(&msg));
return code;
}
};
let written = atomic_write(out, |f| {
let mut w = std::io::BufWriter::new(f);
brygge_ir::artifact::write_to(&ir, &mut w).map_err(std::io::Error::other)?;
w.flush()?;
w.get_ref().metadata().map(|m| m.len())
});
let artifact_len = match written {
Ok(len) => len,
Err(e) => {
output::stderr(&format!("cannot write {}: {e}", out.display()));
return exit::FAILURE;
}
};
output::stderr(&format!("wrote {} ({artifact_len} bytes)", out.display()));
let report = brygge_ir::honesty::summary(&ir);
let rendered = match format {
Format::Human => report.render_human(),
Format::Machine => report.render_machine(),
};
if let Some(code) = output::stdout(&rendered) {
return code;
}
fidelity_exit_class(&ir)
}
fn fidelity_exit_class(ir: &Ir) -> i32 {
if !ir.flags.is_empty() {
exit::CONVENTION_VIOLATION
} else if ir
.loss
.dropped
.iter()
.any(|d| !matches!(d.class, LossClass::Representation))
{
exit::RECORDED_LOSS
} else {
exit::CLEAN
}
}
pub fn run_inspect(artifact: &Path, atoms: bool, format: Format) -> i32 {
let decoded = match read_ir(artifact) {
Ok(d) => d,
Err(e) => {
output::stderr(&display::human(&e));
return exit::FAILURE;
}
};
if decoded.skipped_non_critical_fields > 0 {
output::stderr(&format!(
"note: {} field(s) from a newer contract were not understood and were skipped (none of \
them can change what this artifact claims)",
decoded.skipped_non_critical_fields
));
}
let ir = &decoded.ir;
let report = brygge_ir::honesty::summary(ir)
.with_skipped_non_critical_fields(decoded.skipped_non_critical_fields);
let mut rendered = match format {
Format::Human => report.render_human(),
Format::Machine => report.render_machine(),
};
rendered.push_str(&match format {
Format::Human => render_transforms_human(ir, atoms),
Format::Machine => render_transforms_machine(ir),
});
if atoms {
rendered.push_str(&match format {
Format::Human => render_atoms_human(ir, decoded.contract),
Format::Machine => render_atoms_machine(ir, decoded.contract),
});
}
if let Some(code) = output::stdout(&rendered) {
return code;
}
exit::CLEAN
}
pub fn run_inspect_authors(artifact: &Path, format: Format) -> i32 {
let decoded = match read_ir(artifact) {
Ok(d) => d,
Err(e) => {
output::stderr(&display::human(&e));
return exit::FAILURE;
}
};
let identities = authors::collect_identities(&decoded.ir);
let rendered = match format {
Format::Human => render_inspect_authors_human(&identities),
Format::Machine => render_inspect_authors_machine(&identities),
};
if let Some(code) = output::stdout(&rendered) {
return code;
}
exit::CLEAN
}
fn render_inspect_authors_human(identities: &[authors::IdentityCount]) -> String {
let mut s = String::new();
let n = identities.len();
let _ = writeln!(
s,
"# brygge inspect --authors: {n} identit{}; fill in each right-hand side, delete lines you do \
not want to map",
if n == 1 { "y" } else { "ies" }
);
let prefixes: Vec<String> = identities
.iter()
.map(|ic| {
format!(
"{} =",
display::human(&authors::identity_as_map_source(&ic.identity))
)
})
.collect();
let max_len = prefixes
.iter()
.map(|p| p.chars().count())
.max()
.unwrap_or(0);
for (ic, prefix) in identities.iter().zip(&prefixes) {
let pad = (max_len + 2).saturating_sub(prefix.chars().count());
let mut counts = Vec::new();
if ic.author > 0 {
counts.push(format!("{} author", ic.author));
}
if ic.committer > 0 {
counts.push(format!("{} committer", ic.committer));
}
if ic.tagger > 0 {
counts.push(format!("{} tagger", ic.tagger));
}
let _ = writeln!(s, "{prefix}{}# {}", " ".repeat(pad), counts.join(", "));
}
s
}
fn render_inspect_authors_machine(identities: &[authors::IdentityCount]) -> String {
let mut s = String::new();
let _ = writeln!(s, "inspect_authors_version={INSPECT_AUTHORS_VERSION}");
for (i, ic) in identities.iter().enumerate() {
let _ = writeln!(
s,
"authors.{i}.name={}",
display::machine_bytes(&ic.identity.name.bytes)
);
if let Some(email) = &ic.identity.email {
let _ = writeln!(
s,
"authors.{i}.email={}",
display::machine_bytes(&email.bytes)
);
}
let _ = writeln!(s, "authors.{i}.count.author={}", ic.author);
let _ = writeln!(s, "authors.{i}.count.committer={}", ic.committer);
let _ = writeln!(s, "authors.{i}.count.tagger={}", ic.tagger);
}
s
}
fn render_transforms_human(ir: &Ir, show_params: bool) -> String {
if ir.transforms.is_empty() {
return String::new();
}
let report = brygge_ir::honesty::summary(ir);
let mut s = String::new();
let _ = writeln!(s, "transforms: {}", ir.transforms.len());
for (k, t) in ir.transforms.iter().enumerate() {
let k64 = k as u64;
let _ = writeln!(
s,
" {k}. {} {} — consumed sha256:{}; changed {} atom(s), {} ref(s); dropped {}",
display::human(&t.name),
display::human(&t.version),
hex(&t.consumed),
report.transformed_atoms.get(&k64).copied().unwrap_or(0),
report.transformed_refs.get(&k64).copied().unwrap_or(0),
report.transformed_drops.get(&k64).copied().unwrap_or(0),
);
if show_params {
for (pk, pv) in &t.params {
let _ = writeln!(s, " {pk}={}", display::human(pv));
}
}
}
s
}
fn render_transforms_machine(ir: &Ir) -> String {
if ir.transforms.is_empty() {
return String::new();
}
let report = brygge_ir::honesty::summary(ir);
let mut s = String::new();
let _ = writeln!(s, "transforms={}", ir.transforms.len());
for (k, t) in ir.transforms.iter().enumerate() {
let k64 = k as u64;
let _ = writeln!(s, "transform.{k}.name={}", display::machine_value(&t.name));
let _ = writeln!(
s,
"transform.{k}.version={}",
display::machine_value(&t.version)
);
let _ = writeln!(s, "transform.{k}.consumed={}", hex(&t.consumed));
let _ = writeln!(
s,
"transform.{k}.changed_atoms={}",
report.transformed_atoms.get(&k64).copied().unwrap_or(0)
);
let _ = writeln!(
s,
"transform.{k}.changed_refs={}",
report.transformed_refs.get(&k64).copied().unwrap_or(0)
);
let _ = writeln!(
s,
"transform.{k}.dropped={}",
report.transformed_drops.get(&k64).copied().unwrap_or(0)
);
}
s
}
fn render_atoms_human(ir: &Ir, contract: brygge_ir::ContractVersion) -> String {
let mut s = String::new();
let _ = writeln!(
s,
"IR (contract {}): {} atom(s), {} ref(s), {} blob(s)",
contract,
ir.atoms.len(),
ir.refs.len(),
ir.content.len()
);
if contract.minor == 2 {
let _ = writeln!(
s,
"note: contract 0.2.0: an older contract; this build reads it, and writes {}",
brygge_ir::version::CURRENT
);
}
let _ = writeln!(s, "atoms (topological order):");
for atom in &ir.atoms {
let subject = message_subject(atom.metadata.message.as_ref());
let _ = writeln!(
s,
" {} [{}] src:{} {} op(s) {}",
short_hex(&atom.id.0),
status_label_human(&atom.status),
short_hex(&atom.source.atom_id),
atom.ops.len(),
subject,
);
for copy in &atom.copies {
let label = if atom.is_move(copy) { "move" } else { "copy" };
let _ = writeln!(
s,
" {label} {}@{} -> {} [{}]",
display::human(©.from),
short_hex(©.from_atom.0),
display::human(©.to),
status_label_human(©.status)
);
}
if !atom.source.signatures.is_empty() || !atom.source.extras.is_empty() {
for sig in &atom.source.signatures {
let _ = writeln!(
s,
" signature {}: {} byte(s)",
display::human(&sig.label),
sig.bytes.len()
);
}
for extra in &atom.source.extras {
let _ = writeln!(
s,
" extra {}: {} byte(s)",
display::human(&extra.label),
extra.bytes.len()
);
}
}
}
if !ir.refs.is_empty() {
let _ = writeln!(s, "refs:");
for rf in &ir.refs {
let _ = writeln!(
s,
" {} ({}) -> {} [{}]",
display::human(&rf.name),
ref_kind_label(&rf.kind),
short_hex(&rf.target.0),
status_label_human(&rf.status)
);
}
}
let _ = writeln!(s, "loss boundary:");
if ir.loss.dropped.is_empty() {
let _ = writeln!(s, " (nothing dropped)");
} else {
for drop in &ir.loss.dropped {
let _ = writeln!(
s,
" [{}] {} — {}",
loss_class_label(drop.class),
display::human(&drop.what),
display::human(&drop.reason)
);
}
}
let _ = writeln!(s, "flags:");
if ir.flags.is_empty() {
let _ = writeln!(s, " (none)");
} else {
for flag in &ir.flags {
let _ = writeln!(
s,
" [{}] {} x{} — {}",
flag_kind_label(flag.kind),
display::human(&flag.what),
flag.count,
display::human(&flag.reason)
);
}
}
s
}
fn render_atoms_machine(ir: &Ir, contract: brygge_ir::ContractVersion) -> String {
let mut s = String::new();
let _ = writeln!(s, "inspect_version={INSPECT_VERSION}");
let _ = writeln!(s, "contract_version={contract}");
for (i, atom) in ir.atoms.iter().enumerate() {
let _ = writeln!(s, "atom.{i}.id={}", hex(&atom.id.0));
let _ = writeln!(s, "atom.{i}.status={}", status_label_machine(&atom.status));
if let Some(name) = status_other(&atom.status) {
let _ = writeln!(s, "atom.{i}.status_other={}", display::machine_value(name));
}
let _ = writeln!(s, "atom.{i}.source_id={}", hex(&atom.source.atom_id));
let _ = writeln!(s, "atom.{i}.ops={}", atom.ops.len());
let _ = writeln!(s, "atom.{i}.parents={}", atom.parents.len());
let _ = writeln!(
s,
"atom.{i}.message={}",
display::machine_bytes(
atom.metadata
.message
.as_ref()
.map_or(&[][..], |m| m.bytes.as_slice())
)
);
for (j, copy) in atom.copies.iter().enumerate() {
let _ = writeln!(
s,
"atom.{i}.copy.{j}.from={}",
display::machine_value(©.from)
);
let _ = writeln!(s, "atom.{i}.copy.{j}.from_atom={}", hex(©.from_atom.0));
let _ = writeln!(
s,
"atom.{i}.copy.{j}.to={}",
display::machine_value(©.to)
);
let _ = writeln!(
s,
"atom.{i}.copy.{j}.status={}",
status_label_machine(©.status)
);
if let Some(name) = status_other(©.status) {
let _ = writeln!(
s,
"atom.{i}.copy.{j}.status_other={}",
display::machine_value(name)
);
}
let _ = writeln!(s, "atom.{i}.copy.{j}.move={}", atom.is_move(copy));
}
}
for (i, rf) in ir.refs.iter().enumerate() {
let _ = writeln!(s, "ref.{i}.name={}", display::machine_value(&rf.name));
let _ = writeln!(s, "ref.{i}.kind={}", ref_kind_label(&rf.kind));
if let Some(name) = ref_kind_other(&rf.kind) {
let _ = writeln!(s, "ref.{i}.kind_other={}", display::machine_value(name));
}
let _ = writeln!(s, "ref.{i}.target={}", hex(&rf.target.0));
let _ = writeln!(s, "ref.{i}.status={}", status_label_machine(&rf.status));
if let Some(name) = status_other(&rf.status) {
let _ = writeln!(s, "ref.{i}.status_other={}", display::machine_value(name));
}
}
for (i, drop) in ir.loss.dropped.iter().enumerate() {
let _ = writeln!(s, "loss.{i}.class={}", loss_class_label(drop.class));
let _ = writeln!(s, "loss.{i}.what={}", display::machine_value(&drop.what));
}
for (i, flag) in ir.flags.iter().enumerate() {
let _ = writeln!(s, "flag.{i}.kind={}", flag_kind_label(flag.kind));
let _ = writeln!(s, "flag.{i}.what={}", display::machine_value(&flag.what));
let _ = writeln!(s, "flag.{i}.count={}", flag.count);
}
s
}
enum CheckOutcome {
Pass,
Fail(String),
NotChecked(String),
}
impl CheckOutcome {
fn label(&self) -> &'static str {
match self {
Self::Pass => "pass",
Self::Fail(_) => "fail",
Self::NotChecked(_) => "not-checked",
}
}
fn detail(&self) -> Option<&str> {
match self {
Self::Pass => None,
Self::Fail(d) | Self::NotChecked(d) => Some(d),
}
}
fn is_fail(&self) -> bool {
matches!(self, Self::Fail(_))
}
}
fn check_structure(ir: &Ir) -> CheckOutcome {
let mut seen: HashSet<AtomId> = HashSet::new();
for (i, atom) in ir.atoms.iter().enumerate() {
for p in &atom.parents {
if !seen.contains(p) {
return CheckOutcome::Fail(format!(
"atom at position {i} has a parent id not appearing earlier in the artifact"
));
}
}
if !seen.insert(atom.id) {
return CheckOutcome::Fail(format!("duplicate atom id at position {i}"));
}
let mut paths: HashSet<&str> = HashSet::new();
for op in &atom.ops {
if !paths.insert(op.path()) {
return CheckOutcome::Fail(format!(
"atom at position {i} has more than one op for one path"
));
}
}
}
for rf in &ir.refs {
if !seen.contains(&rf.target) {
return CheckOutcome::Fail(
"a ref targets an atom not present in the artifact".to_string(),
);
}
}
let mut ref_keys: HashSet<(&str, &'static str)> = HashSet::new();
for rf in &ir.refs {
if !ref_keys.insert((rf.name.as_str(), ref_kind_label(&rf.kind))) {
return CheckOutcome::Fail("duplicate ref (name, kind)".to_string());
}
}
CheckOutcome::Pass
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
struct ReplayStats {
peak: usize,
clones: usize,
}
fn replay_ir(ir: &Ir) -> (CheckOutcome, ReplayStats) {
let mut refcount: HashMap<AtomId, usize> = HashMap::new();
for atom in &ir.atoms {
if let Some(p0) = atom.parents.first() {
*refcount.entry(*p0).or_insert(0) += 1;
}
for copy in &atom.copies {
*refcount.entry(copy.from_atom).or_insert(0) += 1;
}
}
let mut trees: HashMap<AtomId, BTreeSet<String>> = HashMap::new();
let mut stats = ReplayStats::default();
macro_rules! fail {
($msg:expr) => {
return (CheckOutcome::Fail($msg.to_string()), stats)
};
}
for atom in &ir.atoms {
let p0 = atom.parents.first().copied();
let mut tree = match p0 {
Some(p) => {
let remaining = refcount.get_mut(&p).map_or(0, |c| {
*c -= 1;
*c
});
if remaining == 0 {
match trees.remove(&p) {
Some(t) => t,
None => fail!(
"an atom's first-parent tree is unavailable (a structural inconsistency)"
),
}
} else {
match trees.get(&p) {
Some(t) => {
stats.clones += 1;
t.clone()
}
None => fail!(
"an atom's first-parent tree is unavailable (a structural inconsistency)"
),
}
}
}
None => BTreeSet::new(),
};
for copy in &atom.copies {
let source_tree_has_it = if Some(copy.from_atom) == p0 {
tree.contains(©.from)
} else {
match trees.get(©.from_atom) {
Some(t) => t.contains(©.from),
None => {
fail!("a copy's from_atom tree is unavailable (a structural inconsistency)")
}
}
};
if !source_tree_has_it {
fail!("a copy's 'from' path is not present in from_atom's replayed tree");
}
if Some(copy.from_atom) != p0 {
if let Some(c) = refcount.get_mut(©.from_atom) {
*c -= 1;
if *c == 0 {
trees.remove(©.from_atom);
}
}
}
}
for op in &atom.ops {
match op {
PathOp::Add { path, .. } => {
if !tree.insert(path.clone()) {
fail!("an Add op names an already-present path");
}
}
PathOp::Modify { path, .. } | PathOp::Replace { path, .. } => {
if !tree.contains(path) {
fail!("a Modify/Replace op names an absent path");
}
}
PathOp::Delete { path, .. } => {
if !tree.remove(path) {
fail!("a Delete op names an absent path");
}
}
}
}
if refcount.get(&atom.id).copied().unwrap_or(0) > 0 {
trees.insert(atom.id, tree);
}
stats.peak = stats.peak.max(trees.len());
}
(CheckOutcome::Pass, stats)
}
fn check_replay(ir: &Ir) -> CheckOutcome {
replay_ir(ir).0
}
fn check_derivations(ir: &Ir) -> CheckOutcome {
fn check_one(d: &Derivation) -> Result<(), String> {
if d.by.is_empty() {
return Err("a derivation's 'by' is empty".to_string());
}
if d.decoder_version.is_empty() {
return Err("a derivation's 'decoder_version' is empty".to_string());
}
if let Some(c) = d.confidence {
if c > 100 {
return Err(format!("a derivation's confidence {c} exceeds 100"));
}
}
match &d.kind {
DerivationKind::InferredRename => {
for key in ["rename_algorithm", "rename_threshold"] {
if !d.params.contains_key(key) {
return Err(format!(
"an InferredRename derivation is missing required param '{key}'"
));
}
}
}
DerivationKind::ReconstructedChangeset => {
for key in [
"window_secs",
"cluster_keys",
"date_rule",
"confidence_rule",
] {
if !d.params.contains_key(key) {
return Err(format!(
"a ReconstructedChangeset derivation is missing required param '{key}'"
));
}
}
}
DerivationKind::ReconstructedBranch => {
if !d.params.contains_key("layout") && !d.params.contains_key("source") {
return Err(
"a ReconstructedBranch derivation has neither 'layout' nor 'source' param"
.to_string(),
);
}
}
DerivationKind::InferredMerge
| DerivationKind::NormalizedMetadata
| DerivationKind::Other(_) => {}
}
Ok(())
}
fn check_status(s: &EpistemicStatus) -> Result<(), String> {
match s {
EpistemicStatus::Stated => Ok(()),
EpistemicStatus::Derived(d) => check_one(d),
EpistemicStatus::Transformed { prior, .. } => check_status(prior),
}
}
for atom in &ir.atoms {
if let Err(e) = check_status(&atom.status) {
return CheckOutcome::Fail(e);
}
for op in &atom.ops {
if let Err(e) = check_status(op_status(op)) {
return CheckOutcome::Fail(e);
}
}
for copy in &atom.copies {
if let Err(e) = check_status(©.status) {
return CheckOutcome::Fail(e);
}
}
}
for rf in &ir.refs {
if let Err(e) = check_status(&rf.status) {
return CheckOutcome::Fail(e);
}
}
CheckOutcome::Pass
}
fn innermost_status(s: &EpistemicStatus) -> &EpistemicStatus {
let mut current = s;
while let EpistemicStatus::Transformed { prior, .. } = current {
current = prior;
}
current
}
fn check_source_invariants(ir: &Ir) -> CheckOutcome {
let kind = &ir.provenance.source.kind;
let decoder_name: &str = match kind {
brygge_ir::SourceKind::Git => "brygge-decode-git",
brygge_ir::SourceKind::Hg => "brygge-decode-hg",
brygge_ir::SourceKind::Svn => "brygge-decode-svn",
brygge_ir::SourceKind::Cvs => "brygge-decode-cvs",
brygge_ir::SourceKind::Other(_) => {
return CheckOutcome::NotChecked(
"no invariants known for this source kind".to_string(),
);
}
};
if ir.provenance.decoder != decoder_name {
return CheckOutcome::Fail(format!(
"provenance.decoder is '{}', expected '{decoder_name}' for this source kind",
ir.provenance.decoder
));
}
for atom in &ir.atoms {
if &atom.source.kind != kind {
return CheckOutcome::Fail(
"an atom's source.kind does not match provenance.source.kind".to_string(),
);
}
}
match kind {
brygge_ir::SourceKind::Cvs => {
for atom in &ir.atoms {
let ok = matches!(
innermost_status(&atom.status),
EpistemicStatus::Derived(d)
if d.kind == DerivationKind::ReconstructedChangeset
|| d.kind == DerivationKind::ReconstructedBranch
);
if !ok {
return CheckOutcome::Fail(
"a CVS atom is not Derived(ReconstructedChangeset) or Derived(ReconstructedBranch)"
.to_string(),
);
}
if !atom.copies.is_empty() {
return CheckOutcome::Fail(
"a CVS atom carries a copy record; CVS records no renames".to_string(),
);
}
}
for rf in &ir.refs {
if !innermost_status(&rf.status).is_derived() {
return CheckOutcome::Fail("a CVS ref is not Derived".to_string());
}
}
}
brygge_ir::SourceKind::Svn => {
let branch_lines = ir
.provenance
.params
.get("branch_lines")
.map(|v| v == "true")
.unwrap_or(false);
for atom in &ir.atoms {
let ok = if branch_lines {
matches!(
innermost_status(&atom.status),
EpistemicStatus::Derived(d)
if d.kind == DerivationKind::ReconstructedBranch
&& d.params.get("line").map(String::as_str) == Some("true")
)
} else {
!innermost_status(&atom.status).is_derived()
};
if !ok {
return CheckOutcome::Fail(if branch_lines {
"a --branch-lines SVN atom is not Derived(ReconstructedBranch, line=true)"
.to_string()
} else {
"an SVN atom is Derived; SVN's revision spine is always Stated".to_string()
});
}
if atom.parents.len() > 1 {
return CheckOutcome::Fail(
"an SVN atom has more than one parent; SVN has no DAG".to_string(),
);
}
}
for rf in &ir.refs {
let ok = matches!(
innermost_status(&rf.status),
EpistemicStatus::Derived(d) if d.kind == DerivationKind::ReconstructedBranch
);
if !ok {
return CheckOutcome::Fail(
"an SVN ref is not Derived(ReconstructedBranch)".to_string(),
);
}
}
}
brygge_ir::SourceKind::Git => {
for atom in &ir.atoms {
for copy in &atom.copies {
if !innermost_status(©.status).is_derived() {
return CheckOutcome::Fail(
"a Git copy record is Stated; Git never states a rename".to_string(),
);
}
}
}
}
brygge_ir::SourceKind::Hg => {
for atom in &ir.atoms {
if atom.parents.len() > 2 {
return CheckOutcome::Fail("an hg atom has more than two parents".to_string());
}
}
}
brygge_ir::SourceKind::Other(_) => unreachable!("handled above"),
}
CheckOutcome::Pass
}
fn check_provenance(ir: &Ir) -> CheckOutcome {
if ir.provenance.decoder.is_empty() {
return CheckOutcome::Fail("provenance.decoder is empty".to_string());
}
if ir.provenance.decoder_version.is_empty() {
return CheckOutcome::Fail("provenance.decoder_version is empty".to_string());
}
if ir.provenance.brygge_version.is_empty() {
return CheckOutcome::Fail("provenance.brygge_version is empty".to_string());
}
CheckOutcome::Pass
}
fn check_loss_boundary(ir: &Ir) -> CheckOutcome {
for drop in &ir.loss.dropped {
if drop.what.is_empty() {
return CheckOutcome::Fail(
"a loss-boundary drop record has an empty 'what'".to_string(),
);
}
if drop.reason.is_empty() {
return CheckOutcome::Fail(
"a loss-boundary drop record has an empty 'reason'".to_string(),
);
}
}
CheckOutcome::Pass
}
#[derive(Debug)]
enum AgainstSourceOutcome {
Corresponds(Option<String>),
DoesNotCorrespond(String),
Reproduces(Option<String>),
DoesNotReproduce(String),
RootCorresponds(String),
RootReproduces(String),
NotChecked(String),
NotRun,
}
impl AgainstSourceOutcome {
fn machine_label(&self) -> &'static str {
match self {
Self::Corresponds(_) => "corresponds",
Self::DoesNotCorrespond(_) => "does-not-correspond",
Self::Reproduces(_) => "reproduces",
Self::DoesNotReproduce(_) => "does-not-reproduce",
Self::RootCorresponds(_) => "root-corresponds",
Self::RootReproduces(_) => "root-reproduces",
Self::NotChecked(_) => "not-checked",
Self::NotRun => "not-run",
}
}
fn human_label(&self) -> &'static str {
match self {
Self::Corresponds(_) => "corresponds",
Self::DoesNotCorrespond(_) => "does not correspond",
Self::Reproduces(_) => "reproduces",
Self::DoesNotReproduce(_) => "does not reproduce",
Self::RootCorresponds(_) => "the chain's root corresponds to the source",
Self::RootReproduces(_) => "the chain's root reproduces the source",
Self::NotChecked(_) => "could not be checked",
Self::NotRun => "not run",
}
}
fn detail(&self) -> Option<&str> {
match self {
Self::DoesNotCorrespond(d) | Self::DoesNotReproduce(d) | Self::NotChecked(d) => Some(d),
_ => None,
}
}
fn note(&self) -> Option<&str> {
match self {
Self::Corresponds(Some(n))
| Self::Reproduces(Some(n))
| Self::RootCorresponds(n)
| Self::RootReproduces(n) => Some(n),
_ => None,
}
}
fn is_mismatch(&self) -> bool {
matches!(self, Self::DoesNotCorrespond(_) | Self::DoesNotReproduce(_))
}
fn is_not_checked(&self) -> bool {
matches!(self, Self::NotChecked(_))
}
}
fn run_against_source(ir1: &Ir, repo: &Path, storage: &brygge_ir::Storage) -> AgainstSourceOutcome {
let Some(kind) = source_kind_of(ir1) else {
return AgainstSourceOutcome::NotChecked(
"against-source verify is not implemented for this IR's source kind".to_string(),
);
};
if kind == SourceKind::Svn {
if let Some(mismatch) = svn_source_form_mismatch(ir1, repo) {
return AgainstSourceOutcome::NotChecked(mismatch);
}
}
let opts = SourceOpts {
infer_renames: kind == SourceKind::Git && infer_renames_from_provenance(ir1),
reconstruct_refs: reconstruct_refs_from_provenance(ir1),
branch_lines: kind == SourceKind::Svn && branch_lines_from_provenance(ir1),
carry_extra_namespaces: Vec::new(),
layout: layout_from_provenance(ir1),
cvs_window: cvs_window_from_provenance(ir1),
cvs_floor: cvs_floor_from_provenance(ir1),
};
let is_cvs = kind == SourceKind::Cvs;
let ir2 = match decode_source(kind, repo, &opts, storage) {
Ok(ir) => ir,
Err((_, msg)) => {
return AgainstSourceOutcome::NotChecked(format!("cannot re-decode source: {msg}"));
}
};
let versions_differ = svn_version_note(ir1, &ir2);
let ir2 = align_svnadmin_version(ir1, ir2);
let floor_differs = decoder_floor_note(ir1, &ir2);
let ir2 = align_decoder_floor(ir1, ir2);
let this_build_brygge_version = ir2.provenance.brygge_version.clone();
let brygge_versions_differ = ir1.provenance.brygge_version != this_build_brygge_version
|| ir1.provenance.decoder_version != ir2.provenance.decoder_version;
let ir2 = if brygge_versions_differ {
match ir2.restamped(
&ir1.provenance.brygge_version,
&ir1.provenance.decoder_version,
) {
Ok(r) => r,
Err(e) => {
return AgainstSourceOutcome::NotChecked(format!(
"could not compare across brygge versions: {e}"
));
}
}
} else {
ir2
};
let version_note =
|| brygge_version_note(&ir1.provenance.brygge_version, &this_build_brygge_version);
let version_detail =
|| brygge_version_detail(&ir1.provenance.brygge_version, &this_build_brygge_version);
if let Some(first) = ir1.transforms.first() {
return match brygge_ir::digest_of(&ir2) {
Ok(digest) => {
let rerun_note = format!(
"{} transform(s) after it were not re-run",
ir1.transforms.len()
);
if digest == first.consumed {
let mut note = rerun_note;
if brygge_versions_differ {
note = format!("{note}; {}", version_note());
}
if let Some(f) = &floor_differs {
note = format!("{note}; {f}");
}
if is_cvs {
AgainstSourceOutcome::RootReproduces(note)
} else {
AgainstSourceOutcome::RootCorresponds(note)
}
} else if brygge_versions_differ {
AgainstSourceOutcome::NotChecked(version_detail())
} else {
let detail = "the chain's root is not this source's decode".to_string();
if is_cvs {
AgainstSourceOutcome::DoesNotReproduce(detail)
} else {
AgainstSourceOutcome::DoesNotCorrespond(detail)
}
}
}
Err(e) => AgainstSourceOutcome::NotChecked(format!(
"could not compute the re-decode's own digest: {e}"
)),
};
}
let corresponds = ir1 == &ir2;
if !corresponds && brygge_versions_differ {
return AgainstSourceOutcome::NotChecked(version_detail());
}
let detail = || {
let d = divergence(ir1, &ir2);
match &versions_differ {
Some(v) => format!("{d} (svnadmin versions differ: {v})"),
None => d,
}
};
match (is_cvs, corresponds) {
(true, true) => AgainstSourceOutcome::Reproduces(combine_notes(vec![
brygge_versions_differ.then(version_note),
floor_differs.clone(),
])),
(true, false) => AgainstSourceOutcome::DoesNotReproduce(detail()),
(false, true) => {
let svn_note = versions_differ
.map(|v| format!("svnadmin versions differ ({v}); the history is identical"));
let note = combine_notes(vec![
brygge_versions_differ.then(version_note),
svn_note,
floor_differs.clone(),
]);
AgainstSourceOutcome::Corresponds(note)
}
(false, false) => AgainstSourceOutcome::DoesNotCorrespond(detail()),
}
}
fn brygge_version_note(a: &str, b: &str) -> String {
format!("decoded by brygge {a}, re-derived by {b}; the history is identical")
}
fn brygge_version_detail(a: &str, b: &str) -> String {
format!(
"decoded by brygge {a}; this build ({b}) decodes differently, which a newer decoder may do \
legitimately; run `verify --against-source` with brygge {a} for a definite answer"
)
}
fn svn_source_form_mismatch(ir1: &Ir, repo: &Path) -> Option<String> {
let recorded = ir1.provenance.params.get("source_form")?;
if matches!(std::fs::symlink_metadata(repo), Err(e) if e.kind() == std::io::ErrorKind::NotFound)
{
return None;
}
let given = if repo.is_file() {
"dumpfile"
} else {
"svnadmin-dump"
};
if recorded == given {
return None;
}
Some(format!(
"the artifact was made from a {recorded}; verify against the same form"
))
}
fn align_svnadmin_version(ir1: &Ir, mut ir2: Ir) -> Ir {
if let (Some(a), Some(_)) = (
ir1.provenance.params.get("svnadmin_version"),
ir2.provenance.params.get("svnadmin_version"),
) {
let a = a.clone();
ir2.provenance
.params
.insert("svnadmin_version".to_string(), a);
}
ir2
}
fn svn_version_note(ir1: &Ir, ir2: &Ir) -> Option<String> {
let a = ir1.provenance.params.get("svnadmin_version")?;
let b = ir2.provenance.params.get("svnadmin_version")?;
if a == b {
return None;
}
Some(format!("{a} vs {b}"))
}
fn align_decoder_floor(ir1: &Ir, mut ir2: Ir) -> Ir {
if let (Some(a), Some(_)) = (
ir1.provenance.params.get("floor"),
ir2.provenance.params.get("floor"),
) {
let a = a.clone();
ir2.provenance.params.insert("floor".to_string(), a);
}
ir2
}
fn decoder_floor_note(ir1: &Ir, ir2: &Ir) -> Option<String> {
let a = ir1.provenance.params.get("floor")?;
let b = ir2.provenance.params.get("floor")?;
if a == b {
return None;
}
let a_items: std::collections::BTreeSet<&str> =
a.split(',').filter(|s| !s.is_empty()).collect();
let b_items: std::collections::BTreeSet<&str> =
b.split(',').filter(|s| !s.is_empty()).collect();
let added: Vec<&str> = b_items.difference(&a_items).copied().collect();
let removed: Vec<&str> = a_items.difference(&b_items).copied().collect();
let name = |items: &[&str]| {
if items.is_empty() {
"none".to_string()
} else {
items.join(", ")
}
};
Some(format!(
"the decoder's floor changed between the two decodes: added {}; removed {}",
name(&added),
name(&removed)
))
}
fn combine_notes(parts: Vec<Option<String>>) -> Option<String> {
let present: Vec<String> = parts.into_iter().flatten().collect();
if present.is_empty() {
None
} else {
Some(present.join("; "))
}
}
#[derive(Debug)]
enum AgainstTargetOutcome {
Corresponds,
DoesNotCorrespond(Vec<String>),
NotChecked(String),
NotRun,
}
impl AgainstTargetOutcome {
fn machine_label(&self) -> &'static str {
match self {
Self::Corresponds => "corresponds",
Self::DoesNotCorrespond(_) => "does-not-correspond",
Self::NotChecked(_) => "not-checked",
Self::NotRun => "not-run",
}
}
fn human_label(&self) -> &'static str {
match self {
Self::Corresponds => "corresponds",
Self::DoesNotCorrespond(_) => "does not correspond",
Self::NotChecked(_) => "could not be checked",
Self::NotRun => "not run",
}
}
fn is_mismatch(&self) -> bool {
matches!(self, Self::DoesNotCorrespond(_))
}
fn is_not_checked(&self) -> bool {
matches!(self, Self::NotChecked(_))
}
}
fn list_git_refs(git: &Path, env: &GitEnv, repo: &Path) -> Result<Vec<encode_git::GitRef>, String> {
let mut cmd = Subprocess::new(git);
env.apply(&mut cmd);
cmd.current_dir(repo);
cmd.args(["for-each-ref", "--format=%(objectname) %(refname)"]);
cmd.stdin(Stdio::null()).stderr(Stdio::null());
let output = cmd
.output()
.map_err(|e| format!("cannot run git for-each-ref: {e}"))?;
if !output.status.success() {
return Err(format!(
"git for-each-ref failed (exit {:?})",
output.status.code()
));
}
let text = String::from_utf8(output.stdout)
.map_err(|_| "git for-each-ref printed non-UTF-8 output".to_string())?;
let mut refs = Vec::new();
for line in text.lines() {
let Some((oid_hex, name)) = line.split_once(' ') else {
continue;
};
let oid = hex20(oid_hex).ok_or_else(|| {
format!("git for-each-ref printed a malformed object id: {oid_hex:?}")
})?;
refs.push(encode_git::GitRef {
name: name.to_string(),
target: encode_git::GitRefTarget::Oid(oid),
});
}
let mut head_cmd = Subprocess::new(git);
env.apply(&mut head_cmd);
head_cmd.current_dir(repo);
head_cmd.args(["symbolic-ref", "--quiet", "HEAD"]);
head_cmd.stdin(Stdio::null()).stderr(Stdio::null());
let head_output = head_cmd
.output()
.map_err(|e| format!("cannot run git symbolic-ref: {e}"))?;
let head_target = if head_output.status.success() {
let name = String::from_utf8(head_output.stdout)
.map_err(|_| "git symbolic-ref printed non-UTF-8 output".to_string())?;
encode_git::GitRefTarget::Symbolic(name.trim().to_string())
} else {
let mut rev_cmd = Subprocess::new(git);
env.apply(&mut rev_cmd);
rev_cmd.current_dir(repo);
rev_cmd.args(["rev-parse", "--verify", "HEAD"]);
rev_cmd.stdin(Stdio::null()).stderr(Stdio::null());
let rev_output = rev_cmd
.output()
.map_err(|e| format!("cannot run git rev-parse: {e}"))?;
if rev_output.status.success() {
let hex_str = String::from_utf8(rev_output.stdout)
.map_err(|_| "git rev-parse printed non-UTF-8 output".to_string())?;
let oid = hex20(hex_str.trim())
.ok_or_else(|| "git rev-parse printed a malformed object id".to_string())?;
encode_git::GitRefTarget::Oid(oid)
} else {
return Err("HEAD names no ref and resolves to no commit (unborn)".to_string());
}
};
refs.push(encode_git::GitRef {
name: "HEAD".to_string(),
target: head_target,
});
Ok(refs)
}
fn hex20(s: &str) -> Option<Vec<u8>> {
if s.len() != 40 {
return None;
}
let bytes = s.as_bytes();
let mut out = Vec::with_capacity(20);
for pair in bytes.chunks_exact(2) {
let hi = (*pair.first()? as char).to_digit(16)?;
let lo = (*pair.get(1)? as char).to_digit(16)?;
out.push((hi * 16 + lo) as u8);
}
Some(out)
}
fn run_against_target(
ir: &Ir,
digest: &[u8; 32],
repo: &Path,
storage: &brygge_ir::Storage,
) -> AgainstTargetOutcome {
let Some(git) = plugin::find_tool("git") else {
return AgainstTargetOutcome::NotChecked("git is not on PATH".to_string());
};
let env = match GitEnv::new() {
Ok(e) => e,
Err(e) => {
return AgainstTargetOutcome::NotChecked(format!(
"cannot prepare git's environment: {e}"
));
}
};
let result_refs = match list_git_refs(&git, &env, repo) {
Ok(r) => r,
Err(e) => {
return AgainstTargetOutcome::NotChecked(format!(
"cannot list {}'s refs: {e}",
repo.display()
));
}
};
let opts = SourceOpts {
infer_renames: false,
reconstruct_refs: false,
branch_lines: false,
carry_extra_namespaces: vec![encode_git::OTHER_NAMESPACE.to_string()],
layout: LayoutPolicy::default(),
cvs_window: 0,
cvs_floor: 0,
};
let result_ir = match decode_source(SourceKind::Git, repo, &opts, storage) {
Ok(ir) => ir,
Err((_, msg)) => {
return AgainstTargetOutcome::NotChecked(format!(
"cannot decode {}: {msg}",
repo.display()
));
}
};
let default_branch_ref = format!("refs/heads/{}", encode_git::choose_default_branch(ir).name);
match encode_git::compare_git_target(ir, digest, &result_ir, &result_refs, &default_branch_ref)
{
encode_git::Comparison::Corresponds => AgainstTargetOutcome::Corresponds,
encode_git::Comparison::DoesNotCorrespond(diffs) => {
AgainstTargetOutcome::DoesNotCorrespond(diffs)
}
encode_git::Comparison::NotChecked(reason) => AgainstTargetOutcome::NotChecked(reason),
}
}
fn divergence(a: &Ir, b: &Ir) -> String {
if a.atoms.len() != b.atoms.len() {
return format!(
"atom count differs: artifact {} vs source {}",
a.atoms.len(),
b.atoms.len()
);
}
for (x, y) in a.atoms.iter().zip(b.atoms.iter()) {
if x != y {
return format!(
"first divergence at source atom {}",
short_hex(&x.source.atom_id)
);
}
}
if a.refs != b.refs {
return "refs differ".to_string();
}
if a.content != b.content {
return "content store differs".to_string();
}
"provenance or loss boundary differs".to_string()
}
const CHECK_NAMES: [&str; 7] = [
"integrity",
"structure",
"replay",
"derivations",
"source-invariants",
"provenance",
"loss-boundary",
];
enum Verdict {
Pass,
Fail,
Incomplete,
}
impl Verdict {
fn from(
internal_pass: bool,
against: &AgainstSourceOutcome,
against_target: &AgainstTargetOutcome,
) -> Self {
if !internal_pass || against.is_mismatch() || against_target.is_mismatch() {
Self::Fail
} else if against.is_not_checked() || against_target.is_not_checked() {
Self::Incomplete
} else {
Self::Pass
}
}
fn machine_label(&self) -> &'static str {
match self {
Self::Pass => "pass",
Self::Fail => "fail",
Self::Incomplete => "incomplete",
}
}
fn human_line(&self) -> &'static str {
match self {
Self::Pass => " => PASS",
Self::Fail => " => FAIL",
Self::Incomplete => " => INCOMPLETE (a requested check could not run)",
}
}
fn exit_code(&self) -> i32 {
match self {
Self::Pass => exit::CLEAN,
Self::Fail => exit::VERIFY_FAILED,
Self::Incomplete => exit::FAILURE,
}
}
}
fn compute_internal_checks(
parsed: &Result<Decoded, brygge_ir::Error>,
) -> (Vec<(&'static str, CheckOutcome)>, bool) {
let mut checks: Vec<(&'static str, CheckOutcome)> = Vec::with_capacity(CHECK_NAMES.len());
let ir_opt = match parsed {
Ok(decoded) => {
checks.push(("integrity", CheckOutcome::Pass));
Some(&decoded.ir)
}
Err(e) => {
checks.push(("integrity", CheckOutcome::Fail(e.to_string())));
None
}
};
if let Some(ir) = ir_opt {
checks.push(("structure", check_structure(ir)));
checks.push(("replay", check_replay(ir)));
checks.push(("derivations", check_derivations(ir)));
checks.push(("source-invariants", check_source_invariants(ir)));
checks.push(("provenance", check_provenance(ir)));
checks.push(("loss-boundary", check_loss_boundary(ir)));
} else {
for name in &CHECK_NAMES[1..] {
checks.push((
name,
CheckOutcome::NotChecked(
"the artifact failed to decode; this check cannot run".to_string(),
),
));
}
}
let internal_pass = !checks.iter().any(|(_, o)| o.is_fail());
(checks, internal_pass)
}
pub(crate) fn verify_internal_report(artifact: &Path, format: Format) -> (String, i32) {
let parsed = brygge_ir::from_file(artifact);
if let Err(brygge_ir::Error::Io(msg)) = &parsed {
return (
format!("cannot read {}: {msg}\n", artifact.display()),
exit::FAILURE,
);
}
let (checks, internal_pass) = compute_internal_checks(&parsed);
let against = AgainstSourceOutcome::NotRun;
let against_target = AgainstTargetOutcome::NotRun;
let verdict = Verdict::from(internal_pass, &against, &against_target);
let skipped = parsed
.as_ref()
.map_or(0, |decoded| decoded.skipped_non_critical_fields);
let rendered = format_verify_report(
format,
&checks,
internal_pass,
&against,
&against_target,
&verdict,
skipped,
);
(rendered, verdict.exit_code())
}
pub fn run_verify(
artifact: &Path,
against_source: Option<&Path>,
against_target: Option<&Path>,
spill_dir: Option<&Path>,
format: Format,
) -> i32 {
let storage = if against_source.is_some() || against_target.is_some() {
let dir = match spill_dir {
Some(dir) => {
if !dir.is_dir() {
output::stderr(&format!(
"--spill-dir {} does not exist or is not a directory",
dir.display()
));
return exit::USAGE;
}
dir.to_path_buf()
}
None => artifact
.parent()
.filter(|p| !p.as_os_str().is_empty())
.unwrap_or_else(|| Path::new("."))
.to_path_buf(),
};
Some(brygge_ir::Storage::Spill(dir))
} else {
None
};
let parsed = brygge_ir::from_file(artifact);
if let Err(brygge_ir::Error::Io(msg)) = &parsed {
output::stderr(&format!("cannot read {}: {msg}", artifact.display()));
return exit::FAILURE;
}
let (checks, internal_pass) = compute_internal_checks(&parsed);
let ir_opt = parsed.as_ref().ok().map(|decoded| &decoded.ir);
let against = match (against_source, ir_opt, &storage) {
(Some(src), Some(ir), Some(storage)) => run_against_source(ir, src, storage),
(Some(_), None, _) => AgainstSourceOutcome::NotChecked(
"the artifact failed to decode; there is nothing to re-derive against".to_string(),
),
(None, _, _) => AgainstSourceOutcome::NotRun,
(Some(_), Some(_), None) => unreachable!("storage is set whenever against_source is"),
};
let against_target = match (against_target, ir_opt, &storage) {
(Some(repo), Some(ir), Some(storage)) => {
#[allow(clippy::expect_used)]
let digest = parsed
.as_ref()
.expect("ir_opt is Some only when parsed is Ok")
.digest;
run_against_target(ir, &digest, repo, storage)
}
(Some(_), None, _) => AgainstTargetOutcome::NotChecked(
"the artifact failed to decode; there is nothing to check against a repository"
.to_string(),
),
(None, _, _) => AgainstTargetOutcome::NotRun,
(Some(_), Some(_), None) => unreachable!("storage is set whenever against_target is"),
};
let verdict = Verdict::from(internal_pass, &against, &against_target);
let skipped = parsed
.as_ref()
.map_or(0, |decoded| decoded.skipped_non_critical_fields);
if let Some(code) = render_verify(
format,
&checks,
internal_pass,
&against,
&against_target,
&verdict,
skipped,
) {
return code;
}
verdict.exit_code()
}
fn check_key(name: &str) -> String {
name.replace('-', "_")
}
fn verify_machine_lines(
checks: &[(&'static str, CheckOutcome)],
internal_pass: bool,
against: &AgainstSourceOutcome,
against_target: &AgainstTargetOutcome,
verdict: &Verdict,
skipped_non_critical_fields: u64,
) -> Vec<String> {
let mut out = vec![
format!("verify_version={VERIFY_VERSION}"),
format!("verify.skipped_non_critical_fields={skipped_non_critical_fields}"),
];
for (name, outcome) in checks {
let key = check_key(name);
out.push(format!("verify.check.{key}={}", outcome.label()));
if let Some(d) = outcome.detail() {
out.push(format!(
"verify.check.{key}.detail={}",
display::machine_value(d)
));
}
}
out.push("verify.authorship=unverifiable".to_string());
out.push(format!(
"verify.internal={}",
if internal_pass { "pass" } else { "fail" }
));
out.push(format!("verify.against_source={}", against.machine_label()));
if let Some(d) = against.detail() {
out.push(format!(
"verify.against_source.detail={}",
display::machine_value(d)
));
}
if let Some(n) = against.note() {
out.push(format!(
"verify.against_source.note={}",
display::machine_value(n)
));
}
out.push(format!(
"verify.against_target={}",
against_target.machine_label()
));
if let AgainstTargetOutcome::NotChecked(d) = against_target {
out.push(format!(
"verify.against_target.detail={}",
display::machine_value(d)
));
}
if let AgainstTargetOutcome::DoesNotCorrespond(diffs) = against_target {
out.push(format!(
"verify.against_target.detail={}",
display::machine_value(&target_diff_summary(diffs))
));
}
out.push(format!("verify.result={}", verdict.machine_label()));
out
}
fn target_diff_summary(diffs: &[String]) -> String {
const SHOWN: usize = 20;
let Some(shown) = diffs.get(..SHOWN) else {
return diffs.join("; ");
};
format!("{}; and {} more", shown.join("; "), diffs.len() - SHOWN)
}
fn render_verify(
format: Format,
checks: &[(&'static str, CheckOutcome)],
internal_pass: bool,
against: &AgainstSourceOutcome,
against_target: &AgainstTargetOutcome,
verdict: &Verdict,
skipped_non_critical_fields: u64,
) -> Option<i32> {
let rendered = format_verify_report(
format,
checks,
internal_pass,
against,
against_target,
verdict,
skipped_non_critical_fields,
);
output::stdout(&rendered)
}
fn format_verify_report(
format: Format,
checks: &[(&'static str, CheckOutcome)],
internal_pass: bool,
against: &AgainstSourceOutcome,
against_target: &AgainstTargetOutcome,
verdict: &Verdict,
skipped_non_critical_fields: u64,
) -> String {
let mut s = String::new();
match format {
Format::Machine => {
for line in verify_machine_lines(
checks,
internal_pass,
against,
against_target,
verdict,
skipped_non_critical_fields,
) {
let _ = writeln!(s, "{line}");
}
}
Format::Human => {
let _ = writeln!(
s,
"verify — the honesty checks any reader can run with no source (always run):"
);
for (name, outcome) in checks {
let mark = match outcome {
CheckOutcome::Pass => "ok",
CheckOutcome::Fail(_) => "FAIL",
CheckOutcome::NotChecked(_) => "not-checked",
};
let _ = writeln!(s, " [{mark}] {name}");
if let Some(d) = outcome.detail() {
let _ = writeln!(s, " {}", display::human(d));
}
}
let _ = writeln!(
s,
" authorship: Unverifiable by construction (no IR field can express target \
verification)"
);
let _ = writeln!(
s,
" internal: {}",
if internal_pass { "pass" } else { "fail" }
);
if let AgainstSourceOutcome::NotChecked(reason) = against {
let _ = writeln!(
s,
" against-source: could not be checked ({})",
display::human(reason)
);
} else if !matches!(against, AgainstSourceOutcome::NotRun) {
let _ = writeln!(s, " against-source: {}", against.human_label());
if let Some(d) = against.detail().or_else(|| against.note()) {
let _ = writeln!(s, " {}", display::human(d));
}
}
match against_target {
AgainstTargetOutcome::NotRun => {}
AgainstTargetOutcome::NotChecked(reason) => {
let _ = writeln!(
s,
" against-target: could not be checked ({})",
display::human(reason)
);
}
AgainstTargetOutcome::Corresponds => {
let _ = writeln!(s, " against-target: {}", against_target.human_label());
}
AgainstTargetOutcome::DoesNotCorrespond(diffs) => {
let _ = writeln!(s, " against-target: {}", against_target.human_label());
let _ = writeln!(s, " {}", display::human(&target_diff_summary(diffs)));
}
}
let _ = writeln!(s, "{}", verdict.human_line());
}
}
s
}
const ENCODE_LIST_VERSION: u32 = 2;
const ENCODE_VERSION: u32 = 1;
const ENCODE_GIT_VERSION: u32 = 2;
pub fn run_encode_list(format: Format) -> i32 {
let plugins = plugin::list(plugin::Kind::Encode);
let rendered = match format {
Format::Human => render_encode_list_human(&plugins),
Format::Machine => render_encode_list_machine(&plugins),
};
if let Some(code) = output::stdout(&rendered) {
return code;
}
exit::CLEAN
}
fn render_encode_list_human(plugins: &[plugin::Listed]) -> String {
let mut s = String::new();
if plugins.is_empty() {
let _ = writeln!(s, "no brygge-encode-* plugins found on PATH");
return s;
}
for p in plugins {
let _ = write!(s, "{} {}", p.name, p.path.display());
if p.name == GIT_TARGET {
let _ = write!(s, " (shadowed by the built-in)");
} else if p.shadowed {
let _ = write!(s, " (shadowed)");
}
let _ = writeln!(s);
}
s
}
fn render_encode_list_machine(plugins: &[plugin::Listed]) -> String {
let mut s = String::new();
let _ = writeln!(s, "encode_list_version={ENCODE_LIST_VERSION}");
for (i, p) in plugins.iter().enumerate() {
let _ = writeln!(s, "encoder.{i}.target={}", display::machine_value(&p.name));
let _ = writeln!(
s,
"encoder.{i}.path={}",
display::machine_value(&p.path.display().to_string())
);
let _ = writeln!(
s,
"encoder.{i}.shadowed={}",
p.shadowed || p.name == GIT_TARGET
);
if p.name == GIT_TARGET {
let _ = writeln!(s, "encoder.{i}.shadowed_by=built_in");
}
}
s
}
fn encode_banner_text(format: Format, target: &str, path: &Path) -> String {
match format {
Format::Human => format!(
"encoding with the external plugin `brygge-encode-{target}` (`{}`): not part of brygge; \
brygge verified the artifact, not the plugin's output",
path.display()
),
Format::Machine => format!(
"encode_version={ENCODE_VERSION}\nencode.target={}\nencode.plugin_path={}\n\
encode.banner=not_part_of_brygge",
display::machine_value(target),
display::machine_value(&path.display().to_string()),
),
}
}
fn encode_exit_text(format: Format, target: &str, code: i32) -> String {
match format {
Format::Human => format!("`brygge-encode-{target}` exited with {code}"),
Format::Machine => format!("encode.exit_code={code}"),
}
}
fn encode_signal_text(format: Format, target: &str, signal: i32) -> String {
match format {
Format::Human => match plugin::signal_name(signal) {
Some(name) => {
format!("`brygge-encode-{target}` was killed by signal {signal} ({name})")
}
None => format!("`brygge-encode-{target}` was killed by signal {signal}"),
},
Format::Machine => format!("encode.signal={signal}"),
}
}
pub fn run_encode(target: &str, artifact: &Path, plugin_args: &[String], format: Format) -> i32 {
let Some(path) = plugin::find(plugin::Kind::Encode, target) else {
output::stderr(&format!(
"no encoder for '{target}': brygge-encode-{target} is not on PATH (see `brygge encode \
--list`)"
));
return exit::USAGE;
};
let (report, code) = verify_internal_report(artifact, format);
if code != exit::CLEAN {
output::stderr(&report);
return code;
}
output::stderr(&encode_banner_text(format, target, &path));
let mut argv: Vec<std::ffi::OsString> =
vec!["--artifact".into(), artifact.as_os_str().to_os_string()];
argv.extend(plugin_args.iter().map(std::ffi::OsString::from));
match plugin::run(&path, &argv) {
plugin::Ran::Exited(code) => {
output::stderr(&encode_exit_text(format, target, code));
code
}
plugin::Ran::Signaled(signal) => {
output::stderr(&encode_signal_text(format, target, signal));
exit::FAILURE
}
plugin::Ran::CannotStart(e) => {
output::stderr(&format!(
"cannot start brygge-encode-{target} ({}): {e}",
path.display()
));
exit::FAILURE
}
}
}
fn unique_temp_path(label: &str, attempt: u32) -> PathBuf {
let pid = std::process::id();
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0);
std::env::temp_dir().join(format!("brygge-encode-git-{label}-{pid}-{nanos}-{attempt}"))
}
struct GitEnv {
home: PathBuf,
global_config: PathBuf,
}
impl GitEnv {
fn new() -> std::io::Result<Self> {
const MAX_ATTEMPTS: u32 = 64;
let mut home = None;
for attempt in 0..MAX_ATTEMPTS {
let p = unique_temp_path("home", attempt);
match std::fs::create_dir(&p) {
Ok(()) => {
home = Some(p);
break;
}
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(e) => return Err(e),
}
}
let home = home.ok_or_else(|| std::io::Error::other("could not create a temp HOME"))?;
let mut global_config = None;
for attempt in 0..MAX_ATTEMPTS {
let p = unique_temp_path("gitconfig", attempt);
match std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&p)
{
Ok(_) => {
global_config = Some(p);
break;
}
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(e) => {
let _ = std::fs::remove_dir_all(&home);
return Err(e);
}
}
}
let Some(global_config) = global_config else {
let _ = std::fs::remove_dir_all(&home);
return Err(std::io::Error::other(
"could not create a temp GIT_CONFIG_GLOBAL file",
));
};
Ok(Self {
home,
global_config,
})
}
fn apply(&self, cmd: &mut Subprocess) {
cmd.env_clear();
if let Some(path) = std::env::var_os("PATH") {
cmd.env("PATH", path);
}
cmd.env("HOME", &self.home);
cmd.env("GIT_CONFIG_NOSYSTEM", "1");
cmd.env("GIT_CONFIG_GLOBAL", &self.global_config);
cmd.env("LC_ALL", "C");
if cfg!(windows) {
if let Some(system_root) = std::env::var_os("SystemRoot") {
cmd.env("SystemRoot", system_root);
}
}
}
}
impl Drop for GitEnv {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.home);
let _ = std::fs::remove_file(&self.global_config);
}
}
fn check_ref_format(git: &Path, env: &GitEnv, git_ref: &str) -> Result<(), String> {
let mut cmd = Subprocess::new(git);
env.apply(&mut cmd);
cmd.args(["check-ref-format", git_ref]);
cmd.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null());
match cmd.status() {
Ok(status) if status.success() => Ok(()),
Ok(status) => Err(format!(
"git check-ref-format rejected it (exit {})",
status.code().map_or("?".to_string(), |c| c.to_string())
)),
Err(e) => Err(format!("cannot run git check-ref-format: {e}")),
}
}
fn encode_git_preflight(ir: &Ir, git: &Path, env: &GitEnv) -> Vec<encode_git::Refusal> {
let mut refusals = encode_git::preflight(ir);
let mut checked: BTreeSet<String> = BTreeSet::new();
for rf in &ir.refs {
let path = encode_git::git_ref_path(rf);
if !checked.insert(path.clone()) {
continue;
}
if let Err(reason) = check_ref_format(git, env, &path) {
refusals.push(encode_git::Refusal::InvalidRefName {
git_ref: path,
reason,
});
}
}
refusals
}
fn render_encode_git_refusals(format: Format, refusals: &[encode_git::Refusal]) -> String {
match format {
Format::Human => {
let mut s = String::new();
let _ = writeln!(s, "the artifact cannot be written as Git:");
for r in refusals {
let _ = writeln!(s, " {}", display::human(&r.to_string()));
}
s
}
Format::Machine => {
let mut s = String::new();
let _ = writeln!(s, "encode_git_version={ENCODE_GIT_VERSION}");
for (i, r) in refusals.iter().enumerate() {
let _ = writeln!(
s,
"encode_git.refusal.{i}={}",
display::machine_value(&r.to_string())
);
}
s
}
}
}
fn render_encode_git_report(
digest: &[u8; 32],
default_branch: &encode_git::DefaultBranch,
summary: &encode_git::Summary,
fidelity: &brygge_ir::honesty::FidelityReport,
) -> String {
let mut s = String::new();
let _ = writeln!(s, "encode_git_version={ENCODE_GIT_VERSION}");
let _ = writeln!(s, "encode_git.artifact_digest=sha256:{}", hex(digest));
let _ = writeln!(s, "encode_git.brygge_version={}", env!("CARGO_PKG_VERSION"));
let _ = writeln!(
s,
"encode_git.default_branch={}",
display::machine_value(&default_branch.name)
);
let _ = writeln!(
s,
"encode_git.default_branch_existed={}",
default_branch.existed
);
let _ = writeln!(s, "encode_git.commits={}", summary.commits);
let _ = writeln!(s, "encode_git.tags={}", summary.tags);
let _ = writeln!(s, "encode_git.refs={}", summary.refs);
let _ = writeln!(s, "encode_git.check=corresponds");
for (class, count) in &fidelity.dropped {
let _ = writeln!(s, "encode_git.dropped.{}={count}", key_segment(class));
}
for (kind, count) in &fidelity.flagged {
let _ = writeln!(s, "encode_git.flagged.{}={count}", key_segment(kind));
}
for (field, count) in &summary.supplied {
let _ = writeln!(s, "encode_git.supplied.{}={count}", key_segment(field));
}
for (field, count) in &summary.altered {
let _ = writeln!(s, "encode_git.altered.{}={count}", key_segment(field));
}
for (i, line) in summary.unplaced_ref_transforms.iter().enumerate() {
let _ = writeln!(
s,
"encode_git.unplaced_ref_transform.{i}={}",
display::machine_value(line)
);
}
s
}
fn key_segment(label: &str) -> String {
label.replace('-', "_")
}
pub fn run_encode_git(artifact: &Path, out: &Path, format: Format) -> i32 {
run_encode_git_with_check(artifact, out, format, real_encode_git_check)
}
fn real_encode_git_check(
ir: &Ir,
digest: &[u8; 32],
partial: &Path,
git: &Path,
env: &GitEnv,
default_branch_ref: &str,
) -> encode_git::Comparison {
let result_refs = match list_git_refs(git, env, partial) {
Ok(r) => r,
Err(e) => {
return encode_git::Comparison::NotChecked(format!(
"cannot list the result's refs: {e}"
));
}
};
let spill_dir = match encode_git_check_spill_dir() {
Ok(d) => d,
Err(e) => {
return encode_git::Comparison::NotChecked(format!(
"cannot prepare a spill directory for the check: {e}"
));
}
};
let opts = SourceOpts {
infer_renames: false,
reconstruct_refs: false,
branch_lines: false,
carry_extra_namespaces: vec![encode_git::OTHER_NAMESPACE.to_string()],
layout: LayoutPolicy::default(),
cvs_window: 0,
cvs_floor: 0,
};
let storage = brygge_ir::Storage::Spill(spill_dir.clone());
let result = decode_source(SourceKind::Git, partial, &opts, &storage);
let _ = std::fs::remove_dir_all(&spill_dir);
let result_ir = match result {
Ok(ir) => ir,
Err((_, msg)) => {
return encode_git::Comparison::NotChecked(format!(
"cannot decode the result for the check: {msg}"
));
}
};
encode_git::compare_git_target(ir, digest, &result_ir, &result_refs, default_branch_ref)
}
fn encode_git_check_spill_dir() -> std::io::Result<PathBuf> {
const MAX_ATTEMPTS: u32 = 64;
for attempt in 0..MAX_ATTEMPTS {
let p = unique_temp_path("check-spill", attempt);
match std::fs::create_dir(&p) {
Ok(()) => return Ok(p),
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(e) => return Err(e),
}
}
Err(std::io::Error::other(
"could not create a temp spill directory",
))
}
fn run_encode_git_with_check(
artifact: &Path,
out: &Path,
format: Format,
check: impl Fn(&Ir, &[u8; 32], &Path, &Path, &GitEnv, &str) -> encode_git::Comparison,
) -> i32 {
if out.symlink_metadata().is_ok() {
output::stderr(&format!(
"{} already exists; encode git refuses to overwrite it",
out.display()
));
return exit::USAGE;
}
let report_path = {
let mut p = out.as_os_str().to_os_string();
p.push(".brygge-report");
PathBuf::from(p)
};
if report_path.symlink_metadata().is_ok() {
output::stderr(&format!(
"{} already exists; encode git refuses to overwrite it",
report_path.display()
));
return exit::USAGE;
}
let (report, code) = verify_internal_report(artifact, format);
if code != exit::CLEAN {
output::stderr(&report);
return code;
}
let decoded = match brygge_ir::from_file(artifact) {
Ok(d) => d,
Err(e) => {
output::stderr(&display::human(&format!(
"cannot read {}: {e}",
artifact.display()
)));
return exit::FAILURE;
}
};
let ir = &decoded.ir;
let Some(git) = plugin::find_tool("git") else {
output::stderr("git is not on PATH: brygge encode git needs it (RFC 019 D-1)");
return exit::FAILURE;
};
let env = match GitEnv::new() {
Ok(e) => e,
Err(e) => {
output::stderr(&format!("cannot prepare git's environment: {e}"));
return exit::FAILURE;
}
};
let refusals = encode_git_preflight(ir, &git, &env);
if !refusals.is_empty() {
output::stderr(&render_encode_git_refusals(format, &refusals));
return exit::USAGE;
}
let default_branch = encode_git::choose_default_branch(ir);
let parent = out.parent().filter(|p| !p.as_os_str().is_empty());
let partial = {
let out_name = out.file_name().map_or_else(
|| "encode-git".to_string(),
|n| n.to_string_lossy().into_owned(),
);
let pid = std::process::id();
let mut p = None;
for attempt in 0..64u32 {
let base_name = format!("{out_name}.partial-{pid}-{attempt}");
let candidate =
parent.map_or_else(|| PathBuf::from(&base_name), |d| d.join(&base_name));
match std::fs::create_dir(&candidate) {
Ok(()) => {
p = Some(candidate);
break;
}
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(e) => {
output::stderr(&format!(
"cannot create a working directory beside {}: {e}",
out.display()
));
return exit::FAILURE;
}
}
}
match p {
Some(p) => p,
None => {
output::stderr("cannot create a working directory: too many attempts");
return exit::FAILURE;
}
}
};
let cleanup = |partial: &Path| {
let _ = std::fs::remove_dir_all(partial);
};
let mut init = Subprocess::new(&git);
env.apply(&mut init);
init.current_dir(&partial);
init.args([
"init",
"--quiet",
"--bare",
&format!("--initial-branch={}", default_branch.name),
]);
match init.status() {
Ok(status) if status.success() => {}
Ok(status) => {
cleanup(&partial);
output::stderr(&format!("git init failed (exit {:?})", status.code()));
return exit::FAILURE;
}
Err(e) => {
cleanup(&partial);
output::stderr(&format!("cannot start git: {e}"));
return exit::FAILURE;
}
}
let mut import = Subprocess::new(&git);
env.apply(&mut import);
import.current_dir(&partial);
import.args(["fast-import", "--quiet", "--done"]);
import.stdin(Stdio::piped());
let mut child = match import.spawn() {
Ok(c) => c,
Err(e) => {
cleanup(&partial);
output::stderr(&format!("cannot start git fast-import: {e}"));
return exit::FAILURE;
}
};
let summary = {
#[allow(clippy::expect_used)]
let mut stdin = child
.stdin
.take()
.expect("stdin was requested with Stdio::piped()");
let write_result = encode_git::write_stream(ir, &decoded.digest, &mut stdin);
drop(stdin);
write_result
};
let status = child.wait();
let summary = match (summary, status) {
(Ok(summary), Ok(status)) if status.success() => summary,
(Ok(_), Ok(status)) => {
cleanup(&partial);
output::stderr(&format!(
"git fast-import failed (exit {:?})",
status.code()
));
return exit::FAILURE;
}
(Err(e), _) => {
cleanup(&partial);
output::stderr(&format!("writing the fast-import stream failed: {e}"));
return exit::FAILURE;
}
(Ok(_), Err(e)) => {
cleanup(&partial);
output::stderr(&format!("cannot wait for git fast-import: {e}"));
return exit::FAILURE;
}
};
let default_branch_ref = format!("refs/heads/{}", default_branch.name);
match check(
ir,
&decoded.digest,
&partial,
&git,
&env,
&default_branch_ref,
) {
encode_git::Comparison::Corresponds => {}
encode_git::Comparison::DoesNotCorrespond(diffs) => {
cleanup(&partial);
output::stderr(&format!(
"the result does not match the artifact; refusing to write {}:",
out.display()
));
const SHOWN: usize = 20;
for d in diffs.iter().take(SHOWN) {
output::stderr(&format!(" {}", display::human(d)));
}
if diffs.len() > SHOWN {
output::stderr(&format!(" …and {} more", diffs.len() - SHOWN));
}
return exit::FAILURE;
}
encode_git::Comparison::NotChecked(reason) => {
cleanup(&partial);
output::stderr(&format!(
"the result could not be checked against the artifact: {reason}"
));
return exit::FAILURE;
}
}
let fidelity = brygge_ir::honesty::summary(ir);
let report_text =
render_encode_git_report(&decoded.digest, &default_branch, &summary, &fidelity);
let report_dir = report_path
.parent()
.filter(|p| !p.as_os_str().is_empty())
.unwrap_or_else(|| Path::new("."));
let report_tmp = {
let report_name = report_path.file_name().map_or_else(
|| "brygge-report".to_string(),
|n| n.to_string_lossy().into_owned(),
);
let pid = std::process::id();
let mut p = None;
for attempt in 0..64u32 {
let candidate = report_dir.join(format!("{report_name}.partial-{pid}-{attempt}"));
match std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&candidate)
.and_then(|mut f| f.write_all(report_text.as_bytes()).map(|()| f))
{
Ok(_) => {
p = Some(candidate);
break;
}
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(e) => {
cleanup(&partial);
let _ = std::fs::remove_file(&candidate);
output::stderr(&format!(
"cannot write a temporary report beside {}: {e}",
report_path.display()
));
return exit::FAILURE;
}
}
}
match p {
Some(p) => p,
None => {
cleanup(&partial);
output::stderr("cannot write a temporary report: too many attempts");
return exit::FAILURE;
}
}
};
if let Err(e) = std::fs::rename(&partial, out) {
cleanup(&partial);
let _ = std::fs::remove_file(&report_tmp);
output::stderr(&format!("cannot write {}: {e}", out.display()));
return exit::FAILURE;
}
if let Err(e) = std::fs::rename(&report_tmp, &report_path) {
let _ = std::fs::remove_file(&report_tmp);
output::stderr(&format!(
"the repository was written at {}, but its report could not be put at {}: {e}",
out.display(),
report_path.display()
));
return exit::FAILURE;
}
output::stderr(&format!(
"wrote {} ({} commit(s), {} tag(s), {} ref(s) total; default branch {}{})",
out.display(),
summary.commits,
summary.tags,
summary.refs,
default_branch.name,
if default_branch.existed {
""
} else {
", which has no commits"
}
));
fidelity_exit_class(ir)
}
const TRANSFORM_LIST_VERSION: u32 = 2;
const TRANSFORM_VERSION: u32 = 1;
const TRANSFORM_AUTHORS_VERSION: u32 = 1;
pub fn run_transform_list(format: Format) -> i32 {
let plugins = plugin::list(plugin::Kind::Transform);
let rendered = match format {
Format::Human => render_transform_list_human(&plugins),
Format::Machine => render_transform_list_machine(&plugins),
};
if let Some(code) = output::stdout(&rendered) {
return code;
}
exit::CLEAN
}
fn render_transform_list_human(plugins: &[plugin::Listed]) -> String {
let mut s = String::new();
if plugins.is_empty() {
let _ = writeln!(s, "no brygge-transform-* plugins found on PATH");
return s;
}
for p in plugins {
let _ = write!(s, "{} {}", p.name, p.path.display());
if p.name == AUTHORS_TRANSFORM {
let _ = write!(s, " (shadowed by the built-in)");
} else if p.shadowed {
let _ = write!(s, " (shadowed)");
}
let _ = writeln!(s);
}
s
}
fn render_transform_list_machine(plugins: &[plugin::Listed]) -> String {
let mut s = String::new();
let _ = writeln!(s, "transform_list_version={TRANSFORM_LIST_VERSION}");
for (i, p) in plugins.iter().enumerate() {
let _ = writeln!(
s,
"transformer.{i}.name={}",
display::machine_value(&p.name)
);
let _ = writeln!(
s,
"transformer.{i}.path={}",
display::machine_value(&p.path.display().to_string())
);
let _ = writeln!(
s,
"transformer.{i}.shadowed={}",
p.shadowed || p.name == AUTHORS_TRANSFORM
);
if p.name == AUTHORS_TRANSFORM {
let _ = writeln!(s, "transformer.{i}.shadowed_by=built_in");
}
}
s
}
fn same_file_as(a: &Path, b: &Path) -> bool {
match (std::fs::canonicalize(a), std::fs::canonicalize(b)) {
(Ok(ca), Ok(cb)) => ca == cb,
_ => a == b,
}
}
fn create_transform_temp(dir: &Path) -> std::io::Result<std::path::PathBuf> {
let pid = std::process::id();
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0);
const MAX_ATTEMPTS: u32 = 64;
let mut last_err: Option<std::io::Error> = None;
for attempt in 0..MAX_ATTEMPTS {
let path = dir.join(format!(".brygge-transform-{pid}-{nanos}-{attempt}"));
let opened = open_transform_temp(&path);
match opened {
Ok(()) => return Ok(path),
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => last_err = Some(e),
Err(e) => return Err(e),
}
}
Err(last_err.unwrap_or_else(|| std::io::Error::other("could not create a temp file")))
}
#[cfg(unix)]
fn open_transform_temp(path: &Path) -> std::io::Result<()> {
use std::os::unix::fs::OpenOptionsExt;
std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.mode(0o600)
.open(path)
.map(|_| ())
}
#[cfg(not(unix))]
fn open_transform_temp(path: &Path) -> std::io::Result<()> {
std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(path)
.map(|_| ())
}
fn transform_banner_text(format: Format, name: &str, path: &Path) -> String {
match format {
Format::Human => format!(
"transforming with the external plugin `brygge-transform-{name}` (`{}`): not part of \
brygge; brygge verified the input artifact, and will check the plugin's own output before \
accepting it",
path.display()
),
Format::Machine => format!(
"transform_version={TRANSFORM_VERSION}\ntransform.name={}\ntransform.plugin_path={}\n\
transform.banner=not_part_of_brygge",
display::machine_value(name),
display::machine_value(&path.display().to_string()),
),
}
}
fn transform_exit_text(format: Format, name: &str, code: i32) -> String {
match format {
Format::Human => format!("`brygge-transform-{name}` exited with {code}"),
Format::Machine => format!("transform.exit_code={code}"),
}
}
fn transform_signal_text(format: Format, name: &str, signal: i32) -> String {
match format {
Format::Human => match plugin::signal_name(signal) {
Some(n) => format!("`brygge-transform-{name}` was killed by signal {signal} ({n})"),
None => format!("`brygge-transform-{name}` was killed by signal {signal}"),
},
Format::Machine => format!("transform.signal={signal}"),
}
}
fn transform_result_text(format: Format, summary: &brygge_ir::transform::StepSummary) -> String {
match format {
Format::Human => format!(
"step {}: {} atom(s) changed, {} op(s) changed, {} ref(s) changed, {} dropped",
summary.step,
summary.atoms_changed,
summary.ops_changed,
summary.refs_changed,
summary.dropped
),
Format::Machine => format!(
"transform.step={}\ntransform.atoms_changed={}\ntransform.ops_changed={}\n\
transform.refs_changed={}\ntransform.dropped={}",
summary.step,
summary.atoms_changed,
summary.ops_changed,
summary.refs_changed,
summary.dropped
),
}
}
pub fn run_transform(
name: &str,
artifact: &Path,
out: &Path,
plugin_args: &[String],
format: Format,
) -> i32 {
if same_file_as(out, artifact) {
output::stderr("--out must not be the same file as <artifact>");
return exit::USAGE;
}
let Some(path) = plugin::find(plugin::Kind::Transform, name) else {
output::stderr(&format!(
"no transform for '{name}': brygge-transform-{name} is not on PATH (see `brygge transform \
--list`)"
));
return exit::USAGE;
};
let (report, code) = verify_internal_report(artifact, format);
if code != exit::CLEAN {
output::stderr(&report);
return code;
}
let input = match brygge_ir::from_file(artifact) {
Ok(d) => d,
Err(e) => {
output::stderr(&display::human(&format!(
"cannot read {}: {e}",
artifact.display()
)));
return exit::FAILURE;
}
};
if let Some(dup) = brygge_ir::transform::duplicate_source_identity(&input) {
output::stderr(&display::human(&format!(
"refused: the input has two atoms with the same source identity ({dup:?}) — a transform \
cannot match atoms by it at all"
)));
return exit::VERIFY_FAILED;
}
output::stderr(&transform_banner_text(format, name, &path));
let dir = out
.parent()
.filter(|p| !p.as_os_str().is_empty())
.unwrap_or_else(|| Path::new("."));
let tmp = match create_transform_temp(dir) {
Ok(p) => p,
Err(e) => {
output::stderr(&format!(
"cannot create a temp file in {}: {e}",
dir.display()
));
return exit::FAILURE;
}
};
let mut argv: Vec<std::ffi::OsString> = vec![
"--artifact".into(),
artifact.as_os_str().to_os_string(),
"--out".into(),
tmp.as_os_str().to_os_string(),
];
argv.extend(plugin_args.iter().map(std::ffi::OsString::from));
match plugin::run(&path, &argv) {
plugin::Ran::Exited(0) => {}
plugin::Ran::Exited(code) => {
let _ = std::fs::remove_file(&tmp);
output::stderr(&transform_exit_text(format, name, code));
return code;
}
plugin::Ran::Signaled(signal) => {
let _ = std::fs::remove_file(&tmp);
output::stderr(&transform_signal_text(format, name, signal));
return exit::FAILURE;
}
plugin::Ran::CannotStart(e) => {
let _ = std::fs::remove_file(&tmp);
output::stderr(&format!(
"cannot start brygge-transform-{name} ({}): {e}",
path.display()
));
return exit::FAILURE;
}
}
let parsed_output = brygge_ir::from_file(&tmp);
let (checks, internal_pass) = compute_internal_checks(&parsed_output);
if !internal_pass {
let _ = std::fs::remove_file(&tmp);
let detail = checks
.iter()
.find_map(|(name, outcome)| match outcome {
CheckOutcome::Fail(d) => Some(format!("{name}: {d}")),
_ => None,
})
.unwrap_or_else(|| "an internal check failed".to_string());
output::stderr(&display::human(&format!(
"the transform's output was refused: {detail}"
)));
return exit::VERIFY_FAILED;
}
let Ok(output_decoded) = parsed_output else {
let _ = std::fs::remove_file(&tmp);
return exit::FAILURE;
};
match brygge_ir::transform::check(&input, &output_decoded, name) {
Ok(summary) => {
let final_exit = fidelity_exit_class(&output_decoded.ir);
drop(output_decoded);
if let Err(e) = std::fs::rename(&tmp, out) {
let _ = std::fs::remove_file(&tmp);
output::stderr(&format!("cannot write {}: {e}", out.display()));
return exit::FAILURE;
}
output::stderr(&transform_result_text(format, &summary));
final_exit
}
Err(violation) => {
let _ = std::fs::remove_file(&tmp);
output::stderr(&display::human(&format!(
"the transform's output was refused: {violation}"
)));
exit::VERIFY_FAILED
}
}
}
fn unmapped_line(identity_count: &authors::IdentityCount) -> String {
let mut counts = Vec::new();
if identity_count.author > 0 {
counts.push(format!("{} author", identity_count.author));
}
if identity_count.committer > 0 {
counts.push(format!("{} committer", identity_count.committer));
}
if identity_count.tagger > 0 {
counts.push(format!("{} tagger", identity_count.tagger));
}
format!(
" {} ({})",
display::human(&authors::identity_as_map_source(&identity_count.identity)),
counts.join(", ")
)
}
fn transform_authors_result_text(
format: Format,
summary: &brygge_ir::transform::StepSummary,
mapped: u64,
unmapped: u64,
) -> String {
match format {
Format::Human => format!(
"step {}: {} atom(s) changed, {} ref(s) changed, {} dropped; {} identit{} mapped, {} left \
unmapped",
summary.step,
summary.atoms_changed,
summary.refs_changed,
summary.dropped,
mapped,
if mapped == 1 { "y" } else { "ies" },
unmapped
),
Format::Machine => format!(
"transform_authors_version={TRANSFORM_AUTHORS_VERSION}\ntransform.step={}\n\
transform.atoms_changed={}\ntransform.ops_changed={}\ntransform.refs_changed={}\n\
transform.dropped={}\ntransform.authors.mapped={mapped}\n\
transform.authors.unmapped={unmapped}",
summary.step,
summary.atoms_changed,
summary.ops_changed,
summary.refs_changed,
summary.dropped,
),
}
}
pub fn run_transform_authors(
artifact: &Path,
map_path: &Path,
out: &Path,
require_all: bool,
format: Format,
) -> i32 {
if same_file_as(out, artifact) {
output::stderr("--out must not be the same file as <artifact>");
return exit::USAGE;
}
let map_bytes = match std::fs::read(map_path) {
Ok(b) => b,
Err(e) => {
output::stderr(&format!("cannot read {}: {e}", map_path.display()));
return exit::FAILURE;
}
};
let map = match authors::parse_map(&map_bytes) {
Ok(m) => m,
Err(problems) => {
for p in &problems {
output::stderr(p);
}
return exit::USAGE;
}
};
let input = match brygge_ir::from_file(artifact) {
Ok(d) => d,
Err(e) => {
output::stderr(&display::human(&format!(
"cannot read {}: {e}",
artifact.display()
)));
return exit::FAILURE;
}
};
if let Some(dup) = brygge_ir::transform::duplicate_source_identity(&input) {
output::stderr(&display::human(&format!(
"refused: the input has two atoms with the same source identity ({dup:?}) — a transform \
cannot match atoms by it at all"
)));
return exit::VERIFY_FAILED;
}
let identities = authors::collect_identities(&input.ir);
let mut hits = vec![0u64; map.mappings.len()];
let mut unmapped = Vec::new();
for ic in &identities {
match authors::lookup(&map, &ic.identity).and_then(|idx| hits.get_mut(idx)) {
Some(hit) => *hit += 1,
None => unmapped.push(ic),
}
}
if !unmapped.is_empty() {
output::stderr(&format!(
"{} identit{} left unmapped:",
unmapped.len(),
if unmapped.len() == 1 { "y" } else { "ies" }
));
for ic in &unmapped {
output::stderr(&unmapped_line(ic));
}
}
if require_all && !unmapped.is_empty() {
output::stderr(
"refused: --require-all needs every identity mapped (see the list above); nothing written",
);
return exit::USAGE;
}
for (mapping, hit) in map.mappings.iter().zip(&hits) {
if *hit == 0 {
output::stderr(&format!(
"warning: map line {} matched nothing",
mapping.line
));
}
}
let mapped_count = (identities.len() - unmapped.len()) as u64;
let mut params = std::collections::BTreeMap::new();
params.insert(
"map_sha256".to_string(),
brygge_ir::BlobId::of(&map_bytes).to_hex(),
);
params.insert("require_all".to_string(), require_all.to_string());
let mut edit =
brygge_ir::transform::Edit::begin(&input, "authors", env!("CARGO_PKG_VERSION"), params);
for (in_atom, atom_edit) in input.ir.atoms.iter().zip(edit.atoms()) {
if let Some(author) = &in_atom.metadata.author {
if let Some(target) = authors::remap(&map, author) {
atom_edit.set_author(Some(target.clone()));
}
}
if let Some(committer) = &in_atom.metadata.committer {
if let Some(target) = authors::remap(&map, committer) {
atom_edit.set_committer(Some(target.clone()));
}
}
}
for r in &input.ir.refs {
let Some(tagger) = r.annotation.as_ref().and_then(|a| a.tagger.as_ref()) else {
continue;
};
let Some(target) = authors::remap(&map, tagger) else {
continue;
};
let mut new_annotation = r.annotation.clone().unwrap_or_default();
new_annotation.tagger = Some(target.clone());
if let Ok(mut ref_edit) = edit.ref_mut(r.kind.clone(), &r.name) {
ref_edit.set_annotation(Some(new_annotation));
}
}
let output_ir = match edit.finish() {
Ok(ir) => ir,
Err(e) => {
output::stderr(&display::human(&format!(
"the transform's own output was refused: {e}"
)));
return exit::FAILURE;
}
};
let dir = out
.parent()
.filter(|p| !p.as_os_str().is_empty())
.unwrap_or_else(|| Path::new("."));
let tmp = match create_transform_temp(dir) {
Ok(p) => p,
Err(e) => {
output::stderr(&format!(
"cannot create a temp file in {}: {e}",
dir.display()
));
return exit::FAILURE;
}
};
if let Err(e) = std::fs::write(&tmp, brygge_ir::to_bytes(&output_ir)) {
let _ = std::fs::remove_file(&tmp);
output::stderr(&format!(
"cannot write a temp file in {}: {e}",
dir.display()
));
return exit::FAILURE;
}
let parsed_output = brygge_ir::from_file(&tmp);
let (checks, internal_pass) = compute_internal_checks(&parsed_output);
if !internal_pass {
let _ = std::fs::remove_file(&tmp);
let detail = checks
.iter()
.find_map(|(name, outcome)| match outcome {
CheckOutcome::Fail(d) => Some(format!("{name}: {d}")),
_ => None,
})
.unwrap_or_else(|| "an internal check failed".to_string());
output::stderr(&display::human(&format!(
"the transform's output was refused: {detail}"
)));
return exit::VERIFY_FAILED;
}
let Ok(output_decoded) = parsed_output else {
let _ = std::fs::remove_file(&tmp);
return exit::FAILURE;
};
match brygge_ir::transform::check(&input, &output_decoded, "authors") {
Ok(summary) => {
let final_exit = fidelity_exit_class(&output_decoded.ir);
drop(output_decoded);
if let Err(e) = std::fs::rename(&tmp, out) {
let _ = std::fs::remove_file(&tmp);
output::stderr(&format!("cannot write {}: {e}", out.display()));
return exit::FAILURE;
}
output::stderr(&transform_authors_result_text(
format,
&summary,
mapped_count,
unmapped.len() as u64,
));
final_exit
}
Err(violation) => {
let _ = std::fs::remove_file(&tmp);
output::stderr(&display::human(&format!(
"the transform's output was refused: {violation}"
)));
exit::VERIFY_FAILED
}
}
}
#[cfg(test)]
#[allow(clippy::print_stdout, clippy::print_stderr)]
mod tests;
#[cfg(test)]
mod mutation;
#[cfg(test)]
mod encode_tests;
#[cfg(test)]
mod transform_tests;