Cotton code
145 lines · 6.6 KB · RustRaw
//! Every tile a kit ships names a picture Loom ships (362 walk, 8 Nov 2026://! Drop, Archive, Face, Sign out, Share ink and the Downloads and//! Subscriptions tools were blank cream tiles with words alone). Kit pictures//! are data: the kit names the picture, Loom's catalogue holds it, and this//! guard holds the two together — an act with no object, an object with no//! imageset, a tool with no picture each fail here rather than on a phone.//! Loom's catalogue is read as `src/definitions/loom_pictures.json`, the//! names `pnpm gen:loom-pictures` writes from its Media.xcassets (held fresh//! by scripts/__tests__/loom-pictures.test.ts): nothing under crates/ reads//! outside it.use cotton_core::definitions::ACT_OBJECTS;use cotton_core::rules::card_actions::CHOOSER_PICTURES;use serde_json::Value;use std::collections::BTreeSet;use std::path::{Path, PathBuf};use std::sync::OnceLock;/// Every picture Loom ships, by imageset name (`loom_pictures.json`).fn shipped() -> &'static BTreeSet<String> {    static SHIPPED: OnceLock<BTreeSet<String>> = OnceLock::new();    SHIPPED.get_or_init(|| {        let names: BTreeSet<String> = serde_json::from_value(json(&cotton_store::manifest_dir().join("src/definitions/loom_pictures.json")))            .expect("loom_pictures.json is a list of imageset names");        assert!(names.len() > 100, "Loom's pictures are read ({})", names.len());        names    })}fn kits() -> PathBuf {    cotton_store::manifest_dir().join("kits")}fn ships(picture: &str) -> bool {    shipped().contains(picture)}fn json(path: &Path) -> Value {    serde_json::from_slice(&std::fs::read(path).unwrap_or_else(|error| panic!("{}: {error}", path.display())))        .unwrap_or_else(|error| panic!("{}: {error}", path.display()))}/// Every file under `kits/*/<dir>/` (tables) or `kits/*/tools/*/manifest.json`.fn kit_files(tables: bool) -> Vec<PathBuf> {    let mut found = Vec::new();    for kit in std::fs::read_dir(kits()).unwrap().flatten().filter(|entry| entry.path().is_dir()) {        if tables {            let Ok(entries) = std::fs::read_dir(kit.path().join("tables")) else { continue };            found.extend(entries.flatten().map(|entry| entry.path()).filter(|path| path.extension().is_some_and(|ext| ext == "json")));        } else {            let Ok(entries) = std::fs::read_dir(kit.path().join("tools")) else { continue };            found.extend(entries.flatten().map(|entry| entry.path().join("manifest.json")).filter(|path| path.is_file()));        }    }    found.sort();    assert!(!found.is_empty(), "the kits are read");    found}fn label(entry: &Value) -> String {    entry["id"].as_str().or(entry["label"].as_str()).unwrap_or("?").to_string()}/// RULE: every bare object a kit may name is a picture Loom ships/// (`act-<object>`), and so is every chooser's picture on a held card.#[test]fn every_act_object_and_chooser_picture_is_shipped() {    for object in ACT_OBJECTS {        assert!(ships(&format!("act-{object}")), "ACT_OBJECTS names {object}, and Loom ships no act-{object}");    }    for (chooser, picture) in CHOOSER_PICTURES {        assert!(ships(picture), "the {chooser} chooser is drawn with {picture}, and Loom ships none");    }}/// RULE: every act a shipped kit offers names its object — a table's/// commands (all but a field card's slips, a list's and a form's), its/// handoffs, its package acts and its Plus doors, and every tool's acts —/// so its tile is a picture and never words alone.#[test]fn every_kit_act_names_its_object() {    let mut missing = Vec::new();    let mut checked = 0;    for path in kit_files(true) {        let file = json(&path);        let tables = match &file {            Value::Array(tables) => tables.clone(),            table => vec![table.clone()],        };        let name = path.strip_prefix(kits()).unwrap().display().to_string();        for table in tables {            for command in table["commands"].as_array().into_iter().flatten() {                if command.get("sheet").is_some() || command.get("list").is_some() || command["form"] == Value::Bool(true) {                    continue;                }                checked += 1;                if command["object"].as_str().is_none() { missing.push(format!("{name} command {}", label(command))); }            }            for (part, entries) in [("act", &table["acts"]), ("handoff", &table["actions"]), ("door", &table["create"]["doors"])] {                for entry in entries.as_array().into_iter().flatten() {                    checked += 1;                    if entry["object"].as_str().is_none() { missing.push(format!("{name} {part} {}", label(entry))); }                }            }        }    }    for path in kit_files(false) {        let name = path.strip_prefix(kits()).unwrap().display().to_string();        for act in json(&path)["acts"].as_array().into_iter().flatten() {            checked += 1;            if act["object"].as_str().is_none() { missing.push(format!("{name} act {}", label(act))); }        }    }    assert!(checked > 100, "the sweep read the kits' acts ({checked})");    assert!(missing.is_empty(), "acts with no picture:\n{}", missing.join("\n"));}/// RULE: every tool a shipped kit carries names a picture that ships — an/// asset Loom holds, or a photo it carries in its `pictures/` (and the/// object that photo is cut from, where it names one) — so its fan tile is/// never a blank card with its name typed on it.#[test]fn every_kit_tool_names_a_shipped_picture() {    let mut missing = Vec::new();    for path in kit_files(false) {        let name = path.strip_prefix(kits()).unwrap().display().to_string();        let picture = &json(&path)["picture"];        let shipped = match picture {            Value::String(asset) => ships(asset),            Value::Object(photo) => {                // Carried in the tool's own `pictures/`, or its kit's.                let tool = path.parent().unwrap();                let kit = tool.parent().unwrap().parent().unwrap();                let carried = photo.get("photo").and_then(Value::as_str).and_then(|photo| photo.strip_prefix("photo:")).is_some_and(|sha| {                    [tool, kit].iter().any(|home| home.join("pictures").join(format!("{sha}.png")).is_file())                });                let object = photo.get("object").and_then(Value::as_str).is_none_or(ships);                carried && object            }            _ => false,        };        if !shipped { missing.push(format!("{name}: {picture}")); }    }    assert!(missing.is_empty(), "tools with no shipped picture:\n{}", missing.join("\n"));}