Skip to content

Commit c2fe4df

Browse files
committed
ci: add checker for broken links introduced by PRs
1 parent 457e74f commit c2fe4df

1 file changed

Lines changed: 83 additions & 0 deletions

File tree

‎scripts/check_new_link_failures.py‎

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
"""Fail when Sphinx reports a URL added by the current PR as broken."""
2+
3+
from __future__ import annotations
4+
5+
import argparse
6+
import json
7+
import re
8+
import subprocess
9+
from pathlib import Path
10+
11+
URL_RE = re.compile(r"https?://[^\s<>()\[\]{}\"']+")
12+
TRAILING_PUNCTUATION = ".,;:!?`"
13+
14+
15+
def _added_urls(base: str) -> set[str]:
16+
result = subprocess.run(
17+
[
18+
"git",
19+
"diff",
20+
"--unified=0",
21+
"--diff-filter=AM",
22+
f"{base}...HEAD",
23+
"--",
24+
"source",
25+
],
26+
check=True,
27+
capture_output=True,
28+
text=True,
29+
)
30+
urls: set[str] = set()
31+
for line in result.stdout.splitlines():
32+
if not line.startswith("+") or line.startswith("+++"):
33+
continue
34+
for match in URL_RE.findall(line[1:]):
35+
urls.add(match.rstrip(TRAILING_PUNCTUATION))
36+
return urls
37+
38+
39+
def _broken_urls(report: Path) -> dict[str, str]:
40+
if not report.is_file():
41+
raise SystemExit(f"linkcheck report not found: {report}")
42+
43+
broken: dict[str, str] = {}
44+
for number, raw_line in enumerate(report.read_text(encoding="utf-8").splitlines(), 1):
45+
if not raw_line.strip():
46+
continue
47+
try:
48+
record = json.loads(raw_line)
49+
except json.JSONDecodeError as exc:
50+
raise SystemExit(f"invalid JSON in {report} line {number}: {exc}") from exc
51+
if record.get("status") != "broken":
52+
continue
53+
uri = record.get("uri")
54+
if isinstance(uri, str):
55+
broken[uri] = str(record.get("info") or "broken")
56+
return broken
57+
58+
59+
def main() -> int:
60+
parser = argparse.ArgumentParser()
61+
parser.add_argument("--base", required=True, help="PR base commit SHA")
62+
parser.add_argument("--report", type=Path, default=Path("build/output.json"))
63+
args = parser.parse_args()
64+
65+
added = _added_urls(args.base)
66+
if not added:
67+
print("No newly added HTTP(S) links found in source/. ")
68+
return 0
69+
70+
broken = _broken_urls(args.report)
71+
failures = {url: broken[url] for url in sorted(added & broken.keys())}
72+
if not failures:
73+
print(f"All {len(added)} newly added HTTP(S) link(s) passed Sphinx linkcheck.")
74+
return 0
75+
76+
print("Broken links introduced by this PR:")
77+
for url, info in failures.items():
78+
print(f"- {url}: {info}")
79+
return 1
80+
81+
82+
if __name__ == "__main__":
83+
raise SystemExit(main())

0 commit comments

Comments
 (0)