Skip to content

A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.

Markdown link check: titles, badges, escapes and letter case (refs #333) (#341)

agamrafaeli-instinct7fcf845ed6bc
diff --git a/scripts/oss/md_links.py b/scripts/oss/md_links.py
index a1078c351..1267c14cd 100644
--- a/scripts/oss/md_links.py
+++ b/scripts/oss/md_links.py
@@ -1,18 +1,21 @@
#!/usr/bin/env python3
-"""Markdown link check (#333): every relative link in a tracked *.md file must point at a file that exists.
+"""Markdown link check (#333): every relative link in a tracked *.md file must point at a file that is tracked in git.
`uv run scripts/oss/md_links.py [--root DIR]`. Ignores code fences, absolute URLs (any `scheme:`), `#anchor` and
`mailto:` links, and targets with brackets (reference-style leftovers). Anchors after `#` are not checked, only the file.
+Handles a link title (`[a](b "t")`), `<angle>` targets, `%20` escapes and the outer link of a badge (`[![x](img)](page)`).
+A target must match a tracked file or directory exactly, so a wrong letter case fails on macOS too (CI's Linux would).
One line per dead link (file: link); exit 1 if any."""
import argparse
import os
import re
import subprocess
import sys
+from urllib.parse import unquote
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
-LINK = re.compile(r"\[[^\]]*\]\(([^)\s]+)\)")
+LINK = re.compile(r"\]\(<?([^)\s>]+)>?(?:\s+(?:\"[^\"]*\"|'[^']*'))?\)")
FENCE = re.compile(r"```.*?```", re.S)
@@ -21,16 +24,27 @@ def tracked_markdown(root: Path) -> list[str]:
return [f for f in out.split("\0") if f]
+def tracked_paths(root: Path) -> set[str]:
+ """Every tracked file and every directory above one, with the exact letter case git stores."""
+ out = subprocess.run(["git", "-C", str(root), "ls-files", "-z"], capture_output=True, text=True, check=True).stdout
+ paths = {"."} # the repository root, which `[top](..)` from docs/ or `[x](./)` resolves to
+ for f in filter(None, out.split("\0")):
+ parts = f.split("/")
+ paths.update("/".join(parts[:i]) for i in range(1, len(parts) + 1))
+ return paths
+
+
def dead_links(root: Path) -> list[tuple[str, str]]:
bad = []
+ known = tracked_paths(root)
for f in tracked_markdown(root):
text = FENCE.sub("", (root / f).read_text(encoding="utf-8"))
for m in LINK.finditer(text):
target = m.group(1)
if re.match(r"[A-Za-z][A-Za-z0-9+.-]*:|#", target) or "[" in target:
continue
- path = target.split("#")[0]
- if path and not (root / os.path.normpath(os.path.join(os.path.dirname(f), path))).exists():
+ path = unquote(target.split("#")[0].split("?")[0])
+ if path and os.path.normpath(os.path.join(os.path.dirname(f), path)).replace(os.sep, "/").rstrip("/") not in known:
bad.append((f, target))
return bad
diff --git a/scripts/oss/tests/test_md_links.py b/scripts/oss/tests/test_md_links.py
index 09ff1e425..8a7441edd 100644
--- a/scripts/oss/tests/test_md_links.py
+++ b/scripts/oss/tests/test_md_links.py
@@ -26,3 +26,12 @@ def test_clean_repo_returns_zero(make_repo):
def test_this_repo_has_no_dead_relative_links():
assert m.dead_links(ROOT) == []
+
+
+def test_title_badge_escape_and_case(make_repo):
+ root = make_repo({
+ 'README.md': '[t](docs/a.md "title") [t2](docs/a.md \'x y\') [angle](<docs/a.md>) [esc](docs/b%20c.md) [dir](docs/)\n'
+ '[![badge](img.svg)](LICENSING.md) [![b2](img.svg)](GONE.md) [case](Docs/a.md) [root](.) [root2](./)\n',
+ 'docs/a.md': '[up](..) [up2](../)\n', 'docs/b c.md': 'x\n', 'img.svg': 'x\n', 'LICENSING.md': 'x\n',
+ })
+ assert m.dead_links(root) == [('README.md', 'GONE.md'), ('README.md', 'Docs/a.md')]