//! Embeds the bundled lexicons, those fetched (`lexicons/.json`) and //! our own (`schemas/.json`), the bundled views, `views/.json`, //! and the themes, `themes/.json`, all at the workspace's root: each as //! a table sorted by name, of its name and its text, so the common record //! types never reach the network and the views and themes need no files at //! run time. A lexicon whose file is not named `.json` fails the //! build; the views are checked as they load (`view::bundled`), the themes //! as they do (`theme::all`), and both by the tests. #![forbid(unsafe_code)] use std::{env, fmt::Write, fs, path::Path}; /// The `.json` files of `dir`, by name less `.json`, sorted. fn files(dir: &Path) -> Vec<(String, std::path::PathBuf)> { println!("cargo:rerun-if-changed={}", dir.display()); let mut out: Vec<_> = fs::read_dir(dir) .unwrap_or_else(|e| panic!("{}: {e}", dir.display())) .map(|e| e.unwrap()) .filter(|e| e.file_type().unwrap().is_file()) .filter_map(|e| { let name = e.file_name().into_string().unwrap(); let stem = name.strip_suffix(".json")?.to_string(); assert!( stem.bytes() .all(|c| c.is_ascii_alphanumeric() || c == b'.' || c == b'-'), "{}/{name}: a name of letters, digits, . and - only", dir.display() ); Some((stem, e.path().canonicalize().unwrap())) }) .collect(); out.sort(); out } /// A static table of `files`' names and texts. fn table(name: &str, doc: &str, files: &[(String, std::path::PathBuf)]) -> String { let mut out = format!("/// {doc}\nstatic {name}: &[(&str, &str)] = &[\n"); for (stem, path) in files { writeln!( out, " ({stem:?}, include_str!({:?})),", path.display().to_string() ) .unwrap(); } out.push_str("];\n"); out } fn main() { let root = Path::new(&env::var("CARGO_MANIFEST_DIR").unwrap()).join("../.."); let out = Path::new(&env::var("OUT_DIR").unwrap()).to_path_buf(); // Our own lexicons (`schemas/`) beside those fetched (`lexicons/`): // one table, as either resolves the same way. let mut lexicons = files(&root.join("lexicons")); lexicons.extend(files(&root.join("schemas"))); lexicons.sort(); for pair in lexicons.windows(2) { assert_ne!( pair[0].0, pair[1].0, "{} is both fetched and our own", pair[0].0 ); } for (nsid, _) in &lexicons { assert!( nsid.split('.').count() >= 3, "lexicons/{nsid}.json: not named .json" ); } fs::write( out.join("bundled.rs"), table( "BUNDLED", "The bundled lexicons, by NSID, sorted: each its document's text.", &lexicons, ), ) .unwrap(); fs::write( out.join("views.rs"), table( "VIEWS", "The bundled views, by id, sorted: each its document's text.", &files(&root.join("views")), ), ) .unwrap(); fs::write( out.join("themes.rs"), table( "THEMES", "The themes, by key, sorted: each its document's text.", &files(&root.join("themes")), ), ) .unwrap(); }