Cotton code
130 lines · 4.7 KB · RustRaw
//! `cotton-gen` — generated Swift and Kotlin design values, rendered from//! `cotton_core::design`.//!//! Two generated directories: Loom's `apps/loom/Sources/CottonPaper/Generated`//! (palette, catalogue, logo — the look, which the Mac imports and the phone//! re-exports) and the phone's `apps/cotton/Sources/CottonUI/Generated` (vocabulary,//! emotions, the secret payload — the phone's). The Mac half's own generated//! file was the browser window's `Sections.swift`; H3 deleted the window and it//! went too.//!//! It replaces two Node generators: `scripts/ios-gen.ts` (the phone's palette,//! its asset catalogue and its vocabulary) and `scripts/rust-gen.ts --swift`//! (the Mac's sections and palette). The data they read moved into//! `cotton-core` with them (step 5, R10), so `packages/ui` is no longer a//! generator input.//!//!     cargo run -p cotton-gen            rewrite the generated files//!     cargo run -p cotton-gen -- --check fail on drift (CI)//!     cargo run -p cotton-gen -- --root <dir>   write into another tree (tests)//!//! `--check` WRITES NOTHING AT ALL — it renders in memory and compares BYTES//! with what is committed, naming every differing path and every file that is//! there and should not be. The Node generator it replaces rendered into a temp//! directory first so that a check could not write over the tree it was//! checking; a renderer that returns strings needs no temp directory to make//! the same promise.mod emotions;mod files;mod ios;mod kotlin;mod mark;mod payload;mod retired;mod swift;use std::path::{Path, PathBuf};use std::process::ExitCode;/// The repo root: walk up from this crate until the pnpm workspace manifest is/// found. Walking rather than counting `..` because the crates move to/// `crates/` at the repo root later in this same step, and a count would be a/// silent off-by-two the day they do.fn repo_root() -> Result<PathBuf, String> {    // Read at RUN time, never `env!`: the compile-time value is what a cached    // binary from an earlier CI checkout carries, and it names a directory    // that is gone (#403). Cargo sets it for every `cargo run`.    let manifest = std::env::var("CARGO_MANIFEST_DIR")        .ok()        .filter(|dir| !dir.is_empty())        .ok_or_else(|| {            "cotton-gen: CARGO_MANIFEST_DIR is not set — run through `cargo run`, or pass --root <repo>"                .to_string()        })?;    let start = PathBuf::from(manifest);    let mut at: &Path = &start;    loop {        if at.join("pnpm-workspace.yaml").is_file() {            return Ok(at.to_path_buf());        }        at = at.parent().ok_or_else(|| {            format!(                "cotton-gen: no `pnpm-workspace.yaml` above {} — pass --root <repo>",                start.display()            )        })?;    }}/// `--flag <value>`, or `None` when the flag is absent. `Err` = malformed.fn flag_value(argv: &[String], flag: &str) -> Result<Option<String>, String> {    match argv.iter().position(|arg| arg == flag) {        None => Ok(None),        Some(at) => argv            .get(at + 1)            .cloned()            .map(Some)            .ok_or_else(|| format!("cotton-gen: {flag} needs a directory")),    }}fn run(argv: &[String]) -> Result<i32, String> {    let root = match flag_value(argv, "--root")? {        Some(given) => PathBuf::from(given),        None => repo_root()?,    };    if argv.iter().any(|arg| arg == "--check") {        let differing = files::drift(&root)?;        if !differing.is_empty() {            eprintln!(                "cotton-gen --check: {} file(s) differ from `cotton_core::design`:",                differing.len()            );            for name in &differing {                eprintln!("  {}", root.join(name).display());            }            eprintln!("Run `pnpm gen:design` and commit the result.");            return Ok(1);        }        println!(            "cotton-gen --check: {} files up to date",            files::generate()?.len()        );        return Ok(0);    }    let written = files::write(&root)?;    println!("cotton-gen: {} files → {}", written.len(), root.display());    println!("  Swift: {} and {}", files::IOS_PAPER_DIR, files::IOS_DIR);    println!("  Kotlin: {}", files::ANDROID_DIR);    println!("  Kotlin core: {}", files::ANDROID_CORE_DIR);    Ok(0)}fn main() -> ExitCode {    let argv: Vec<String> = std::env::args().skip(1).collect();    match run(&argv) {        Ok(0) => ExitCode::SUCCESS,        Ok(code) => ExitCode::from(u8::try_from(code).unwrap_or(1)),        Err(message) => {            eprintln!("{message}");            ExitCode::from(2)        }    }}#[cfg(test)]#[path = "main_tests.rs"]mod tests;