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();
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 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\"\n").unwrap();
std::fs::write(root.join("01-basics/add/recipe.toml"), b"id=\"a\"\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);
}
}