use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use crate::witclosure::{PackageIdent, WitClosureError};
#[derive(Debug, thiserror::Error)]
pub enum WitExportError {
#[error(transparent)]
Closure(#[from] WitClosureError),
#[error("io error at {path}: {source}")]
Io {
path: String,
#[source]
source: std::io::Error,
},
#[error(
"the closure names {ident}, and the layer carries it, but no bytes were supplied for it \
— the caller built an index the export could not read back"
)]
BytesMissing { ident: String },
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WitExportReport {
pub root: String,
pub written: Vec<String>,
pub wkg_root: PathBuf,
}
pub fn export(
closure: &[PackageIdent],
root: &PackageIdent,
out: &Path,
bytes_of: &dyn Fn(&PackageIdent) -> Option<Vec<u8>>,
) -> Result<WitExportReport, WitExportError> {
let io = |path: &Path, source: std::io::Error| WitExportError::Io {
path: path.display().to_string(),
source,
};
let mut resolved: BTreeMap<&PackageIdent, Vec<u8>> = BTreeMap::new();
for ident in closure {
let Some(bytes) = bytes_of(ident) else {
return Err(WitExportError::BytesMissing {
ident: ident.as_str().to_string(),
});
};
resolved.insert(ident, bytes);
}
std::fs::create_dir_all(out).map_err(|e| io(out, e))?;
let mut written = Vec::with_capacity(closure.len());
for ident in closure {
let rel = ident.binary_path();
let dest = out.join(&rel);
let parent = dest.parent().expect("binary_path always has a directory");
std::fs::create_dir_all(parent).map_err(|e| io(parent, e))?;
let bytes = resolved
.get(ident)
.expect("every closure member was resolved above");
std::fs::write(&dest, bytes).map_err(|e| io(&dest, e))?;
written.push(ident.as_str().to_string());
}
Ok(WitExportReport {
root: root.as_str().to_string(),
written,
wkg_root: out.to_path_buf(),
})
}
pub fn wkg_stanza(registry: &str, root: &Path) -> String {
format!(
"[registry.\"{registry}\".local]\nroot = \"{}\"\n",
root.display()
)
}
#[cfg(test)]
mod tests {
use super::*;
fn ident(s: &str) -> PackageIdent {
s.parse().expect("fixture ident must parse")
}
#[test]
fn each_package_lands_where_wkg_reads_it_with_the_bytes_it_was_given() {
let tmp = tempfile::tempdir().unwrap();
let base = ident("acme:base@2.0.0");
let app = ident("acme:app@0.3.0");
let closure = vec![base.clone(), app.clone()];
let bytes_of = |i: &PackageIdent| Some(format!("bytes-of-{}", i.as_str()).into_bytes());
let report = export(&closure, &app, tmp.path(), &bytes_of).unwrap();
let base_path = tmp.path().join("acme/base/2.0.0.wasm");
let app_path = tmp.path().join("acme/app/0.3.0.wasm");
assert!(base_path.is_file(), "wkg reads <ns>/<name>/<version>.wasm");
assert!(app_path.is_file());
assert_eq!(
std::fs::read(&app_path).unwrap(),
b"bytes-of-acme:app@0.3.0".to_vec(),
"the export re-encoded a package instead of copying it"
);
assert_eq!(report.written.len(), 2);
assert_eq!(report.root, "acme:app@0.3.0");
}
#[test]
fn a_package_with_no_bytes_leaves_no_partial_tree() {
let tmp = tempfile::tempdir().unwrap();
let base = ident("acme:base@2.0.0");
let app = ident("acme:app@0.3.0");
let closure = vec![base.clone(), app.clone()];
let bytes_of =
|i: &PackageIdent| (i.as_str() != "acme:app@0.3.0").then(|| b"some-bytes".to_vec());
let err = export(&closure, &app, tmp.path(), &bytes_of).unwrap_err();
assert!(
matches!(&err, WitExportError::BytesMissing { ident } if ident == "acme:app@0.3.0"),
"{err:?}"
);
assert!(
!tmp.path().join("acme/base/2.0.0.wasm").exists(),
"the dependency was written before the failure — a partial tree"
);
}
#[test]
fn the_wkg_stanza_points_at_what_was_exported() {
let s = wkg_stanza("acme.registry.example", Path::new("/w/wit"));
assert!(
s.contains("[registry.\"acme.registry.example\".local]"),
"{s}"
);
assert!(s.contains("root = \"/w/wit\""), "{s}");
}
}