use std::io;
use std::path::{Path, PathBuf};
pub fn write_embed(recipes_subdir: &str) -> io::Result<()> {
let manifest_dir = std::env::var("CARGO_MANIFEST_DIR")
.map_err(|_| io::Error::other("CARGO_MANIFEST_DIR not set (call from build.rs)"))?;
let out_dir = std::env::var("OUT_DIR")
.map_err(|_| io::Error::other("OUT_DIR not set (call from build.rs)"))?;
let root = Path::new(&manifest_dir).join(recipes_subdir);
println!("cargo:rerun-if-changed={}", root.display());
let code = generate_embed_code(&root)?;
std::fs::write(Path::new(&out_dir).join("cookbook_recipes.rs"), code)
}
pub fn generate_embed_code(recipes_root: &Path) -> io::Result<String> {
let mut files: Vec<(String, PathBuf)> = Vec::new();
if recipes_root.is_dir() {
collect(recipes_root, recipes_root, &mut files)?;
}
files.sort();
validate_embedded_tree(recipes_root, &files)?;
let mut out = String::from("&[\n");
for (rel, abs) in &files {
out.push_str(&format!(
" ({:?}, include_bytes!({:?}) as &[u8]),\n",
rel,
abs.to_string_lossy(),
));
}
out.push_str("]\n");
Ok(out)
}
fn validate_embedded_tree(recipes_root: &Path, files: &[(String, PathBuf)]) -> io::Result<()> {
if files.is_empty() {
return Ok(());
}
let owned = files
.iter()
.map(|(relative, path)| std::fs::read(path).map(|bytes| (relative.as_str(), bytes)))
.collect::<io::Result<Vec<_>>>()?;
let embedded = owned
.iter()
.map(|(relative, bytes)| (*relative, bytes.as_slice()))
.collect::<Vec<_>>();
crate::recipes_from_embedded(&embedded).map_err(|error| {
io::Error::new(
io::ErrorKind::InvalidData,
format!(
"invalid cookbook tree at {}: {error}",
recipes_root.display()
),
)
})?;
Ok(())
}
fn collect(base: &Path, dir: &Path, out: &mut Vec<(String, PathBuf)>) -> io::Result<()> {
let mut entries: Vec<_> = std::fs::read_dir(dir)?.collect::<io::Result<Vec<_>>>()?;
entries.sort_by_key(|e| e.file_name());
for entry in entries {
let path = entry.path();
if path.is_dir() {
collect(base, &path, out)?;
} else if path.is_file() {
let rel = path
.strip_prefix(base)
.map_err(io::Error::other)?
.components()
.map(|c| c.as_os_str().to_string_lossy())
.collect::<Vec<_>>()
.join("/");
out.push((rel, path));
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn empty_dir_yields_empty_slice() {
let dir = std::env::temp_dir().join(format!("sim-cb-embed-empty-{}", std::process::id()));
let code = generate_embed_code(&dir).unwrap();
assert_eq!(code, "&[\n]\n");
}
#[test]
fn generates_sorted_include_bytes() {
let root = std::env::temp_dir().join(format!("sim-cb-embed-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(root.join("01-basics/add")).unwrap();
std::fs::write(
root.join("book.toml"),
b"book = \"x\"\ntitle = \"X\"\nchapters = [\"01-basics\"]\n",
)
.unwrap();
std::fs::write(
root.join("01-basics/add/recipe.toml"),
b"id = \"a\"\ntitle = \"A\"\ncodec = \"lisp\"\nsetup = \"setup.siml\"\npurpose = \"purpose.md\"\n",
)
.unwrap();
std::fs::write(root.join("01-basics/add/setup.siml"), b"(+ 1 2)\n").unwrap();
std::fs::write(root.join("01-basics/add/purpose.md"), b"Add values.\n").unwrap();
let code = generate_embed_code(&root).unwrap();
assert!(code.contains("\"01-basics/add/recipe.toml\""), "{code}");
assert!(code.contains("\"book.toml\""), "{code}");
assert!(code.contains("include_bytes!("), "{code}");
let recipe_at = code.find("recipe.toml").unwrap();
let book_at = code.find("book.toml").unwrap();
assert!(recipe_at < book_at, "expected sorted order, got:\n{code}");
let _ = std::fs::remove_dir_all(&root);
}
#[test]
fn rejects_a_tree_that_would_fail_when_the_library_is_loaded() {
let root =
std::env::temp_dir().join(format!("sim-cb-embed-invalid-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&root);
std::fs::create_dir_all(&root).unwrap();
std::fs::write(root.join("book.toml"), b"title = \"Missing id\"\n").unwrap();
let error = generate_embed_code(&root).unwrap_err();
assert_eq!(error.kind(), io::ErrorKind::InvalidData);
assert!(
error.to_string().contains("missing required key `book`"),
"{error}"
);
let _ = std::fs::remove_dir_all(&root);
}
}