use std::collections::{BTreeSet, HashMap, HashSet};
use std::fmt::Write as _;
use std::io::Write as IoWrite;
use std::path::Path;
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::cli::{Format, SourceKind};
use crate::display;
use crate::exit;
use crate::output;
use crate::plugin;
const VERIFY_VERSION: u32 = 4;
const INSPECT_VERSION: u32 = 4;
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 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,
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))
}
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(),
};
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,
};
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
}
pub fn run_decode(
kind: SourceKind,
source: &Path,
out: &Path,
infer_renames: bool,
reconstruct_refs: 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,
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
}
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 => {
for atom in &ir.atoms {
if innermost_status(&atom.status).is_derived() {
return CheckOutcome::Fail(
"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),
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 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 note = if brygge_versions_differ {
format!("{rerun_note}; {}", version_note())
} else {
rerun_note
};
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(brygge_versions_differ.then(version_note)),
(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 = match (brygge_versions_differ.then(version_note), svn_note) {
(Some(a), Some(b)) => Some(format!("{a}; {b}")),
(Some(a), None) => Some(a),
(None, b) => b,
};
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 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) -> Self {
if !internal_pass || against.is_mismatch() {
Self::Fail
} else if against.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 verdict = Verdict::from(internal_pass, &against);
let skipped = parsed
.as_ref()
.map_or(0, |decoded| decoded.skipped_non_critical_fields);
let rendered =
format_verify_report(format, &checks, internal_pass, &against, &verdict, skipped);
(rendered, verdict.exit_code())
}
pub fn run_verify(
artifact: &Path,
against_source: Option<&Path>,
spill_dir: Option<&Path>,
format: Format,
) -> i32 {
let storage = if against_source.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 verdict = Verdict::from(internal_pass, &against);
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, &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,
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.result={}", verdict.machine_label()));
out
}
fn render_verify(
format: Format,
checks: &[(&'static str, CheckOutcome)],
internal_pass: bool,
against: &AgainstSourceOutcome,
verdict: &Verdict,
skipped_non_critical_fields: u64,
) -> Option<i32> {
let rendered = format_verify_report(
format,
checks,
internal_pass,
against,
verdict,
skipped_non_critical_fields,
);
output::stdout(&rendered)
}
fn format_verify_report(
format: Format,
checks: &[(&'static str, CheckOutcome)],
internal_pass: bool,
against: &AgainstSourceOutcome,
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,
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));
}
}
let _ = writeln!(s, "{}", verdict.human_line());
}
}
s
}
const ENCODE_LIST_VERSION: u32 = 1;
const ENCODE_VERSION: u32 = 1;
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.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);
}
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
}
}
}
const TRANSFORM_LIST_VERSION: u32 = 1;
const TRANSFORM_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.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);
}
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
}
}
}
#[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;