Files
claude-config/bin/test_citations.py
T

26 lines
1.4 KiB
Python

import pathlib
import re
import subprocess
import unittest
ROOT = pathlib.Path(__file__).resolve().parents[1]
CITATION = re.compile(r'`?CLAUDE\.md`? → ("[^"]+"(?:,? (?:and )?"[^"]+")*)')
HEADING = re.compile(r"^#+ (.+?)(?: \(.*\))?$", re.MULTILINE)
LEAD = re.compile(r"^(?:- )?\*\*(.+?)(?:\*\*|[:.](?=\*\*| )| —)", re.MULTILINE)
NAME = re.compile(r'"([^"]+)"')
STRAY = re.compile(r'CLAUDE\.md(?!`? → "|:\d)[^\n"]{1,5}"')
class Citations(unittest.TestCase):
def test_every_citation_names_a_heading_then_headings_or_bold_leads_of_claude_md(self):
text = (ROOT / "CLAUDE.md").read_text()
headings = set(HEADING.findall(text))
leads = headings | set(LEAD.findall(text))
tracked = subprocess.run(["git", "ls-files", "-z"], capture_output=True, check=True, cwd=ROOT, text=True).stdout.split("\0")
texts = [(path, (ROOT / path).read_text()) for path in filter(None, tracked)]
self.assertEqual([f"{path}: {stray}" for path, text in texts for stray in STRAY.findall(text)], [], 'spell a citation `CLAUDE.md` → "Vocabulary"')
cited = [(path, NAME.findall(run)) for path, text in texts for run in CITATION.findall(text)]
self.assertTrue(cited)
unresolved = [(path, name) for path, names in cited for i, name in enumerate(names) if name not in (headings if i == 0 else leads)]
self.assertEqual([f"{path}: {name}" for path, name in unresolved], [], "the first name is a heading of CLAUDE.md, each later one a heading or a bold lead")