1use std::path::{Path, PathBuf};
13
14use crate::bundle::Bundle;
15use crate::canonical::Fingerprint;
16use crate::contract::Contract;
17use crate::grammar::IfaceId;
18
19#[must_use]
21pub fn path_for(root: &Path, iface: &IfaceId, fp: &Fingerprint) -> PathBuf {
22 root.join(iface.to_string())
23 .join(format!("{}.bundle.json", fp.hex()))
24}
25
26pub fn append(root: &Path, c: &Contract) -> std::io::Result<(PathBuf, bool)> {
29 let b = Bundle::build(c);
30 let path = path_for(root, &c.iface, &b.fingerprint());
31 if path.exists() {
32 return Ok((path, false));
33 }
34 if let Some(dir) = path.parent() {
35 std::fs::create_dir_all(dir)?;
36 }
37 std::fs::write(&path, b.to_bytes())?;
38 Ok((path, true))
39}
40
41#[derive(Debug, Clone, PartialEq, Eq)]
43pub struct Problem {
44 pub at: String,
46 pub tag: &'static str,
50 pub message: String,
51}
52
53#[must_use]
55pub fn check(root: &Path) -> Vec<String> {
56 check_tagged(root)
57 .into_iter()
58 .map(|p| format!("{}: {}", p.at, p.message))
59 .collect()
60}
61
62#[must_use]
66pub fn check_tagged(root: &Path) -> Vec<Problem> {
67 let mut out = Vec::new();
68 let mut push = |at: &str, tag: &'static str, message: String| {
69 out.push(Problem {
70 at: at.to_owned(),
71 tag,
72 message,
73 });
74 };
75 let Ok(dirs) = std::fs::read_dir(root) else {
76 return out;
77 };
78 let mut dirs: Vec<_> = dirs.flatten().collect();
79 dirs.sort_by_key(std::fs::DirEntry::file_name);
80 for d in dirs {
81 let name = d.file_name().to_string_lossy().into_owned();
82 let Ok(iface) = name.parse::<IfaceId>() else {
83 push(
84 &name,
85 "directory",
86 "not an interface directory <name>.v<major>".into(),
87 );
88 continue;
89 };
90 let Ok(files) = std::fs::read_dir(d.path()) else {
91 push(&name, "directory", "not a directory".into());
92 continue;
93 };
94 let mut files: Vec<_> = files.flatten().collect();
95 files.sort_by_key(std::fs::DirEntry::file_name);
96 for f in files {
97 let fname = f.file_name().to_string_lossy().into_owned();
98 let at = format!("{name}/{fname}");
99 let Some(fp) = fname
100 .strip_suffix(".bundle.json")
101 .and_then(|h| Fingerprint::parse(&format!("sha256:{h}")).ok())
102 else {
103 push(
104 &at,
105 "file_name",
106 "not <64 lowercase hex>.bundle.json".into(),
107 );
108 continue;
109 };
110 let bytes = match std::fs::read(f.path()) {
111 Ok(b) => b,
112 Err(e) => {
113 push(&at, "io", e.to_string());
114 continue;
115 }
116 };
117 match Bundle::verify_expecting(&bytes, &fp) {
118 Err(e) => push(&at, e.tag(), e.to_string()),
119 Ok(b) => {
120 if b.contract.get("interface").and_then(|v| v.as_str())
121 != Some(&iface.to_string())
122 {
123 push(
124 &at,
125 "interface",
126 format!("the bundle's interface is not {iface}"),
127 );
128 }
129 if b.to_bytes() != bytes {
130 push(&at, "jcs", "not in JCS form".into());
131 }
132 }
133 }
134 }
135 }
136 out
137}
138
139#[cfg(test)]
140mod tests {
141 use super::*;
142 use crate::contract::load_str;
143
144 #[test]
145 fn append_is_idempotent_and_checked() {
146 let tmp = std::env::temp_dir().join(format!("zk2-history-{}", std::process::id()));
147 let _ = std::fs::remove_dir_all(&tmp);
148 let src = "[interface]\nname = \"t\"\nmajor = 1\nminor = 0\n\
149 [resources.\"a\"]\nkind = \"stream\"\ntype = { raw = \"text/plain\" }\n";
150 let c = load_str(src, Path::new("."), None).contract.unwrap();
151 let (p, wrote) = append(&tmp, &c).unwrap();
152 assert!(wrote);
153 assert!(!append(&tmp, &c).unwrap().1);
154 assert!(check(&tmp).is_empty(), "{:?}", check(&tmp));
155
156 let moved = p.with_file_name(format!("{}.bundle.json", "0".repeat(64)));
157 std::fs::rename(&p, &moved).unwrap();
158 assert_eq!(check(&tmp).len(), 1);
159 std::fs::remove_dir_all(&tmp).unwrap();
160 }
161}