Cotton code
317 lines · 16.6 KB · RustRaw
#[path = "src/definitions/revision.rs"]mod revision;#[path = "src/kit_pictures.rs"]mod kit_pictures;use std::{    env, fs,    path::{Path, PathBuf},    process::Command,};fn collect(root: &Path, dir: &Path, files: &mut Vec<(String, Vec<u8>)>) {    println!("cargo:rerun-if-changed={}", dir.display());    for entry in fs::read_dir(dir).expect("definition directory") {        let path = entry.expect("definition entry").path();        if path.is_dir() {            collect(root, &path, files);        } else if path            .extension()            .is_some_and(|extension| extension == "json")        {            let name = path                .strip_prefix(root)                .unwrap()                .to_str()                .expect("UTF-8 definition path")                .replace('\\', "/");            files.push((name, fs::read(&path).expect("definition bytes")));        }    }}fn git(args: &[&str]) -> String {    let out = Command::new("git")        .args(args)        .output()        .expect("git at build time");    assert!(out.status.success(), "cannot read build commit");    String::from_utf8(out.stdout).unwrap().trim().to_owned()}fn main() {    let crate_dir = PathBuf::from(env::var_os("CARGO_MANIFEST_DIR").unwrap());    // The kits (`kits/` in this crate): one folder per app, each a kit.json    // naming the tables, tools and boards it ships, its tables beside it and    // its tools under `tools/<id>/`. The shell (`kits/shell/`: the Bin, Home's    // board, the themes and the lines) is what every database is created with;    // the personal kit's tools are Cotton's kit (`kit::package`); every other    // kit's tools are the business packages a toolkit carries    // (`toolkits::SHIPPED_PACKAGES`).    let kits = crate_dir.join("kits").canonicalize().expect("the kits directory");    let mut files = Vec::new();    collect(&kits, &kits, &mut files);    // The one kit this core is for (`COTTON_CORE_KIT`, set per app by    // scripts/build-xcframework.sh and scripts/build-android-core.sh): it    // carries that kit's tools' pictures and the shell's, and no other    // tool's (`kit_pictures`). Unset is the whole object's core.    println!("cargo:rerun-if-env-changed={}", kit_pictures::CORE_KIT_ENV);    println!("cargo:rustc-check-cfg=cfg(cotton_app_core)");    let carried = kit_pictures::Carried::of(&kits, env::var(kit_pictures::CORE_KIT_ENV).ok().as_deref()).unwrap_or_else(|why| panic!("{why}"));    if carried.kit.is_some() {        println!("cargo:rustc-cfg=cotton_app_core");    }    // The picture bytes a kit package or the shell carries serve the app's    // assets too; discover them from the definitions so adding a tool needs no    // code registry. A definition's pictures sit in its package's `pictures/`.    let mut pictures = std::collections::BTreeMap::new();    for (name, bytes) in &files {        let value: serde_json::Value = serde_json::from_slice(bytes).expect("kit JSON");        let Some(photo) = value.pointer("/picture/photo").and_then(serde_json::Value::as_str) else { continue };        let Some(object) = value.pointer("/picture/object").and_then(serde_json::Value::as_str) else { continue };        assert!(!object.contains(['/', '\\']), "picture object is an asset name");        let png = format!("{}.png", photo.trim_start_matches("photo:"));        let path = match picture_home(name) {            Some(package) => kits.join(package).join("pictures").join(&png).canonicalize().expect("kit picture bytes"),            // A kit's own table: its picture sits in the `pictures/` of a            // tool that names it, when one carries it; else the object            // serves it with the table.            None => match carried_picture(&kits, &carried, name, &png) {                Some(path) => path,                None => continue,            },        };        if !carried.carries(&kits, &path) {            continue;        }        println!("cargo:rerun-if-changed={}", path.display());        pictures.insert(photo.trim_start_matches("photo:").to_string(), path);    }    let mut generated = String::from("pub const OBJECT_TOOL_PICTURES: &[(&str, &[u8])] = &[\n");    for (hash, path) in pictures { generated.push_str(&format!("({hash:?}, include_bytes!({:?})),\n", path.to_str().expect("picture path"))); }    generated.push_str("];\n");    let out = PathBuf::from(env::var_os("OUT_DIR").unwrap());    fs::write(out.join("core_kit.rs"), format!("pub const CORE_KIT: Option<&str> = {:?};\n", carried.kit)).expect("core kit");    fs::write(out.join("tool_pictures.rs"), generated).expect("picture registry");    // The personal kit's tools, compiled in for `kit::package`.    let personal = tools_of(&kits, "personal");    fs::write(out.join("kit_files.rs"), package_registry(&kits, &carried, "KIT_FILES", &personal)).expect("kit registry");    // The shell kit's tables, `(id, json)` in its kit.json's order — the    // tables every database is made with, wherever each is defined.    let mut shell = String::from("pub const SHELL_KIT_TABLES: &[(&str, &str)] = &[\n");    for name in kit_json(&kits, "shell")["tables"].as_array().expect("kits/shell/kit.json lists its tables") {        let (kit, id) = entry("shell", name.as_str().expect("a table entry"));        let path = kits.join(&kit).join("tables").join(format!("{id}.json")).canonicalize().expect("the shell's table file");        println!("cargo:rerun-if-changed={}", path.display());        shell.push_str(&format!("    ({id:?}, include_str!({:?})),\n", path.to_str().expect("table path")));    }    shell.push_str("];\n");    fs::write(out.join("shell_kit_tables.rs"), shell).expect("shell tables");    // Every other app's kit: its tools, each with the tables it names. A tool    // the personal kit defines that another kit lists (Cotton Books lists    // `personal/books`) is Cotton's own, already in the kit above, and never    // a business package.    let mut business = Vec::new();    let cottons = kits.join("personal").join("tools");    for kit in kit_ids(&kits).into_iter().filter(|kit| kit != "personal" && kit != "shell") {        business.extend(tools_of(&kits, &kit).into_iter().filter(|(_, dir)| !dir.starts_with(&cottons)));    }    fs::write(out.join("kit_packages.rs"), shipped_packages(&kits, &business)).expect("business packages");    // Every app's kit.json, `(id, json)` by id: what an app keeps to    // (`kit::AppKit`), its tools and tables named as the kit names them.    let mut app_kits = String::from("pub const APP_KITS: &[(&str, &str)] = &[\n");    for kit in kit_ids(&kits) {        let path = kits.join(&kit).join("kit.json");        kit_json(&kits, &kit);        app_kits.push_str(&format!("    ({kit:?}, include_str!({:?})),\n", path.to_str().expect("kit path")));    }    app_kits.push_str("];\n");    fs::write(out.join("app_kits.rs"), app_kits).expect("app kits");    // The face ids a card may name (`definitions::card::FaceId`): Loom's    // registry and the faces CottonUI still draws, as `pnpm gen:faces` writes    // them from apps/loom/faces.json and faces-pending.json.    let faces = crate_dir.join("src/definitions/face_ids.json");    println!("cargo:rerun-if-changed={}", faces.display());    let ids: Vec<String> = serde_json::from_slice(&fs::read(&faces).expect("face_ids.json")).expect("face_ids.json is a list of ids");    assert!(ids.windows(2).all(|pair| pair[0] < pair[1]), "face_ids.json is sorted and names each id once: run `pnpm gen:faces`");    let mut known = String::from("pub const KNOWN_FACES: &[&str] = &[\n");    for id in &ids {        known.push_str(&format!("    {id:?},\n"));    }    known.push_str("];\n");    fs::write(out.join("face_ids.rs"), known).expect("face ids");    println!(        "cargo:rustc-env=COTTON_DEFINITIONS_HASH={}",        revision::content_hash(files.iter().map(|(p, b)| (p.as_str(), b.as_slice())))    );    for path in [        git(&["rev-parse", "--git-path", "HEAD"]),        git(&["rev-parse", "--git-path", "packed-refs"]),    ] {        println!("cargo:rerun-if-changed={path}");    }    let symbolic = Command::new("git")        .args(["symbolic-ref", "-q", "HEAD"])        .output()        .unwrap();    if symbolic.status.success() {        println!(            "cargo:rerun-if-changed={}",            git(&[                "rev-parse",                "--git-path",                String::from_utf8(symbolic.stdout).unwrap().trim()            ])        );    }    println!(        "cargo:rustc-env=COTTON_DEFINITIONS_STAMP={}",        git(&["show", "-s", "--format=%ct", "HEAD"])    );}/// The package a definition file under `kits/` belongs to, whose `pictures/`/// holds the pictures it names: a tool's folder (`<kit>/tools/<id>`) or the/// shell. A kit's own tables are the object's to serve, pictures and all, so/// the build carries none for them.fn picture_home(name: &str) -> Option<String> {    let parts: Vec<&str> = name.split('/').collect();    match parts.as_slice() {        [kit, "tools", tool, _, ..] => Some(format!("{kit}/tools/{tool}")),        ["shell", _, ..] => Some("shell".to_string()),        _ => None,    }}/// The picture `png` of the kit table file `name` (`<kit>/tables/<id>.json`)/// as a tool of that kit carries it: the `pictures/` of a tool whose manifest/// names the table, among the tools this core carries.fn carried_picture(root: &Path, carried: &kit_pictures::Carried, name: &str, png: &str) -> Option<PathBuf> {    let parts: Vec<&str> = name.split('/').collect();    let [kit, "tables", file] = parts.as_slice() else { return None };    let table = file.strip_suffix(".json")?;    let mut tools: Vec<PathBuf> = fs::read_dir(root.join(kit).join("tools")).ok()?.map(|entry| entry.expect("tools entry").path()).collect();    tools.sort();    tools.into_iter().filter(|tool| carried.carries_tool(tool)).find_map(|tool| {        let manifest: serde_json::Value = serde_json::from_slice(&fs::read(tool.join("manifest.json")).ok()?).ok()?;        let names = manifest["tables"].as_array()?.iter().any(|named| entry(kit, named.as_str().unwrap_or_default()) == (kit.to_string(), table.to_string()));        let path = tool.join("pictures").join(png);        (names && path.is_file()).then(|| path.canonicalize().expect("kit picture bytes"))    })}/// The kits under `root`, by folder name.fn kit_ids(root: &Path) -> Vec<String> {    let mut ids: Vec<String> = fs::read_dir(root)        .expect("the kits directory")        .map(|entry| entry.expect("kits entry").path())        .filter(|path| path.join("kit.json").is_file())        .map(|path| path.file_name().unwrap().to_str().expect("UTF-8 kit id").to_string())        .collect();    ids.sort();    ids}/// A kit's kit.json.fn kit_json(root: &Path, kit: &str) -> serde_json::Value {    let path = root.join(kit).join("kit.json");    println!("cargo:rerun-if-changed={}", path.display());    let value: serde_json::Value = serde_json::from_slice(&fs::read(&path).expect("kit.json")).expect("kit.json is JSON");    assert_eq!(value["id"].as_str(), Some(kit), "{} names another kit", path.display());    value}/// Where an entry of a kit's list lives: `"<id>"` is the kit's own, and/// `"<kit>/<id>"` names another kit's, so a file is defined once and listed/// by any kit.fn entry(kit: &str, name: &str) -> (String, String) {    match name.split_once('/') {        Some((other, id)) => (other.to_string(), id.to_string()),        None => (kit.to_string(), name.to_string()),    }}/// The tool folders `kit` ships, in its kit.json's order: `(tool id, folder)`.fn tools_of(root: &Path, kit: &str) -> Vec<(String, PathBuf)> {    let listed = kit_json(root, kit);    let tools = listed["tools"].as_array().unwrap_or_else(|| panic!("kits/{kit}/kit.json lists its tools"));    tools        .iter()        .map(|name| {            let (home, id) = entry(kit, name.as_str().expect("a tool entry is a string"));            let dir = root.join(&home).join("tools").join(&id);            assert!(dir.join("manifest.json").is_file(), "kits/{kit} lists tool {id}, which kits/{home}/tools/{id}/manifest.json does not hold");            (id, dir)        })        .collect()}/// `pub const SHIPPED_PACKAGES: &[(tool id, manifest, tables)]`: each tool/// with the tables its manifest names, read from its kit's `tables/`.fn shipped_packages(root: &Path, tools: &[(String, PathBuf)]) -> String {    let mut out = String::from("pub const SHIPPED_PACKAGES: &[(&str, &str, &[&str])] = &[\n");    for (id, dir) in tools {        let manifest = dir.join("manifest.json");        println!("cargo:rerun-if-changed={}", manifest.display());        let tool: serde_json::Value = serde_json::from_slice(&fs::read(&manifest).expect("manifest")).expect("manifest is JSON");        let kit = dir.parent().and_then(Path::parent).and_then(Path::file_name).and_then(|n| n.to_str()).expect("a tool's kit").to_string();        out.push_str(&format!("({id:?}, include_str!({:?}), &[", manifest.to_str().expect("manifest path")));        for table in tool["tables"].as_array().into_iter().flatten() {            let (home, table) = entry(&kit, table.as_str().expect("a table id"));            let path = root.join(&home).join("tables").join(format!("{table}.json"));            assert!(path.is_file(), "{id} names table {table}, which kits/{home}/tables does not hold");            println!("cargo:rerun-if-changed={}", path.display());            out.push_str(&format!("include_str!({:?}), ", path.to_str().expect("table path")));        }        out.push_str("]),\n");    }    out.push_str("];\n");    out}/// `pub const <name>: &[(tool id, path in the package, bytes)]` for every/// tool folder in `tools`, in id order: its manifest, the tables its/// manifest names — each the one definition in its kit's `tables/`, carried/// as `tables/<id>.json` — then its pictures and sample records, each in name/// order. A tool whose pictures this core does not carry (`kit_pictures`)/// keeps its definitions and sample records, and no picture.fn package_registry(root: &Path, carried: &kit_pictures::Carried, name: &str, tools: &[(String, PathBuf)]) -> String {    let mut out = format!("pub const {name}: &[(&str, &str, &[u8])] = &[\n");    // The files' digest, worked out here once a build (`kit::fingerprint`): hashed at launch, every picture the core    // carries was read through SHA-256 on every cold open (about 2 s of an emulator's launch on a debug core).    let mut digest = <sha2::Sha256 as sha2::Digest>::new();    for (id, tool) in tools.iter().map(|(id, dir)| (id, dir)).collect::<std::collections::BTreeMap<_, _>>() {        let manifest = tool.join("manifest.json");        let kit = tool.parent().and_then(Path::parent).and_then(Path::file_name).and_then(|n| n.to_str()).expect("a tool's kit").to_string();        let named: serde_json::Value = serde_json::from_slice(&fs::read(&manifest).expect("manifest")).expect("manifest is JSON");        let mut tables = std::collections::BTreeMap::new();        for table in named["tables"].as_array().into_iter().flatten() {            let (home, table) = entry(&kit, table.as_str().expect("a table id"));            let path = root.join(&home).join("tables").join(format!("{table}.json"));            assert!(path.is_file(), "{id} names table {table}, which kits/{home}/tables does not hold");            tables.insert(format!("tables/{table}.json"), path);        }        let mut files = vec![("manifest.json".to_string(), manifest)];        files.extend(tables);        for part in ["pictures", "records"] {            if part == "pictures" && !carried.carries_tool(tool) {                continue;            }            if let Ok(entries) = fs::read_dir(tool.join(part)) {                let mut entries: Vec<_> = entries.map(|entry| entry.expect("package entry").path()).collect();                entries.sort();                files.extend(entries.into_iter().map(|path| (path.strip_prefix(tool).unwrap().to_str().expect("UTF-8 package path").replace('\\', "/"), path)));            }        }        for (file, path) in files {            println!("cargo:rerun-if-changed={}", path.display());            out.push_str(&format!("({id:?}, {file:?}, include_bytes!({:?})),\n", path.to_str().expect("package path")));            let bytes = fs::read(&path).expect("package file");            for part in [id.as_bytes(), file.as_bytes(), bytes.as_slice()] {                sha2::Digest::update(&mut digest, (part.len() as u64).to_le_bytes());                sha2::Digest::update(&mut digest, part);            }        }    }    out.push_str("];\n");    let digest: String = sha2::Digest::finalize(digest).iter().map(|byte| format!("{byte:02x}")).collect();    out.push_str(&format!("pub const {name}_DIGEST: &str = {digest:?};\n"));    out}