Files
LLeMbas-Android/scripts/fetch-tokens.py
T
HomerandClaude Opus 5.5 052d0a3894 Pin the server contract and tokens to LLeMbas 2.0 (server dev f5b3dbb)
The contract moves from v1.7.0 to the server's dev at f5b3dbb965823ade: event_canvas.json is
gone (2.0 has no canvas) and the chat detail no longer carries knowledge_bases. The app modelled
neither, so no model changes; ContractTest now says the canvas fixture is absent and that a
canvas frame from an older stream is ignored.

Tokens from the same commit: only --selection is new among the colours, and it is now in the
palette and used for selected text, as on the web UI. CI also runs on pushes to dev, where 2.0
is built.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 04:30:38 +00:00

129 lines
4.9 KiB
Python
Executable File

#!/usr/bin/env python3
"""The server's colours, as the app's Compose theme.
scripts/fetch-tokens.py <server-ref> read tokens.css at that ref (a tag such as v1.7.0),
write Tokens.kt and tokens.lock.json
scripts/fetch-tokens.py verify: Tokens.kt matches tokens.lock.json
The server is a git checkout, LLeMbas beside this repository by default (LEMBAS_SERVER names
another). Only the colour tokens of the two themes are read -- `moria` (declared on `:root`) and
`shire` -- and each becomes a `Palette` in Kotlin. The lock records the ref, the commit and the
SHA-256 of the generated file, as LLeMbas Desktop's `tokens.lock.json` does: the file in the tree
says which server version the look comes from, and CI refuses a copy that drifted.
"""
from __future__ import annotations
import hashlib
import json
import os
import re
import subprocess
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
SERVER = Path(os.environ.get("LEMBAS_SERVER", ROOT.parent / "LLeMbas"))
SOURCE = "src/lembas/web/static/css/tokens.css"
OUT = ROOT / "app/src/main/java/eu/llembas/android/ui/theme/Tokens.kt"
LOCK = ROOT / "tokens.lock.json"
# The tokens the app uses, in the order they are written. A token missing from a theme is an
# error rather than a default: a palette that silently fell back would look right and be wrong.
NAMES = (
"bg", "bg-sunken", "surface", "surface-raised", "surface-hover", "surface-active",
"border", "border-strong", "ink", "ink-muted", "ink-faint", "ink-inverse",
"accent", "accent-hover", "accent-ink", "accent-soft", "selection", "leaf", "danger", "danger-soft",
"success", "success-soft", "warning", "warning-soft", "bubble-user", "code-bg", "code-border",
)
THEMES = {
"moria": r':root,\s*:root\[data-theme="moria"\]\s*\{',
"shire": r':root\[data-theme="shire"\],\s*:root\[data-base="shire"\]\s*\{',
}
def sha(path: Path) -> str:
return hashlib.sha256(path.read_bytes()).hexdigest()
def block(css: str, opener: str) -> str:
match = re.search(opener, css)
if not match:
sys.exit(f"fetch-tokens: no block {opener!r} in {SOURCE}")
depth, start = 1, match.end()
for i in range(start, len(css)):
depth += {"{": 1, "}": -1}.get(css[i], 0)
if depth == 0:
return css[start:i]
sys.exit("fetch-tokens: unbalanced braces")
def argb(value: str) -> str:
value = value.strip()
if m := re.fullmatch(r"#([0-9a-fA-F]{6})", value):
return f"0xFF{m.group(1).upper()}"
if m := re.fullmatch(r"rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*([\d.]+)\s*\)", value):
r, g, b = (int(m.group(i)) for i in (1, 2, 3))
a = round(float(m.group(4)) * 255)
return f"0x{a:02X}{r:02X}{g:02X}{b:02X}"
sys.exit(f"fetch-tokens: not a colour this script reads: {value!r}")
def camel(name: str) -> str:
head, *rest = name.split("-")
return head + "".join(p.capitalize() for p in rest)
def generate(css: str, ref: str) -> str:
lines = [
"// Generated by scripts/fetch-tokens.py from the LLeMbas server's tokens.css at "
f"{ref}. Do not edit.",
"package eu.llembas.android.ui.theme",
"",
"import androidx.compose.ui.graphics.Color",
"",
"data class Palette(",
*[f" val {camel(n)}: Color," for n in NAMES],
")",
"",
]
for theme, opener in THEMES.items():
body = block(css, opener)
values = dict(re.findall(r"--([a-z0-9-]+)\s*:\s*([^;]+);", body))
missing = [n for n in NAMES if n not in values]
if missing:
sys.exit(f"fetch-tokens: {theme} has no {', '.join(missing)}")
lines.append(f"val {theme.capitalize()} = Palette(")
lines += [f" {camel(n)} = Color({argb(values[n])}L)," for n in NAMES]
lines += [")", ""]
return "\n".join(lines)
def main() -> None:
if len(sys.argv) == 1:
lock = json.loads(LOCK.read_text())
if sha(OUT) != lock["sha256"]:
sys.exit(f"fetch-tokens: {OUT.name} does not match {LOCK.name} (server {lock['tag']})")
print(f"fetch-tokens: {OUT.name} matches {LOCK.name} (server {lock['tag']})")
return
ref = sys.argv[1]
commit = subprocess.run(
["git", "-C", str(SERVER), "rev-parse", "--verify", f"{ref}^{{commit}}"],
capture_output=True, text=True, check=True,
).stdout.strip()
css = subprocess.run(
["git", "-C", str(SERVER), "show", f"{commit}:{SOURCE}"],
capture_output=True, text=True, check=True,
).stdout
OUT.parent.mkdir(parents=True, exist_ok=True)
OUT.write_text(generate(css, ref), encoding="utf-8")
LOCK.write_text(
json.dumps({"tag": ref, "commit": commit, "sha256": sha(OUT)}, indent=2) + "\n"
)
print(f"fetch-tokens: wrote {OUT.relative_to(ROOT)} from {ref} ({commit[:12]})")
if __name__ == "__main__":
main()