A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
tools: PR content summary, records a branch adds, removes or re-dates (fixes #325) (#328)
agamrafaeli-instinctc7756eae3360
diff --git a/docs/dev-setup.md b/docs/dev-setup.mdindex 79f9fee25..8fb5feac7 100644--- a/docs/dev-setup.md+++ b/docs/dev-setup.md@@ -25,6 +25,7 @@ Unity, a Unity licence and macOS are only needed for `unity/`. The sim, the cont| GDD feature sections (also run by the policy checker tests) | `uv run scripts/oss/gdd_lint.py` | Repo policy || Every event by date, with era, anchor and review status | `uv run scripts/event_timeline.py [--status draft]` | none (helper) || Every content source with its check date and age (`--older-than DAYS`) | `uv run scripts/source_report.py` | none (helper) |+| Content records a branch adds, removes or re-dates (paste into the PR) | `uv run scripts/pr_content_summary.py [origin/main]` | none (helper) || Dead relative links in Markdown files (also run by the policy checker tests) | `uv run scripts/oss/md_links.py` | Repo policy || New event file (skeleton with every required field) | `uv run scripts/new_event.py <id> [--from D] [--to D]` | none (helper) || Changelog line | `uv run scripts/oss/changelog_check.py --base origin/main` | Changelog |diff --git a/scripts/oss/tests/test_pr_content_summary.py b/scripts/oss/tests/test_pr_content_summary.pynew file mode 100644index 000000000..a00223b3a--- /dev/null+++ b/scripts/oss/tests/test_pr_content_summary.py@@ -0,0 +1,62 @@+"""PR content summary (#325): added, removed and re-dated records against a base, and the no-change line."""+import importlib.util+import re+from pathlib import Path++from conftest import commit_all, git++ROOT = Path(__file__).resolve().parents[3]+SPEC = importlib.util.spec_from_file_location('pr_content_summary', ROOT / 'scripts/pr_content_summary.py')+m = importlib.util.module_from_spec(SPEC)+SPEC.loader.exec_module(m)++MODEL = "indicators:\n - { id: morale }\n - { id: food }\npolicies:\n - { id: rationing }\n"+++def test_added_removed_redated(make_repo, capsys):+ root = make_repo({"content/model.yaml": MODEL, "content/events/a.yaml": "id: a\nfrom: 1948-06-01\n",+ "content/events/b.yaml": "id: b\nfrom: 1949-01-01\nto: 1949-02-01\n"})+ base = commit_all(root, "base")+ (root / "content/events/a.yaml").write_text("id: a\nfrom: 1948-06-01\nto: 1948-07-01\n")+ (root / "content/events/b.yaml").unlink()+ (root / "content/events/c.yaml").write_text("id: c\nfrom: 1950-01-01\n")+ (root / "content/model.yaml").write_text(MODEL.replace("{ id: food }", "{ id: food, from: 1949-01-01 }")+ + " - { id: maabarot, from: 1948-08-01 }\n")+ commit_all(root, "change")+ assert m.main([base, "--root", str(root)]) == 0+ out = capsys.readouterr().out+ assert "**Added** (2)" in out and "- `event:c` (1950-01-01 to open)" in out and "- `policy:maabarot` (1948-08-01 to open)" in out+ assert "**Removed** (1)" in out and "- `event:b` (1949-01-01 to 1949-02-01)" in out+ assert "`event:a`: 1948-06-01 to open -> 1948-06-01 to 1948-07-01" in out+ assert "`indicator:food`: - to open -> 1949-01-01 to open" in out+++def test_no_change_and_bad_base(make_repo, capsys):+ root = make_repo({"content/model.yaml": MODEL, "content/events/a.yaml": "id: a\nfrom: 1948-06-01\n"})+ base = commit_all(root, "base")+ assert m.main([base, "--root", str(root)]) == 0+ assert capsys.readouterr().out.strip() == "No content records changed."+ assert m.main(["nope", "--root", str(root)]) == 2+++def test_main_moving_on_is_not_this_branchs_change(make_repo, capsys):+ root = make_repo({"content/model.yaml": MODEL, "content/events/a.yaml": "id: a\nfrom: 1948-06-01\n"})+ commit_all(root, "base")+ git(root, "checkout", "-q", "-b", "topic")+ (root / "content/events/t.yaml").write_text("id: t\nfrom: 1949-01-01\n")+ commit_all(root, "topic adds t")+ git(root, "checkout", "-q", "main")+ (root / "content/events/n.yaml").write_text("id: n\nfrom: 1950-01-01\n")+ commit_all(root, "main adds n")+ git(root, "checkout", "-q", "topic")+ assert m.main(["main", "--root", str(root)]) == 0+ out = capsys.readouterr().out+ assert "**Added** (1)" in out and "`event:t`" in out and "event:n" not in out and "Removed" not in out+++def test_lists_are_the_sims_dated_model_records():+ cs = (ROOT / "sim/Statecraft.Sim/Content.cs").read_text()+ view = cs[cs.index("class ModelView"):]+ view = view[:view.index("\n }")]+ props = re.findall(r"IReadOnlyList<\w+> (\w+) \{ get; \}", view)+ assert [re.sub(r"(?<!^)([A-Z])", r"_\1", p).lower() for p in props] == m.LISTSdiff --git a/scripts/pr_content_summary.py b/scripts/pr_content_summary.pynew file mode 100644index 000000000..7f3fa9a12--- /dev/null+++ b/scripts/pr_content_summary.py@@ -0,0 +1,86 @@+#!/usr/bin/env python3+# /// script+# requires-python = ">=3.10"+# dependencies = ["pyyaml==6.0.3"]+# ///+"""Markdown summary of the game records a branch adds, removes or re-dates (#325):+`uv run scripts/pr_content_summary.py [BASE]` (BASE defaults to origin/main; the branch is HEAD).++Compares committed content only, against the merge base (BASE...HEAD), like the changelog check. Covers+content/events/*.yaml (by id) and the dated record lists in content/model.yaml (indicators, policies, effects,+situations, voter_groups, actors). A record is "re-dated" when its `from` or `to` changed. Prints nothing but "No content records changed." when there is no difference."""+import argparse+import subprocess+import sys+from pathlib import Path++import yaml++ROOT = Path(__file__).resolve().parents[1]+# The dated model records: the sim's ModelView (sim/Statecraft.Sim/Content.cs; a test keeps them equal).+LISTS = ["indicators", "policies", "effects", "situations", "voter_groups", "actors"]+++def git(root: Path, *args: str) -> str:+ r = subprocess.run(["git", "-C", str(root), *args], capture_output=True, text=True)+ return r.stdout if r.returncode == 0 else ""+++def records(root: Path, ref: str) -> dict[str, dict]:+ """{ "event:id" or "policy:id": {"from": .., "to": ..} } as committed at ref."""+ out: dict[str, dict] = {}+ for path in git(root, "ls-tree", "-r", "--name-only", ref, "content/events/").split():+ if path.endswith(".yaml"):+ e = yaml.safe_load(git(root, "show", f"{ref}:{path}")) or {}+ if "id" in e:+ out[f"event:{e['id']}"] = {"from": str(e.get("from", "")), "to": str(e.get("to", ""))}+ model = yaml.safe_load(git(root, "show", f"{ref}:content/model.yaml")) or {}+ for key in LISTS:+ for r in model.get(key) or []:+ if isinstance(r, dict) and "id" in r:+ out[f"{key.rstrip('s') if key != 'policies' else 'policy'}:{r['id']}"] = {+ "from": str(r.get("from", "")), "to": str(r.get("to", ""))}+ return out+++def summarize(old: dict[str, dict], new: dict[str, dict]) -> str:+ added = sorted(set(new) - set(old))+ removed = sorted(set(old) - set(new))+ redated = sorted(k for k in set(old) & set(new) if old[k] != new[k])+ if not (added or removed or redated):+ return "No content records changed."++ def win(r: dict) -> str:+ return f" ({r['from'] or '-'} to {r['to'] or 'open'})" if r["from"] or r["to"] else ""++ lines = []+ for title, keys, src in (("Added", added, new), ("Removed", removed, old)):+ if keys:+ lines += [f"**{title}** ({len(keys)})"] + [f"- `{k}`{win(src[k])}" for k in keys] + [""]+ if redated:+ lines += [f"**Re-dated** ({len(redated)})"] + [+ f"- `{k}`: {old[k]['from'] or '-'} to {old[k]['to'] or 'open'} -> {new[k]['from'] or '-'} to {new[k]['to'] or 'open'}"+ for k in redated]+ return "\n".join(lines).rstrip()+++def main(argv: list[str] | None = None) -> int:+ p = argparse.ArgumentParser(description=__doc__.split("\n")[0])+ p.add_argument("base", nargs="?", default="origin/main")+ p.add_argument("--root", type=Path, default=ROOT)+ a = p.parse_args(argv)+ if not git(a.root, "rev-parse", "--verify", "--quiet", f"{a.base}^{{commit}}").strip():+ print(f"base ref not found: {a.base} (try: git fetch origin)", file=sys.stderr)+ return 2+ # Against the merge base, as `git diff BASE...HEAD` and the changelog check do: what main gained since the branch+ # started is not this branch's change.+ fork = git(a.root, "merge-base", a.base, "HEAD").strip()+ if not fork:+ print(f"no merge base between {a.base} and HEAD", file=sys.stderr)+ return 2+ print(summarize(records(a.root, fork), records(a.root, "HEAD")))+ return 0+++if __name__ == "__main__":+ sys.exit(main())