Cotton code
49 lines · 1.9 KB · PythonRaw
#!/usr/bin/env python3"""Write apps/loom/Sources/CottonPaper/Theme/ThemeScaleKeys.swift: one enum caseper token (`scale.tokens`) the shipped paper theme carries (crates/cotton-core/kits/shell/themes/paper.json), so a face reads `theme.scale[.cardKeyCentre]` — a name thecompiler checks — and never spells a number of its own.    python3 scripts/gen-theme-keys/gen.py          # write    python3 scripts/gen-theme-keys/gen.py --check  # exit 1 when the file is staleRun it after a key is added to the shipped themes. `ThemeScaleKeyTests` holds theenum and both shipped themes to the same key set."""import jsonimport pathlibimport sysROOT = pathlib.Path(__file__).resolve().parents[2]THEME = ROOT / "crates/cotton-core/kits/shell/themes/paper.json"OUT = ROOT / "apps/loom/Sources/CottonPaper/Theme/ThemeScaleKeys.swift"def camel(key: str) -> str:    head, *rest = key.split("_")    return head + "".join(part[:1].upper() + part[1:] for part in rest)def render() -> str:    keys = sorted(json.loads(THEME.read_text())["scale"]["tokens"])    lines = [        "// GENERATED by `scripts/gen-theme-keys/gen.py` from the shipped paper theme's",        "// `scale.tokens` — do not edit by hand; run the script after a token is added to",        "// `crates/cotton-core/kits/shell/themes/*.json`.",        "",        "extension ThemeScale {",        "    /// Every token the theme's `scale.tokens` carries, by its",        "    /// row spelling. Read one with `theme.scale[.key]`.",        "    public enum Key: String, CaseIterable, Sendable {",    ]    lines += [f'        case {camel(key)} = "{key}"' for key in keys]    lines += ["    }", "}", ""]    return "\n".join(lines)if __name__ == "__main__":    text = render()    if "--check" in sys.argv:        sys.exit(0 if OUT.exists() and OUT.read_text() == text else 1)    OUT.write_text(text)    print(f"wrote {OUT.relative_to(ROOT)}")