Cotton code
114 lines · 6.1 KB · RustRaw
//! The faces walk's database-only tools (`scripts/faces-walk/tools`) wear the//! cards `scripts/faces-walk/cards.json` gives them, and the install verb//! (the database cards installer) gives the owner's database the same//! blocks — so each block must fit its table as the core checks a card, and//! resolve over the walk's invented rows into the places the faces draw.use cotton_core::definitions::TableDefinition;use cotton_core::records::card::{resolve, Around, ResolvedCard};use cotton_core::records::page::Words;use cotton_core::rules::shell_lines::LineSet;use serde_json::{json, Value};use std::path::PathBuf;fn walk() -> PathBuf {    PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").expect("cargo sets CARGO_MANIFEST_DIR")).join("../../scripts/faces-walk")}fn read(path: PathBuf) -> Value {    serde_json::from_str(&std::fs::read_to_string(&path).unwrap_or_else(|_| panic!("{} reads", path.display()))).expect("JSON")}/// The walk's table with the walk's card on it, checked as a card is.fn carded(tool: &str, table: &str) -> TableDefinition {    let mut held = read(walk().join(format!("tools/{tool}/tables/{table}.json")));    held["card"] = read(walk().join("cards.json"))[tool][table].clone();    let definition: TableDefinition = serde_json::from_value(held).expect("the walk's table decodes");    definition.card.as_ref().expect("a card").validate(&definition, "card").expect("the card fits its table");    definition}/// Each invented row of the walk's table, by name, resolved on its card.fn cards_of(tool: &str, table: &TableDefinition, now: &str) -> Vec<(String, ResolvedCard)> {    let now = chrono::DateTime::parse_from_rfc3339(now).unwrap().with_timezone(&chrono::Utc);    let lines = LineSet::shipped("cards").unwrap();    read(walk().join(format!("tools/{tool}/records/{}.json", table.id)))        .as_array()        .expect("rows")        .iter()        .map(|row| {            let data = row.as_object().unwrap();            let card = resolve(table.card.as_ref().unwrap(), table, "r-1", data, "Asia/Kolkata", now, Words::shipped(), &lines, Around::default()).expect("the row's card");            (row["name"].as_str().unwrap().to_string(), card)        })        .collect()}// RULE: a machine's card carries three dials — memory, disk and load, each// the used part and its whole as numbers the face draws — and its facts:// chip, memory, disk, load and coding sessions, each under its label.#[test]fn a_machine_card_draws_three_dials_and_its_facts() {    let machine = carded("machines", "machine");    let cards = cards_of("machines", &machine, "2026-10-23T10:00:00Z");    let (name, card) = &cards[0];    assert_eq!(name, "atlas-mini");    assert_eq!(card.fields["memory_dial"], json!({"used": 23, "total": 64}));    assert_eq!(card.fields["disk_dial"], json!({"used": 345, "total": 926}));    assert_eq!(card.fields["load_dial"], json!({"used": 2.14, "total": 14}));    let labels: Vec<&str> = card.fields["facts"].as_array().unwrap().iter().filter_map(|fact| fact["label"].as_str()).collect();    assert_eq!(labels, ["Chip", "Memory", "Disk", "Load", "Coding sessions"]);    assert!(cards.iter().all(|(_, card)| card.fields.contains_key("memory_dial") && card.fields.contains_key("disk_dial")));    assert_eq!(card.fields["model"], "Mac mini");    assert_eq!(card.fields["date"], "4 min ago", "a recent sample says how long ago");}// RULE: a quota's card says its week's share in words, the whole hours left// until the week resets and the weekday it resets on, on the reader's clock,// and the last readings as numbers for a trend line; a week already reset// says so and names no weekday.#[test]fn a_quota_card_says_hours_left_its_reset_day_and_its_trend() {    let quota = carded("quotas", "quota");    let cards = cards_of("quotas", &quota, "2026-10-23T10:00:00Z");    let (name, card) = &cards[0];    assert_eq!(name, "ada@invented.example");    assert_eq!(card.fields["share"], "62 percent used");    assert_eq!(card.fields["hours_left"], "38 hours left");    assert_eq!(card.fields["resets_on"], "resets Sunday");    assert_eq!(card.fields["trend"], json!([12, 24, 31, 43, 50, 57, 62]));    let (_, reset) = &cards[1];    assert_eq!(reset.fields["hours_left"], "Has reset");    assert!(reset.fields.get("resets_on").is_none());    assert!(reset.fields.get("trend").is_none(), "a quota with no readings draws no line");}// RULE: a subscription's card says its price per period ("/ month"), since// when it runs, whose login it is, its category, and what it has cost —// paid in all, how many charges, the last charge — each under its label; a// cancelled one says when it ended, and a live one says no end.#[test]fn a_subscription_card_says_its_period_since_login_category_and_what_it_cost() {    let subscription = carded("subscriptions", "subscription");    let cards = cards_of("subscriptions", &subscription, "2026-10-23T10:00:00Z");    let (name, card) = &cards[0];    assert_eq!(name, "Streamly");    assert_eq!(card.fields["period"], "/ month");    assert_eq!(card.fields["holder"], "ada@invented.example");    assert_eq!(card.fields["tag"], "Entertainment");    assert_eq!(card.fields["labels"]["started"], "Since");    assert_eq!(card.fields["labels"]["holder"], "Signed in as");    let facts: Vec<(&str, &str)> = card.fields["facts"]        .as_array()        .unwrap()        .iter()        .map(|fact| (fact["label"].as_str().unwrap(), fact["said"].as_str().unwrap()))        .collect();    assert_eq!(facts.iter().map(|(label, _)| *label).collect::<Vec<_>>(), ["Paid in all", "Charges", "Last charged"]);    assert!(card.fields.get("ends").is_none(), "a live subscription has no end");    let (_, weekly) = cards.iter().find(|(name, _)| name == "Veg box").unwrap();    assert_eq!(weekly.fields["period"], "/ week");    let (_, cancelled) = cards.iter().find(|(name, _)| name == "Tunecast").unwrap();    assert_eq!(cancelled.fields["state"], "Cancelled");    assert!(cancelled.fields["ends"].as_str().unwrap().contains("20 May"), "{:?}", cancelled.fields["ends"]);    assert_eq!(cancelled.fields["labels"]["ends"], "Cancelled");}