Skip to content

A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.

4.6 KB
Raw Blame
# /// script
# requires-python = ">=3.11"
# dependencies = ["pyyaml==6.0.3"]
# ///
"""Bakes content/map/localities_1948.yaml (the sourced, human-edited source of truth) into
content/map/localities_1948.tsv, the compact runtime form the player reads at boot (Localities.ParseRuntime in Unity).

The boot budget is the reason (docs/visual-v1.md, "Boot"): scanning the 176k-character YAML cost about 170 ms of the
map build at cpu 4. The runtime file keeps only the fields the map draws and checks, one row per line, tab-separated:

  place  id name name_he today today_he lon lat type landmark mixed population status checked sources
  camp   subdistrict population status checked sources

`name_he` is the 1948 Hebrew name, empty where the YAML has none (#558; its sources stay in the YAML); `today` and
`today_he` are empty for a place with no living successor; `mixed` is 1 for a mixed locality (kind mixed_locality);
`sources` is the row's number of sources (the URLs stay in the YAML). Lines starting with '#' are
comments. No field may hold a tab, a carriage return or a newline: the bake refuses such a row, naming it.

Usage: uv run tools/localities_bake.py [--check]
--check exits 1 when the committed runtime file differs from a fresh bake (pytest runs the same comparison:
tools/tests/test_localities.py).
"""
import argparse
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))  # under python -I the script's folder is not on sys.path
import yaml12  # noqa: E402


ROOT = Path(__file__).resolve().parents[1]
SOURCE = ROOT / "content" / "map" / "localities_1948.yaml"
RUNTIME = ROOT / "content" / "map" / "localities_1948.tsv"
PLACE_COLUMNS = ["place", "id", "name", "name_he", "today", "today_he", "lon", "lat", "type", "landmark", "mixed",
                 "population", "status", "checked", "sources"]
CAMP_COLUMNS = ["camp", "subdistrict", "population", "status", "checked", "sources"]


def _field(value, where: str) -> str:
    text = "" if value is None else str(value)
    if any(c in text for c in "\t\r\n"):
        raise ValueError(f"{SOURCE.name}: {where}: a field holds a tab or a line break: {text!r}")
    return text


def _number(value, where: str) -> str:
    if isinstance(value, bool) or not isinstance(value, (int, float)):
        raise ValueError(f"{SOURCE.name}: {where}: {value!r} is not a number")
    return repr(float(value)) if isinstance(value, float) else str(value)


def bake(text: str) -> str:
    """The runtime file for the YAML text: deterministic, so a fresh bake equals the committed file."""
    doc = yaml12.load(text)
    out = [
        "# Generated by tools/localities_bake.py from localities_1948.yaml. Do not edit: edit the YAML and rerun the tool.",
        "# The runtime form the map reads at boot (presentation only, outside the content hash). Sources: the YAML.",
        "#" + "\t".join(PLACE_COLUMNS),
        "#" + "\t".join(CAMP_COLUMNS),
    ]
    for p in doc["places"]:
        where = f"place '{p.get('id')}'"
        today = p.get("today") or {}
        row = ["place", p["id"], p["name"], p.get("name_he") or "", today.get("name", ""), today.get("name_he", ""),
               _number(p["lon"], where), _number(p["lat"], where), p["type"], p["landmark"],
               "1" if p.get("kind") == "mixed_locality" else "0", _number(p["population"], where),
               p["status"], p["checked"], str(len(p.get("sources") or []))]
        out.append("\t".join(_field(v, where) for v in row))
    for c in doc.get("encampments") or []:
        where = f"encampments '{c.get('subdistrict')}'"
        row = ["camp", c["subdistrict"], _number(c["population"], where), c["status"], c["checked"],
               str(len(c.get("sources") or []))]
        out.append("\t".join(_field(v, where) for v in row))
    return "\n".join(out) + "\n"


def main() -> int:
    ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    ap.add_argument("--check", action="store_true", help="fail when the committed runtime file is stale")
    args = ap.parse_args()
    fresh = bake(SOURCE.read_text(encoding="utf-8"))
    if args.check:
        current = RUNTIME.read_text(encoding="utf-8") if RUNTIME.exists() else ""
        if current != fresh:
            print(f"{RUNTIME.relative_to(ROOT)} is stale: run uv run tools/localities_bake.py", file=sys.stderr)
            return 1
        print(f"{RUNTIME.relative_to(ROOT)} is fresh")
        return 0
    RUNTIME.write_text(fresh, encoding="utf-8", newline="\n")
    print(f"wrote {RUNTIME.relative_to(ROOT)}: {len(fresh)} characters, {fresh.count(chr(10)) - 4} rows")
    return 0


if __name__ == "__main__":
    sys.exit(main())