Cotton code
63 lines · 2.2 KB · RustRaw
//! Swift literals, and the header every generated file carries.//!//! Small, and worth its own module: these functions are the only place this//! binary decides how a value becomes Swift, and two of them are judgements a//! rewrite could get wrong while every byte still matched./// Who writes the generated files, and how a reader regenerates them.////// Named once rather than spelled at each renderer so the sentence cannot come/// to differ between the Mac's file and the phone's — which is exactly what/// happened while `rust-gen.ts` and `ios-gen.ts` were two scripts writing two/// halves of one design system.pub const GENERATED_BY: &str = "cotton-gen";/// The command a reader runs. A pnpm script rather than a bare `cargo run`/// because that is what CI runs, and because locally it takes the machine-wide/// build lock every heavy build on this Mac takes.pub const REGENERATE_WITH: &str = "pnpm gen:design";/// The command CI runs.pub const CHECK_WITH: &str = "gen:design:check";/// A Swift string literal.pub fn swift_str(value: &str) -> String {    let mut out = String::from("\"");    for ch in value.chars() {        match ch {            '\\' => out.push_str("\\\\"),            '"' => out.push_str("\\\""),            '\n' => out.push_str("\\n"),            '\t' => out.push_str("\\t"),            _ => out.push(ch),        }    }    out.push('"');    out}/// A Swift raw string literal (`#"…"#`), for a regular expression whose/// backslashes are its own.////// A pattern containing `"#` would end the literal early — no declared pattern/// does, and this refuses rather than emitting Swift that will not compile.pub fn swift_raw(value: &str) -> Result<String, String> {    if value.contains("\"#") {        return Err(format!(            "cotton-gen: pattern contains '\"#' and cannot be a raw literal: {value}"        ));    }    Ok(format!("#\"{value}\"#"))}/// The two-line header every generated Swift file opens with.pub fn generated_header(source: &str) -> String {    format!(        "// GENERATED by `{GENERATED_BY}` from `{source}` — do not edit by hand.\n\         // Run `{REGENERATE_WITH}`; `{CHECK_WITH}` guards drift in CI."    )}#[cfg(test)]#[path = "swift_tests.rs"]mod tests;