A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
Tools: a malformed YAML file is a one-line error naming the file (part 1 of #2532) (#3008)
Eyal Golan0e2c3216fef3
diff --git a/tools/review_queue.py b/tools/review_queue.pyindex 33f5175ca..6b8ff86f9 100644--- a/tools/review_queue.py+++ b/tools/review_queue.py@@ -57,6 +57,7 @@ import yamlsys.path.insert(0, str(Path(__file__).resolve().parent)) # under python -I the script's folder is not on sys.pathimport review_record # noqa: E402+import yaml12 # noqa: E402ROOT = Path(__file__).resolve().parents[1]PAGE = ROOT / "docs" / "review-queue.md"@@ -200,9 +201,18 @@ def signed_rows(text: str) -> list[SignedRow]:return out+def _compose(text: str, rel: str):+ """The YAML node tree of a file's text; text that is not YAML is a QueueError naming the file and line (#2532)."""+ try:+ return yaml.compose(text)+ except yaml.YAMLError as e:+ raise QueueError(yaml12.not_yaml(rel, e)) from e++def scan(text: str, rel: str) -> list[Entry]:- """The flags and the reviewed statuses in one YAML file, with their lines; no git."""- root = yaml.compose(text)+ """The flags and the reviewed statuses in one YAML file, with their lines; no git. Raises QueueError on text that is+ not YAML."""+ root = _compose(text, rel)entries: list[Entry] = []if root is None:return entries@@ -253,7 +263,7 @@ def scan_translations(repo: Path, rel: str) -> list[Entry]:agent-checked, listed as the inline flag it replaces, with the row and sources of its English record (the sources staythere): a content entry's record by its key; an event's by its id, with its text_he_sources, else the event's ownsources."""- root = yaml.compose((repo / rel).read_text(encoding="utf-8"))+ root = _compose((repo / rel).read_text(encoding="utf-8"), rel)entries: list[Entry] = []parsed: dict[str, dict] = {}events: dict[str, dict] | None = None@@ -266,7 +276,7 @@ def scan_translations(repo: Path, rel: str) -> list[Entry]:if events is None:events = {}for path in sorted((repo / "content" / "events").glob("*.yaml")):- tree = yaml.compose(path.read_text(encoding="utf-8"))+ tree = _compose(path.read_text(encoding="utf-8"), path.relative_to(repo).as_posix())top = {_scalar(a): b for a, b in tree.value} if isinstance(tree, yaml.MappingNode) else {}if "id" in top:events[_scalar(top["id"])] = top@@ -278,7 +288,7 @@ def scan_translations(repo: Path, rel: str) -> list[Entry]:where, _, name = rest.rpartition(".")if file not in parsed:path = repo / "content" / file- tree = yaml.compose(path.read_text(encoding="utf-8")) if path.is_file() else None+ tree = _compose(path.read_text(encoding="utf-8"), path.relative_to(repo).as_posix()) if path.is_file() else Noneparsed[file] = {".".join(ids): n for ids, n in _records(tree)}record = parsed[file].get(where)fields = {_scalar(a): b for a, b in record.value} if record is not None else {}diff --git a/tools/tests/test_review_queue.py b/tools/tests/test_review_queue.pyindex c086c3683..5f3cff71d 100644--- a/tools/tests/test_review_queue.py+++ b/tools/tests/test_review_queue.py@@ -252,3 +252,60 @@ def test_a_moved_hebrew_flag_is_listed_with_its_english_records_row_and_sources(("translations/he/events.yaml", 6, "truce", "text_he", "הפוגה.", ["https://example.org/truce"])]assert all(e.checked_by == "an AI agent (the `agent-checked` flag)" for e in entries if e.file.startswith("translations/"))assert "| example | name_he | איש לדוגמה | <https://example.org/hebrew-name> |" in rq.page(entries, 0, "0123456789abcdef")+++def _one_line_error(capsys) -> str:+ err = capsys.readouterr().err+ assert "Traceback" not in err and err.count("\n") == 1, err+ return err+++def test_a_malformed_content_file_is_a_clear_error_naming_the_file_and_line(tmp_path, capsys):+ """#2532: one bad content file stopped the whole queue with a traceback that did not name the file."""+ repo = make_repo(tmp_path)+ (repo / "content" / "offices.yaml").write_text("offices:\n - id: pm\n title: [unclosed\n", encoding="utf-8")+ assert rq.run(repo, write=False) == 2+ err = _one_line_error(capsys)+ assert err.startswith("review_queue: content/offices.yaml:") and "not valid YAML" in err+++def test_a_malformed_translation_file_is_a_clear_error_naming_the_file_and_line(tmp_path, capsys):+ """#2532: the same for translations/he/ and the content and event files it reads for sources."""+ repo = make_repo(tmp_path)+ he = repo / "translations" / "he"+ he.mkdir(parents=True)+ (he / "content.yaml").write_text('"offices.yaml#offices.fm.title":\n text: "x\n', encoding="utf-8")+ assert rq.run(repo, write=False) == 2+ assert _one_line_error(capsys) == ("review_queue: translations/he/content.yaml:3: not valid YAML: found unexpected end of "+ "stream (while scanning a quoted scalar from line 2)\n")+++def test_a_malformed_record_file_read_for_a_translation_is_a_clear_error(tmp_path, capsys):+ """#2532: the English record file a translations/he/content.yaml flag points at."""+ repo = make_repo(tmp_path)+ he = repo / "translations" / "he"+ he.mkdir(parents=True)+ (he / "content.yaml").write_text('"broken.yaml#rows.a.name":\n text: "x"\n review: "agent-checked"\n', encoding="utf-8")+ (repo / "content" / "broken.yaml").write_text("rows: {a: [\n", encoding="utf-8")+ entries = []+ try:+ entries = rq.scan_translations(repo, "translations/he/content.yaml")+ except rq.QueueError as e:+ assert str(e).startswith("content/broken.yaml:") and "not valid YAML" in str(e)+ else:+ raise AssertionError(f"no error: {entries}")+++def test_a_malformed_event_read_for_a_translation_is_a_clear_error(tmp_path):+ """#2532: the event files a translations/he/events.yaml flag reads for its sources."""+ repo = make_repo(tmp_path)+ he = repo / "translations" / "he"+ he.mkdir(parents=True)+ (he / "events.yaml").write_text('truce:\n text: "x"\n review: "agent-checked"\n', encoding="utf-8")+ (repo / "content" / "events" / "zz_broken.yaml").write_text("id: zz\ntitle: 'open\n", encoding="utf-8")+ try:+ rq.scan_translations(repo, "translations/he/events.yaml")+ except rq.QueueError as e:+ assert str(e).startswith("content/events/zz_broken.yaml:") and "not valid YAML" in str(e)+ else:+ raise AssertionError("no error")diff --git a/tools/tests/test_translate.py b/tools/tests/test_translate.pyindex 291d6f659..4554803ab 100644--- a/tools/tests/test_translate.py+++ b/tools/tests/test_translate.py@@ -420,3 +420,13 @@ def test_a_key_any_yaml_reader_would_type_or_split_is_quoted(key):@pytest.mark.parametrize("key", ["alpha", "a.one", "first_truce", "1948-05-15", "v1", "nully", "yes_vote"])def test_a_plain_key_stays_plain(key):assert translate._yaml_key(key) == key+++def test_a_malformed_file_is_an_error_naming_the_file_and_line(tmp_path):+ """#2532: the page shows `Type: message`; a YAML error did not name the file it came from."""+ bad = tmp_path / "broken.yaml"+ bad.write_text("id: x\ntitle: [unclosed\n", encoding="utf-8")+ with pytest.raises(ValueError) as e:+ translate._parse(bad)+ message = str(e.value)+ assert message.startswith(f"{bad}:") and "not valid YAML" in message and "\n" not in messagediff --git a/tools/translate.py b/tools/translate.pyindex a93f402fc..3ef28d50c 100644--- a/tools/translate.py+++ b/tools/translate.py@@ -89,11 +89,15 @@ _PARSED: dict[Path, tuple[tuple[int, int], object]] = {}def _parse(path: Path):"""The file's YAML, parsed again only when the file changes (the page re-checks on every keystroke). Callers do not- change what it returns."""+ change what it returns. Text that is not YAML is a ValueError naming the file and line."""stat = path.stat()stamp = (stat.st_mtime_ns, stat.st_size)if path not in _PARSED or _PARSED[path][0] != stamp:- _PARSED[path] = (stamp, yaml12.load(_read(path)))+ try:+ data = yaml12.load(_read(path))+ except yaml12.yaml.YAMLError as e: # the page shows only the message: name the file (#2532)+ raise ValueError(yaml12.not_yaml(str(path), e)) from e+ _PARSED[path] = (stamp, data)return _PARSED[path][1]diff --git a/tools/yaml12.py b/tools/yaml12.pyindex 021db73c1..c7979bb9a 100644--- a/tools/yaml12.py+++ b/tools/yaml12.py@@ -22,6 +22,7 @@ keeps the game's YAML free of both kinds (dates excepted, which every reader her- hazards(text): the plain scalars that safe_load reads differently from load(), with line and key path.- ambiguous(text): the plain scalars a YamlDotNet bool or int read accepts beyond YAML 1.2 (y, yes, off, 017, 1_000,1:30, 0b101, 0o17).+- not_yaml(name, error): a one-line message for a YAMLError, naming the file and the line (#2532).`uv run tools/yaml12.py FILE...` prints both lists.Use these instead of yaml.safe_load in tools/, scripts/ and .github/; tools/tests/test_yaml12_guard.py fails on a new@@ -138,6 +139,18 @@ def load_raw(text: str) -> Any:return yaml.load(text, Loader=RawLoader) # noqa: S506 (a SafeLoader subclass)+def not_yaml(name: str, error: yaml.YAMLError) -> str:+ """One line for a parse error in file <name>: "<name>:<line>: not valid YAML: <problem>". The line is 1-based, from+ where the parser stopped; PyYAML's own message spans several lines and, given text, names no file."""+ mark = getattr(error, "problem_mark", None) or getattr(error, "context_mark", None)+ problem = getattr(error, "problem", None) or next(iter(str(error).splitlines()), "") or type(error).__name__+ context, start = getattr(error, "context", None), getattr(error, "context_mark", None)+ if context and start is not None and start is not mark:+ context += f" from line {start.line + 1}"+ where = f"{name}:{mark.line + 1}" if mark is not None else name+ return f"{where}: not valid YAML: {problem}" + (f" ({context})" if context else "")++@dataclass(frozen=True)class Hazard:line: int # 1-based