use std::path::{Path, PathBuf};
use crate::bundle::Bundle;
use crate::canonical::Fingerprint;
use crate::contract::Contract;
use crate::grammar::IfaceId;
#[must_use]
pub fn path_for(root: &Path, iface: &IfaceId, fp: &Fingerprint) -> PathBuf {
root.join(iface.to_string())
.join(format!("{}.bundle.json", fp.hex()))
}
pub fn append(root: &Path, c: &Contract) -> std::io::Result<(PathBuf, bool)> {
let b = Bundle::build(c);
let path = path_for(root, &c.iface, &b.fingerprint());
if path.exists() {
return Ok((path, false));
}
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir)?;
}
std::fs::write(&path, b.to_bytes())?;
Ok((path, true))
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Problem {
pub at: String,
pub tag: &'static str,
pub message: String,
}
#[must_use]
pub fn check(root: &Path) -> Vec<String> {
check_tagged(root)
.into_iter()
.map(|p| format!("{}: {}", p.at, p.message))
.collect()
}
#[must_use]
pub fn check_tagged(root: &Path) -> Vec<Problem> {
let mut out = Vec::new();
let mut push = |at: &str, tag: &'static str, message: String| {
out.push(Problem {
at: at.to_owned(),
tag,
message,
});
};
let Ok(dirs) = std::fs::read_dir(root) else {
return out;
};
let mut dirs: Vec<_> = dirs.flatten().collect();
dirs.sort_by_key(std::fs::DirEntry::file_name);
for d in dirs {
let name = d.file_name().to_string_lossy().into_owned();
let Ok(iface) = name.parse::<IfaceId>() else {
push(
&name,
"directory",
"not an interface directory <name>.v<major>".into(),
);
continue;
};
let Ok(files) = std::fs::read_dir(d.path()) else {
push(&name, "directory", "not a directory".into());
continue;
};
let mut files: Vec<_> = files.flatten().collect();
files.sort_by_key(std::fs::DirEntry::file_name);
for f in files {
let fname = f.file_name().to_string_lossy().into_owned();
let at = format!("{name}/{fname}");
let Some(fp) = fname
.strip_suffix(".bundle.json")
.and_then(|h| Fingerprint::parse(&format!("sha256:{h}")).ok())
else {
push(
&at,
"file_name",
"not <64 lowercase hex>.bundle.json".into(),
);
continue;
};
let bytes = match std::fs::read(f.path()) {
Ok(b) => b,
Err(e) => {
push(&at, "io", e.to_string());
continue;
}
};
match Bundle::verify_expecting(&bytes, &fp) {
Err(e) => push(&at, e.tag(), e.to_string()),
Ok(b) => {
if b.contract.get("interface").and_then(|v| v.as_str())
!= Some(&iface.to_string())
{
push(
&at,
"interface",
format!("the bundle's interface is not {iface}"),
);
}
if b.to_bytes() != bytes {
push(&at, "jcs", "not in JCS form".into());
}
}
}
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use crate::contract::load_str;
#[test]
fn append_is_idempotent_and_checked() {
let tmp = std::env::temp_dir().join(format!("zk2-history-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&tmp);
let src = "[interface]\nname = \"t\"\nmajor = 1\nminor = 0\n\
[resources.\"a\"]\nkind = \"stream\"\ntype = { raw = \"text/plain\" }\n";
let c = load_str(src, Path::new("."), None).contract.unwrap();
let (p, wrote) = append(&tmp, &c).unwrap();
assert!(wrote);
assert!(!append(&tmp, &c).unwrap().1);
assert!(check(&tmp).is_empty(), "{:?}", check(&tmp));
let moved = p.with_file_name(format!("{}.bundle.json", "0".repeat(64)));
std::fs::rename(&p, &moved).unwrap();
assert_eq!(check(&tmp).len(), 1);
std::fs::remove_dir_all(&tmp).unwrap();
}
}