Cotton code
207 lines · 9.9 KB · RustRaw
//! Which pictures a core carries (15 Nov 2026).//!//! `kits/` holds every app's pictures (23 MB of PNGs, nearly all of it under//! `kits/personal/tools/<id>/pictures/`), and until this rule every core//! carried all of them: Books on a phone held Music's, Money's and Cinemas'//! pictures, 31 MB of data it never drew. A core built for ONE app's kit//! (`COTTON_CORE_KIT=<kit>`, read by `build.rs`) carries the pictures of the//! tools that kit holds (its `tools` and its `folds`, `kit::AppKit::held`) and//! the shell's, and no other tool's. Every definition stays whole: only//! picture bytes are per app. A build that names no kit (Cotton's whole//! object, the Worker's module, the Mac importer, every test) carries all.//!//! The rule is read from the kit's own `kit.json`, never a list kept per app,//! and it is this one file for the build script and the crate both//! (`build.rs` takes it by path, as it takes `definitions/revision.rs`), so//! the tests here hold the build to it.use std::{    fs,    path::{Path, PathBuf},};/// The build input that names the one kit a core is for.pub const CORE_KIT_ENV: &str = "COTTON_CORE_KIT";/// What a core carries: every tool's pictures, or one kit's.#[derive(Debug, Clone, PartialEq, Eq)]pub struct Carried {    /// The kit this core is for; none is the whole object.    pub kit: Option<String>,    /// The tool folders whose `pictures/` it carries; none is every tool's.    held: Option<Vec<PathBuf>>,}impl Carried {    /// What the core for `kit` carries of the kits under `root`, or why no    /// such core is built: a kit the tree does not hold, one that is no app's    /// to keep to (`personal`, `shell`: Cotton's whole object names no kit),    /// or a held tool that names a picture its folder does not carry.    pub fn of(root: &Path, kit: Option<&str>) -> Result<Carried, String> {        let Some(kit) = kit.filter(|kit| !kit.is_empty()) else {            return Ok(Carried { kit: None, held: None });        };        if kit == "personal" || kit == "shell" {            return Err(format!("{CORE_KIT_ENV}={kit}: {kit} is no app's kit; a whole-object core is built with {CORE_KIT_ENV} unset"));        }        let path = root.join(kit).join("kit.json");        let text = fs::read(&path).map_err(|_| format!("{CORE_KIT_ENV}={kit}: kits/{kit}/kit.json is not there"))?;        let listed: serde_json::Value = serde_json::from_slice(&text).map_err(|error| format!("kits/{kit}/kit.json: {error}"))?;        let mut held = Vec::new();        for list in ["tools", "folds"] {            for name in listed[list].as_array().into_iter().flatten() {                let name = name.as_str().ok_or_else(|| format!("kits/{kit}/kit.json: a {list} entry is a string"))?;                let (home, id) = name.split_once('/').unwrap_or((kit, name));                let tool = root.join(home).join("tools").join(id);                for photo in named_photos(&tool)? {                    if picture_file(&tool, &photo).is_none() {                        return Err(format!(                            "{CORE_KIT_ENV}={kit}: kits/{home}/tools/{id} names photo:{photo}, which its pictures/ does not hold, so the {kit} core would draw it blank"                        ));                    }                }                held.push(tool);            }        }        Ok(Carried { kit: Some(kit.to_string()), held: Some(held) })    }    /// Whether the core carries the pictures in the tool folder `tool`    /// (`kits/<kit>/tools/<id>`).    pub fn carries_tool(&self, tool: &Path) -> bool {        self.held.as_ref().is_none_or(|held| held.iter().any(|dir| dir == tool))    }    /// Whether the core carries the picture file `path`: the shell's always,    /// a tool's when the core carries that tool, and a picture that is no    /// tool's (the business kits' own, `kits/kitchen/pictures`) only in a    /// whole core.    pub fn carries(&self, root: &Path, path: &Path) -> bool {        let Some(held) = &self.held else { return true };        path.starts_with(root.join("shell")) || held.iter().any(|tool| path.starts_with(tool.join("pictures")))    }}/// Every `photo:<sha256>` the tool folder's manifest names, by hash: its own/// picture and its fan tile's, wherever the manifest says one.fn named_photos(tool: &Path) -> Result<Vec<String>, String> {    let manifest = tool.join("manifest.json");    let text = fs::read_to_string(&manifest).map_err(|_| format!("{} is not there", manifest.display()))?;    let mut photos: Vec<String> = text        .split("photo:")        .skip(1)        .filter_map(|rest| rest.get(..64))        .filter(|hash| hash.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)))        .map(str::to_string)        .collect();    photos.sort();    photos.dedup();    Ok(photos)}/// The file in the tool folder's `pictures/` that holds the picture `hash`.fn picture_file(tool: &Path, hash: &str) -> Option<PathBuf> {    let prefix = format!("{hash}.");    fs::read_dir(tool.join("pictures")).ok()?.filter_map(Result::ok).map(|entry| entry.path())        .find(|path| path.file_name().and_then(|name| name.to_str()).is_some_and(|name| name.starts_with(&prefix)))}#[cfg(test)]mod tests {    use super::*;    fn kits() -> PathBuf {        cotton_store::manifest_dir().join("kits")    }    fn pictures(root: &Path, tool: &str) -> Vec<PathBuf> {        let mut files: Vec<PathBuf> = fs::read_dir(root.join(tool).join("pictures")).expect("the tool's pictures").map(|entry| entry.unwrap().path()).collect();        files.sort();        assert!(!files.is_empty(), "{tool} carries pictures");        files    }    /// RULE: a Books core holds Books' pictures and the shell's, and no other    /// tool's (Money's, Music's), nor a business kit's own.    #[test]    fn a_books_core_holds_books_and_the_shells_pictures_and_not_moneys() {        let root = kits();        let books = Carried::of(&root, Some("books")).expect("the Books core");        assert_eq!(books.kit.as_deref(), Some("books"));        for path in pictures(&root, "personal/tools/books").into_iter().chain(pictures(&root, "shell")) {            assert!(books.carries(&root, &path), "the Books core carries {}", path.display());        }        for other in ["personal/tools/money", "personal/tools/music", "kitchen"] {            for path in pictures(&root, other) {                assert!(!books.carries(&root, &path), "the Books core carries {}", path.display());            }        }        assert!(books.carries_tool(&root.join("personal/tools/books")));        assert!(!books.carries_tool(&root.join("personal/tools/money")));    }    /// RULE: a kit's core carries every tool it holds, the folded ones too    /// (People folds Birthdays), and Money's holds Subscriptions'.    #[test]    fn a_core_carries_every_tool_its_kit_holds() {        let root = kits();        let people = Carried::of(&root, Some("people")).expect("the People core");        assert!(people.carries_tool(&root.join("personal/tools/people")));        assert!(people.carries_tool(&root.join("personal/tools/birthdays")));        let money = Carried::of(&root, Some("money")).expect("the Money core");        for tool in ["personal/tools/money", "personal/tools/subscriptions"] {            for path in pictures(&root, tool) {                assert!(money.carries(&root, &path), "the Money core carries {}", path.display());            }        }    }    /// RULE: a build that names no kit carries everything (Cotton's whole    /// object, the Worker's module, the Mac importer).    #[test]    fn a_whole_core_carries_everything() {        let root = kits();        for whole in [Carried::of(&root, None).unwrap(), Carried::of(&root, Some("")).unwrap()] {            assert_eq!(whole.kit, None);            for tool in ["personal/tools/money", "personal/tools/books", "shell", "kitchen"] {                for path in pictures(&root, tool) {                    assert!(whole.carries(&root, &path));                }            }        }    }    /// RULE: every app kit this tree ships builds its core: each tool it    /// holds carries the pictures it names.    #[test]    fn every_app_kit_builds_its_core() {        let root = kits();        for (id, _) in crate::kit::APP_KITS.iter().filter(|(id, _)| *id != "personal" && *id != "shell" && *id != "kitchen") {            Carried::of(&root, Some(id)).unwrap_or_else(|why| panic!("{why}"));        }    }    /// RULE: a picture a kit's tool names and does not carry fails the build,    /// never draws blank; so does a kit that is not there, and the two kits    /// that are no app's.    #[test]    fn a_missing_picture_and_an_unknown_kit_fail_the_build() {        let root = std::env::temp_dir().join(format!("cotton-kit-pictures-{}", std::process::id()));        let _ = fs::remove_dir_all(&root);        let tool = root.join("personal/tools/ledger");        fs::create_dir_all(tool.join("pictures")).unwrap();        fs::create_dir_all(root.join("ledger")).unwrap();        fs::write(root.join("ledger/kit.json"), r#"{"id":"ledger","tools":["personal/ledger"]}"#).unwrap();        let hash = "ab".repeat(32);        fs::write(tool.join("manifest.json"), format!(r#"{{"id":"ledger","picture":{{"photo":"photo:{hash}"}}}}"#)).unwrap();        let why = Carried::of(&root, Some("ledger")).expect_err("a named picture that is not carried");        assert!(why.contains(&hash) && why.contains("blank"), "{why}");        fs::write(tool.join("pictures").join(format!("{hash}.png")), b"png").unwrap();        let ledger = Carried::of(&root, Some("ledger")).expect("the picture is carried now");        assert!(ledger.carries(&root, &tool.join("pictures").join(format!("{hash}.png"))));        assert!(Carried::of(&root, Some("absent")).unwrap_err().contains("kits/absent/kit.json"));        for none in ["personal", "shell"] {            assert!(Carried::of(&root, Some(none)).unwrap_err().contains("no app's kit"));        }        fs::remove_dir_all(&root).unwrap();    }}