Every relative link must point at an existing file and, when it has a #anchor, at a real heading (slugged the way Gitea does); every docs page must be linked from the README and link back to it. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
72 lines
2.7 KiB
Python
72 lines
2.7 KiB
Python
"""The README and docs/ pages link to each other; keep those links from rotting."""
|
|
|
|
import os
|
|
import re
|
|
import unittest
|
|
|
|
from helpers import REPO
|
|
|
|
PAGES = ["README.md"] + sorted(f"docs/{n}" for n in os.listdir(os.path.join(REPO, "docs"))
|
|
if n.endswith(".md"))
|
|
|
|
|
|
def read(rel):
|
|
with open(os.path.join(REPO, rel)) as f:
|
|
return f.read()
|
|
|
|
|
|
def strip_code(text):
|
|
"""Drop fenced blocks and inline code, where `[x](y)` is an example, not a link."""
|
|
text = re.sub(r"^```.*?^```", "", text, flags=re.S | re.M)
|
|
return re.sub(r"`[^`\n]*`", "", text)
|
|
|
|
|
|
def slug(heading):
|
|
"""The anchor Gitea/GitHub make for a heading."""
|
|
heading = heading.replace("`", "").strip().lower()
|
|
return re.sub(r"\s", "-", re.sub(r"[^\w\s-]", "", heading))
|
|
|
|
|
|
def anchors(rel):
|
|
text = re.sub(r"^```.*?^```", "", read(rel), flags=re.S | re.M)
|
|
return {slug(m.group(2)) for m in re.finditer(r"^(#{1,6})\s+(.*)$", text, re.M)}
|
|
|
|
|
|
def links(rel):
|
|
for m in re.finditer(r"\[[^\]]*\]\(([^)\s]+)\)", strip_code(read(rel)).replace("\n", " ")):
|
|
target = m.group(1)
|
|
if not re.match(r"[a-z]+:", target): # skip https:, mailto:
|
|
yield target
|
|
|
|
|
|
class DocsLinksTest(unittest.TestCase):
|
|
def test_relative_links_and_anchors_resolve(self):
|
|
problems = []
|
|
for page in PAGES:
|
|
for target in links(page):
|
|
path, _, fragment = target.partition("#")
|
|
dest = os.path.normpath(os.path.join(os.path.dirname(page), path)) if path else page
|
|
if not os.path.exists(os.path.join(REPO, dest)):
|
|
problems.append(f"{page}: {target} -> {dest} does not exist")
|
|
elif fragment and dest.endswith(".md") and fragment not in anchors(dest):
|
|
problems.append(f"{page}: {target} -> no heading #{fragment} in {dest}")
|
|
self.assertEqual(problems, [])
|
|
|
|
def test_every_docs_page_is_linked_from_the_readme(self):
|
|
linked = {os.path.normpath(t.partition("#")[0]) for t in links("README.md")}
|
|
self.assertEqual(sorted(set(PAGES[1:]) - linked), [])
|
|
|
|
def test_every_docs_page_links_back_to_the_readme(self):
|
|
for page in PAGES[1:]:
|
|
self.assertIn("../README.md", set(links(page)), page)
|
|
|
|
def test_slug_matches_how_gitea_names_anchors(self):
|
|
self.assertEqual(slug("Heartbeat: is kernelwatch itself running?"),
|
|
"heartbeat-is-kernelwatch-itself-running")
|
|
self.assertEqual(slug("Scripting: `kernelwatch status`"), "scripting-kernelwatch-status")
|
|
self.assertEqual(slug("Authelia (forward auth)"), "authelia-forward-auth")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|