diff --git a/.github/workflows/canon-marker.yml b/.github/workflows/canon-marker.yml index 915377b..39600d4 100644 --- a/.github/workflows/canon-marker.yml +++ b/.github/workflows/canon-marker.yml @@ -5,9 +5,13 @@ on: jobs: check: - runs-on: ubuntu-latest + # The forge's runner carries the label `docker` (image node:22-bookworm); + # `ubuntu-latest` matches no runner there and the job is cancelled. + runs-on: docker steps: - uses: actions/checkout@v4 with: fetch-depth: 0 + - run: apt-get update -qq && apt-get install -y -qq python3-yaml + - run: python3 -m unittest scripts/tests/test_check_canon_marker.py - run: python3 scripts/check_canon_marker.py "origin/${{ github.base_ref }}" diff --git a/scripts/check_canon_marker.py b/scripts/check_canon_marker.py index b38ab6c..1ea5d88 100644 --- a/scripts/check_canon_marker.py +++ b/scripts/check_canon_marker.py @@ -1,11 +1,13 @@ #!/usr/bin/env python3 """Canon/proposal marker check. Usage: check_canon_marker.py -Checks .md files under Aetheria/ added or modified against . +Checks .md files under Aetheria/ added, modified or renamed against . Proves the form and presence of ruling ids, not that the ruling exists. """ import re, subprocess, sys +import yaml + ID = re.compile(r"^[a-z0-9][a-z0-9-]*:ruling:[a-z0-9][a-z0-9._-]*$") @@ -14,33 +16,47 @@ def git(*a): def frontmatter(text): - """Return (kind, rulings or None, error). Only the two keys we need.""" + """Return (kind, rulings or None, error). Frontmatter is real YAML.""" if not text.startswith("---\n"): return None, None, None end = text.find("\n---", 4) if end < 0: return None, None, "unterminated frontmatter" - kind, rulings, in_rul = None, None, False - for line in text[4:end].splitlines(): - m = re.match(r"^kind:\s*(\S+)\s*$", line) - if m: - kind, in_rul = m.group(1), False - elif re.match(r"^rulings:\s*$", line): - rulings, in_rul = [], True - elif re.match(r"^rulings:\s*\[(.*)\]\s*$", line): - rulings, in_rul = [s.strip() for s in line.split("[", 1)[1].rstrip("] \n").split(",") if s.strip()], False - elif in_rul and (m := re.match(r"^\s+-\s*(\S+)\s*$", line)): - rulings.append(m.group(1)) - elif not line.startswith((" ", "\t")): - in_rul = False + try: + data = yaml.safe_load(text[4:end]) + except yaml.YAMLError as e: + return None, None, f"frontmatter is not valid YAML ({type(e).__name__})" + if data is None: + data = {} + if not isinstance(data, dict): + return None, None, "frontmatter must be a mapping" + kind, rulings = data.get("kind"), data.get("rulings") + if kind is not None and not isinstance(kind, str): + return None, None, "kind must be a string" + if rulings is not None and not (isinstance(rulings, list) and all(isinstance(r, str) for r in rulings)): + return None, None, "rulings must be a list of strings" return kind, rulings, None +def changed(base): + """(status letter, path) for each page added, modified or renamed (the new path).""" + out = git("diff", "-z", "--name-status", "--diff-filter=AMR", f"{base}...HEAD", "--", "Aetheria") + fields = out.split("\0") + rows, i = [], 0 + while i < len(fields) and fields[i]: + st = fields[i] + if st[0] == "R": + rows.append(("R", fields[i + 2])) + i += 3 + else: + rows.append((st[0], fields[i + 1])) + i += 2 + return rows + + def main(base): - status = git("diff", "--name-status", "--diff-filter=AM", f"{base}...HEAD", "--", "Aetheria") failed = False - for row in status.splitlines(): - st, path = row.split("\t", 1) + for st, path in changed(base): if not path.endswith(".md"): continue kind, rulings, err = frontmatter(open(path, encoding="utf-8").read()) @@ -71,4 +87,5 @@ def main(base): if __name__ == "__main__": + sys.stdout.reconfigure(encoding="utf-8") sys.exit(main(sys.argv[1])) diff --git a/scripts/tests/__pycache__/test_check_canon_marker.cpython-313.pyc b/scripts/tests/__pycache__/test_check_canon_marker.cpython-313.pyc new file mode 100644 index 0000000..0652bd9 Binary files /dev/null and b/scripts/tests/__pycache__/test_check_canon_marker.cpython-313.pyc differ diff --git a/scripts/tests/test_check_canon_marker.py b/scripts/tests/test_check_canon_marker.py new file mode 100644 index 0000000..cdb40d9 --- /dev/null +++ b/scripts/tests/test_check_canon_marker.py @@ -0,0 +1,138 @@ +"""Tests for scripts/check_canon_marker.py: each builds a throwaway git repo +with a main branch, adds pages on a branch, and runs the check against main.""" +import os +import subprocess +import tempfile +import unittest + +SCRIPT = os.path.join(os.path.dirname(__file__), "..", "check_canon_marker.py") +RULING = "aetheria-lore:ruling:megiddo-origin" + + +def git(cwd, *args): + subprocess.run(["git", "-c", "user.email=t@t", "-c", "user.name=t", *args], + cwd=cwd, check=True, capture_output=True) + + +class Repo: + def __init__(self): + self.tmp = tempfile.TemporaryDirectory() + self.dir = self.tmp.name + git(self.dir, "init", "-b", "main") + os.makedirs(os.path.join(self.dir, "Aetheria")) + self.write("Aetheria/Legacy.md", "old page, no marker\n" + "line of lore\n" * 20) + git(self.dir, "add", "-A") + git(self.dir, "commit", "-m", "base") + git(self.dir, "checkout", "-b", "pr") + + def write(self, path, text): + full = os.path.join(self.dir, path) + os.makedirs(os.path.dirname(full), exist_ok=True) + with open(full, "w", encoding="utf-8") as f: + f.write(text) + + def commit(self): + git(self.dir, "add", "-A") + git(self.dir, "commit", "-m", "pr") + + def check(self): + p = subprocess.run(["python3", SCRIPT, "main"], cwd=self.dir, + capture_output=True, text=True) + return p.returncode, p.stdout + p.stderr + + +def canon(rulings, kind="canon"): + return f"---\nkind: {kind}\nrulings:\n{rulings}---\nbody\n" + + +class CanonMarker(unittest.TestCase): + def run_pages(self, pages, after=None): + r = Repo() + for path, text in pages.items(): + r.write(path, text) + if after: + after(r) + r.commit() + return r.check() + + def test_a_canon_page_with_a_ruling_id_passes(self): + code, out = self.run_pages({"Aetheria/A.md": canon(f" - {RULING}\n")}) + self.assertEqual(code, 0, out) + + def test_a_canon_page_without_a_ruling_fails(self): + code, out = self.run_pages({"Aetheria/A.md": "---\nkind: canon\n---\nx\n"}) + self.assertEqual(code, 1, out) + + def test_a_non_ascii_path_is_checked_not_skipped(self): + code, out = self.run_pages({"Aetheria/Framgång.md": "---\nkind: canon\n---\nx\n"}) + self.assertEqual(code, 1, out) + self.assertIn("Framgång.md", out) + + def test_a_renamed_page_is_checked(self): + def rename(r): + git(r.dir, "mv", "Aetheria/Legacy.md", "Aetheria/Moved.md") + r.write("Aetheria/Moved.md", "---\nkind: canon\n---\n" + "old page, no marker\n" + "line of lore\n" * 20) + code, out = self.run_pages({}, after=rename) + self.assertEqual(code, 1, out) + self.assertIn("Moved.md", out) + + def test_quoted_values_parse(self): + text = f'---\nkind: "canon"\nrulings:\n - "{RULING}"\n---\nx\n' + code, out = self.run_pages({"Aetheria/A.md": text}) + self.assertEqual(code, 0, out) + + def test_a_trailing_comment_on_a_ruling_is_not_part_of_the_id(self): + code, out = self.run_pages({"Aetheria/A.md": canon(f" - {RULING} # megiddo\n")}) + self.assertEqual(code, 0, out) + + def test_a_flow_list_of_rulings_parses(self): + text = f"---\nkind: canon\nrulings: [{RULING}, weksa:ruling:other]\n---\nx\n" + code, out = self.run_pages({"Aetheria/A.md": text}) + self.assertEqual(code, 0, out) + + def test_cross_campaign_ruling_ids_count(self): + code, out = self.run_pages({"Aetheria/A.md": canon(" - weksa-body:ruling:faction-play-1\n")}) + self.assertEqual(code, 0, out) + + def test_a_malformed_ruling_id_fails(self): + code, out = self.run_pages({"Aetheria/A.md": canon(" - megiddo-origin\n")}) + self.assertEqual(code, 1, out) + + def test_a_proposal_may_not_carry_rulings(self): + code, out = self.run_pages({"Aetheria/A.md": canon(f" - {RULING}\n", kind="proposal")}) + self.assertEqual(code, 1, out) + + def test_a_proposal_without_rulings_passes(self): + code, out = self.run_pages({"Aetheria/A.md": "---\nkind: proposal\n---\nx\n"}) + self.assertEqual(code, 0, out) + + def test_an_unknown_kind_fails(self): + code, out = self.run_pages({"Aetheria/A.md": "---\nkind: draft\n---\nx\n"}) + self.assertEqual(code, 1, out) + + def test_a_new_untagged_page_fails(self): + code, out = self.run_pages({"Aetheria/A.md": "no frontmatter\n"}) + self.assertEqual(code, 1, out) + + def test_a_touched_legacy_page_passes_with_a_notice(self): + code, out = self.run_pages({"Aetheria/Legacy.md": "old page, edited\n" + "line of lore\n" * 20}) + self.assertEqual(code, 0, out) + self.assertIn("notice", out) + + def test_invalid_yaml_fails_instead_of_crashing(self): + code, out = self.run_pages({"Aetheria/A.md": "---\nkind: [canon\n---\nx\n"}) + self.assertEqual(code, 1, out) + self.assertNotIn("Traceback", out) + + def test_a_non_mapping_frontmatter_fails(self): + code, out = self.run_pages({"Aetheria/A.md": "---\n- canon\n---\nx\n"}) + self.assertEqual(code, 1, out) + self.assertNotIn("Traceback", out) + + def test_pages_outside_aetheria_are_not_checked(self): + code, out = self.run_pages({"README2.md": "---\nkind: canon\n---\nx\n"}) + self.assertEqual(code, 0, out) + + +if __name__ == "__main__": + unittest.main()