Cotton code
60 lines · 2.4 KB · RustRaw
//! The kit's lines, said by the rules themselves so the phone and the Worker//! say them in the same words. The files are the kit's own//! (`cotton-core/kits/shell/lines/<set>.json`, compiled in); a piece the kit//! has no line for is said as written, as cotton-core's `refusal_words` does.use std::sync::OnceLock;use serde_json::Value;/// The kit line sets the rules say, compiled in.fn set(id: &str) -> &'static Value {    static REFUSAL: OnceLock<Value> = OnceLock::new();    static CONVERSATION: OnceLock<Value> = OnceLock::new();    let (cell, text) = match id {        "refusal" => (&REFUSAL, include_str!("../../cotton-core/kits/shell/lines/refusal.json")),        "conversation" => (&CONVERSATION, include_str!("../../cotton-core/kits/shell/lines/conversation.json")),        _ => return &Value::Null,    };    cell.get_or_init(|| serde_json::from_str(text).unwrap_or(Value::Null))}/// `<set>.<key>` (a dotted path) with each `{name}` filled; a key the kit has/// no line for is said as its own path.pub fn resolve(set_id: &str, line_path: &str, fills: &[(&str, &str)]) -> String {    let Some(words) = set(set_id).pointer(&format!("/{}", line_path.replace('.', "/"))).and_then(Value::as_str) else {        return format!("{set_id}.{line_path}");    };    let mut words = words.to_string();    for (name, value) in fills {        words = words.replace(&format!("{{{name}}}"), value);    }    words}/// `refusal.definition.<piece>` with each `{name}` filled.pub fn refusal(piece: &str, fills: &[(&str, &str)]) -> String {    let Some(words) = set("refusal").get("definition").and_then(|set| set.get(piece)).and_then(Value::as_str) else {        return piece.to_string();    };    let mut words = words.to_string();    for (name, value) in fills {        words = words.replace(&format!("{{{name}}}"), value);    }    words}#[cfg(test)]mod tests {    #[test]    fn a_piece_is_said_as_the_kit_line_with_its_fills() {        assert_eq!(super::refusal("record_has_no_column", &[("key", "fee")]), "record has no column fee");        assert_eq!(super::refusal("no such piece", &[]), "no such piece");    }    #[test]    fn a_key_is_said_as_its_kit_line_or_its_own_path() {        assert_eq!(super::resolve("conversation", "preview.poll", &[("question", "Lunch?")]), "Poll · Lunch?");        assert_eq!(super::resolve("conversation", "preview.nothing", &[]), "conversation.preview.nothing");    }}