Cotton code
336 lines · 16.4 KB · RustRaw
use super::*;use crate::rules::sync_status::{Line, SyncWords};/// RULE: every string of every kit line file is one row, and the rows laid/// back over the file give the file again — so a database written with the/// rows says exactly what the kit says, and no line is left compiled-only.#[test]fn every_kit_line_is_a_row_and_the_rows_are_the_file() {    let rows = shipped_rows();    assert!(rows.iter().any(|row| row.id() == "sync.lines.up_to_date"));    assert!(rows.iter().any(|row| row.id() == "sync.ages.now"));    assert!(rows.iter().any(|row| row.id() == "sync.unnamed"));    let mut ids: Vec<String> = rows.iter().map(LineRow::id).collect();    ids.sort();    ids.dedup();    assert_eq!(ids.len(), rows.len(), "one row per line");    for (set, json) in SHIPPED {        let file: Value = serde_json::from_str(json).unwrap();        assert_eq!(resolved(set, &rows), Some(file), "{set}'s rows are its file");        assert_eq!(resolved(set, &[]), Some(serde_json::from_str::<Value>(json).unwrap()), "{set} falls back to the kit");    }    assert_eq!(&SyncWords::of_rows(&rows), SyncWords::shipped());}/// The app's bundled snapshot of the shipped sets, from this crate: a folder/// holding one file per set, so two lanes editing two sets never touch the/// same snapshot file.fn snapshot_dir() -> std::path::PathBuf {    cotton_store::manifest_dir().join("../../apps/loom/Sources/CottonValues/Resources/lines")}/// The kit's line folder, every set's source file.fn kit_dir() -> std::path::PathBuf {    cotton_store::manifest_dir().join("kits/shell/lines")}/// The `.json` file names directly in `dir`, sorted.fn json_names(dir: &std::path::Path) -> Vec<String> {    let mut names: Vec<String> = std::fs::read_dir(dir)        .unwrap_or_else(|error| panic!("{} could not be listed: {error}", dir.display()))        .map(|entry| entry.unwrap().path())        .filter(|path| path.extension().is_some_and(|ext| ext == "json"))        .map(|path| path.file_name().unwrap().to_string_lossy().to_string())        .collect();    names.sort();    names}/// Write the app's snapshot after a kit line file changes:/// cargo test -p cotton-core --lib generate_shipped_lines -- --ignored/// One byte-for-byte copy per kit file; a copy whose kit file is gone is removed.#[test]#[ignore = "generation command writes the app resource; run after a kit line file changes"]fn generate_shipped_lines() {    let (kit, snapshot) = (kit_dir(), snapshot_dir());    std::fs::create_dir_all(&snapshot).expect("the snapshot folder is made");    let sources = json_names(&kit);    for name in &sources {        std::fs::copy(kit.join(name), snapshot.join(name)).expect("a set's copy is written");    }    for name in json_names(&snapshot) {        if !sources.contains(&name) {            std::fs::remove_file(snapshot.join(&name)).expect("a stale copy is removed");        }    }}/// RULE: the app's bundled snapshot (`apps/loom/Sources/CottonValues/Resources/lines/<set>.json`,/// `ShellLines`' words before the core answers) is every kit line file copied/// byte for byte and nothing else, so the fallback never says a word the kit/// does not; one file per set, so a conflict in the snapshot happens only where/// the kit file itself conflicts. The app reads it through `readBundledJSON`/// like the catalogue and opens no line file itself.#[test]fn the_apps_line_snapshot_is_the_kits_sets() {    let (kit, snapshot) = (kit_dir(), snapshot_dir());    let sources = json_names(&kit);    let copies = json_names(&snapshot);    for name in &sources {        let copy = std::fs::read(snapshot.join(name));        assert!(copy.is_ok(), "the app's snapshot has no {name} — regenerate with generate_shipped_lines");        assert!(copy.unwrap() == std::fs::read(kit.join(name)).unwrap(), "the app's {name} is not the kit's — regenerate with generate_shipped_lines");    }    for name in &copies {        assert!(sources.contains(name), "the app's snapshot holds {name}, which no kit file is — regenerate with generate_shipped_lines");    }}/// RULE: a database's row wins over the compiled words; a line it has no row/// for is the kit's, and a row naming no line of the kit is ignored (a/// synthetic rewording, never the owner's words).#[test]fn a_row_rewords_its_line_and_the_kit_fills_the_rest() {    let rows = vec![        LineRow { set: "sync".into(), line: "lines.up_to_date".into(), words: "In step with {with} · {at}".into() },        LineRow { set: "sync".into(), line: "ages.now".into(), words: "this moment".into() },        LineRow { set: "sync".into(), line: "lines.no_such_line".into(), words: "ignored".into() },    ];    let words = SyncWords::of_rows(&rows);    let line = Line::UpToDate { with: Some("Studio Mac".into()), at: 1_000 };    assert_eq!(words.say(&line, 1_000), "In step with Studio Mac · this moment");    assert_eq!(words.lines["sending"], SyncWords::shipped().lines["sending"]);    assert!(!words.lines.contains_key("no_such_line"));}/// THE PICKER (contract 5): a line with plural forms is chosen by its `{n}`/// through CLDR, whether the caller names the object or one of its forms, and/// falls back to `other` for a form the set lacks.#[test]fn the_count_picks_the_plural_form() {    assert_eq!(plural_form("1"), "one");    assert_eq!(plural_form("0"), "other");    assert_eq!(plural_form("2"), "other");    assert_eq!(plural_form("1.5"), "other");    assert_eq!(plural_form("1,204"), "other");    assert_eq!(plural_form("many"), "other");    // A shipped set with no plural forms says its line as written.    let plain = shipped_rows().into_iter().find(|row| row.set == "sync").unwrap();    assert_eq!(resolve("sync", &plain.line, &[], &[("n", "1")]), Some(plain.words.clone()).map(|w| w.replace("{n}", "1")));    // `pick` over an object of forms.    let forms: serde_json::Map<String, Value> =        serde_json::from_str(r#"{"one":"{n} day late","other":"{n} days late"}"#).unwrap();    assert_eq!(pick(&forms, "1"), Some("{n} day late"));    assert_eq!(pick(&forms, "3"), Some("{n} days late"));    let only_other: serde_json::Map<String, Value> = serde_json::from_str(r#"{"other":"{n} days"}"#).unwrap();    assert_eq!(pick(&only_other, "1"), Some("{n} days"));}/// RULE: a count is said in the kit's plural forms wherever it is said. An/// opened card's related list (`related` with a `column`, counted on the/// card's file index) is said in its table's own line, one thread and N/// threads, for every related list of every kit; a list whose table has no/// line is said beside its own label ("Stories: 1"), which has no singular/// to say, so no line puts one before a plural.////// WHY: Cotton 348's walk — "1 threads" on a person's file index: the/// fallback line said `{n} {label}` for one as for many, the label plural.#[test]fn every_related_count_of_every_kit_says_one_in_the_singular() {    let kits = cotton_store::manifest_dir().join("kits");    let mut counted = 0;    for kit in json_names_in_dirs(&kits) {        let definition: Value = serde_json::from_slice(&std::fs::read(&kit).unwrap()).unwrap();        for related in definition["related"].as_array().into_iter().flatten().filter(|related| related["column"].is_string()) {            let table = related["table"].as_str().unwrap();            let line = format!("opened.related.{table}");            let one = resolve("cards", &line, &[], &[("n", "1")]).unwrap_or_else(|| panic!("{}: no `cards.{line}`", kit.display()));            let two = resolve("cards", &line, &[], &[("n", "2")]).unwrap();            assert_ne!(one.replacen('1', "2", 1), two, "{line}: one is said as many");            assert!(one.starts_with("1 ") && two.starts_with("2 "), "{line}: {one} / {two}");            counted += 1;        }    }    assert!(counted >= 6, "{counted} related counts");    assert_eq!(resolve("cards", "opened.related.thread", &[], &[("n", "1")]).as_deref(), Some("1 thread"));    assert_eq!(resolve("cards", "opened.related.thread", &[], &[("n", "4")]).as_deref(), Some("4 threads"));    assert_eq!(resolve("cards", "opened.related.labelled", &[], &[("label", "Stories"), ("n", "1")]).as_deref(), Some("Stories: 1"));    assert_eq!(resolve("cards", "opened.related.count", &[], &[("label", "threads"), ("n", "1")]), None, "removed: it said 1 threads");}/// Every table file of every kit (`kits/<kit>/tables/*.json`).fn json_names_in_dirs(kits: &std::path::Path) -> Vec<std::path::PathBuf> {    let mut files = Vec::new();    for kit in std::fs::read_dir(kits).unwrap().map(|entry| entry.unwrap().path()) {        let tables = kit.join("tables");        if tables.is_dir() {            files.extend(json_names(&tables).into_iter().map(|name| tables.join(name)));        }    }    files.sort();    files}/// Numbers are grouped by CLDR, never by a hand-written comma.#[test]fn a_number_is_grouped() {    assert_eq!(number(7), "7");    assert_eq!(number(1204), "1,204");    assert_eq!(number(-1_200_000), "-1,200,000");}/// Lines written before the picker say their plural as `one`/`many` (bin,/// empty, the tool definitions' figures, and the owner's database holds them/// so): a count that is not one says the `many` words, never nothing.#[test]fn a_one_many_line_says_many_for_three() {    let forms: serde_json::Map<String, Value> =        serde_json::from_str(r#"{"one":"{n} record","many":"{n} records"}"#).unwrap();    assert_eq!(pick(&forms, "3"), Some("{n} records"));    assert_eq!(pick(&forms, "1"), Some("{n} record"));    let bin = shipped_rows().into_iter().find(|row| row.set == "bin" && row.line.ends_with(".many")).expect("bin says one/many");    let object = bin.line.trim_end_matches(".many");    assert_eq!(resolve("bin", object, &[], &[("n", "3")]), Some(bin.words.replace("{n}", "3")));}/// A map (named in its file's `maps`) takes a row for a key the kit lacks;/// any other path the kit lacks is still ignored.#[test]fn a_map_takes_new_keys_and_fixed_lines_do_not() {    let row = |line: &str| LineRow { set: "money".into(), line: line.into(), words: "KSh".into() };    let file = resolved("money", &[row("symbols.KES"), row("amount.new_mark"), row("statement.flows.extra")]).unwrap();    assert_eq!(file["symbols"]["KES"], "KSh");    assert!(file["amount"].get("new_mark").is_none());    assert_eq!(resolve("money", "symbols.KES", &[row("symbols.KES")], &[]), Some("KSh".into()));    assert_eq!(number_grouped(1_234_567, "en-IN"), "12,34,567");    assert_eq!(number_grouped(1_234_567, "not a locale"), "1,234,567");}/// RULE (the transforms contract, 22 Oct 2026): every set is shipped. A file/// in `kits/shell/lines/` with no `SHIPPED` entry is never written to a/// database, never resolved and never in the app's snapshot, so every key in/// it says its raw path; an entry must be that file's bytes under its own id/// (`"id"` in the file is the set's name). The snapshot follows `SHIPPED`/// (`the_apps_line_snapshot_is_the_kits_sets`), so this closes the loop from/// the directory. A new set goes at the END of `SHIPPED`, never reordered.////// And no key twice in one object: serde_json keeps the last of two, so the/// first's lines vanish without a word — `dates.json` held two `"ago"`/// objects and `dates.ago.now` said nothing until the line-key guard caught it.#[test]fn every_kit_line_file_is_shipped_once_under_its_own_id() {    let dir = cotton_store::manifest_dir().join("kits/shell/lines");    let mut files: Vec<(String, String)> = std::fs::read_dir(&dir)        .expect("kits/shell/lines")        .map(|entry| entry.unwrap().path())        .filter(|path| path.extension().is_some_and(|ext| ext == "json"))        .map(|path| (path.file_stem().unwrap().to_string_lossy().to_string(), std::fs::read_to_string(&path).unwrap()))        .collect();    files.sort();    let shipped: Vec<&str> = SHIPPED.iter().map(|(set, _)| *set).collect();    for (set, text) in &files {        let entry = SHIPPED.iter().find(|(id, _)| id == set);        assert!(entry.is_some(), "kits/shell/lines/{set}.json has no SHIPPED entry — add (\"{set}\", include_str!(..)) at the end");        assert_eq!(entry.unwrap().1, text.as_str(), "SHIPPED's {set} is not kits/shell/lines/{set}.json");        let file: Value = serde_json::from_str(text).unwrap();        assert_eq!(file["id"], *set, "kits/shell/lines/{set}.json names another id");        if let Err(error) = serde_json::from_str::<NoDuplicateKeys>(text) {            panic!("kits/shell/lines/{set}.json: {error}");        }    }    for set in &shipped {        assert!(files.iter().any(|(id, _)| id == set), "SHIPPED names {set}, which has no file in kits/shell/lines");    }    let mut unique = shipped.clone();    unique.sort();    unique.dedup();    assert_eq!(unique.len(), shipped.len(), "a set is in SHIPPED twice");}/// Any JSON, refused when one object names a key twice.struct NoDuplicateKeys;impl<'de> serde::Deserialize<'de> for NoDuplicateKeys {    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {        deserializer.deserialize_any(NoDuplicateKeysVisitor)    }}struct NoDuplicateKeysVisitor;impl<'de> serde::de::Visitor<'de> for NoDuplicateKeysVisitor {    type Value = NoDuplicateKeys;    fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {        f.write_str("JSON")    }    fn visit_map<A: serde::de::MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {        let mut seen = std::collections::BTreeSet::new();        while let Some(key) = map.next_key::<String>()? {            if !seen.insert(key.clone()) {                return Err(serde::de::Error::custom(format!("the key \"{key}\" is in one object twice")));            }            map.next_value::<NoDuplicateKeys>()?;        }        Ok(NoDuplicateKeys)    }    fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {        while seq.next_element::<NoDuplicateKeys>()?.is_some() {}        Ok(NoDuplicateKeys)    }    fn visit_str<E>(self, _: &str) -> Result<Self::Value, E> {        Ok(NoDuplicateKeys)    }    fn visit_bool<E>(self, _: bool) -> Result<Self::Value, E> {        Ok(NoDuplicateKeys)    }    fn visit_i64<E>(self, _: i64) -> Result<Self::Value, E> {        Ok(NoDuplicateKeys)    }    fn visit_u64<E>(self, _: u64) -> Result<Self::Value, E> {        Ok(NoDuplicateKeys)    }    fn visit_f64<E>(self, _: f64) -> Result<Self::Value, E> {        Ok(NoDuplicateKeys)    }    fn visit_unit<E>(self) -> Result<Self::Value, E> {        Ok(NoDuplicateKeys)    }}/// A database made before a kit line was reworded holds the kit's old words/// as its row (every database is written with the kit's lines, add-only): the/// owner's Comms said "Chat never shows when you were last here." a day after/// the kit said Comms (1a5250db85). A row holding the kit's own earlier words/// says the kit's present ones; a person's rewording still wins.#[test]fn a_row_holding_the_kits_earlier_words_says_the_kits_present_ones() {    let row = |line: &str, words: &str| LineRow { set: "chat".into(), line: line.into(), words: words.into() };    let rows = [        row("app.you.last_seen", "Chat never shows when you were last here."),        row("app.you.notifications_line", "Messages and calls, even while Chat is closed"),        row("app.you.read_receipts", "Seen ticks"),    ];    let set = LineSet::of_rows("chat", &rows).unwrap();    assert_eq!(set.say("app.you.last_seen", &[]).as_deref(), Some("Comms never shows when you were last here."));    assert_eq!(set.say("app.you.notifications_line", &[]).as_deref(), Some("Messages and calls, even while Comms is closed"));    assert_eq!(set.say("app.you.read_receipts", &[]).as_deref(), Some("Seen ticks"), "a person's own words stay");}/// Every earlier wording names a line the kit ships, and none is that line's present words.#[test]fn every_earlier_wording_names_a_shipped_line_and_is_not_its_present_words() {    let shipped: std::collections::HashMap<String, String> = shipped_rows().into_iter().map(|row| (row.id(), row.words)).collect();    let file: Value = serde_json::from_str(REWORDED).unwrap();    let lines = file["lines"].as_object().expect("reworded.json has lines");    assert!(lines.len() > 100, "{} lines", lines.len());    for (id, earlier) in lines {        let now = shipped.get(id).unwrap_or_else(|| panic!("{id} is not a line the kit ships"));        for words in earlier.as_array().unwrap() {            assert_ne!(words.as_str(), Some(now.as_str()), "{id}: its present words are not earlier ones");        }    }}