Skip to content

Commit 0e4de13

Browse files
committed
Check new documentation links against cached base reports
Compare PR and merge-queue links with the exact base revision's Sphinx JSONL report. Escape and anchor known URLs so new paths and fragments remain checked, while preserving checks for local links and manual exclusions. Restore an exact-SHA baseline cache published only by main pushes. On a cache miss, fetch the base commit and generate its report in a temporary worktree rather than weakening enforcement. Accept existing broken links in that report, but reject missing or malformed reports. Make new-link failures block PRs and merge queues. Keep full checks on pushes informational and retain failing daily checks for site-wide link monitoring. Upload full reports and summarize failing URLs so maintainers can investigate outages without blocking unrelated changes.
1 parent 7c738e1 commit 0e4de13

4 files changed

Lines changed: 223 additions & 3 deletions

File tree

‎.github/workflows/test.yml‎

Lines changed: 57 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,18 +27,27 @@ jobs:
2727
timeout-minutes: 20
2828
continue-on-error: >-
2929
${{ fromJSON(matrix.continue-on-error) }}
30+
env:
31+
LINKCHECK_BASE_REF: >-
32+
${{ matrix.noxenv == 'linkcheck' &&
33+
(github.event.pull_request.base.sha || github.event.merge_group.base_sha) || '' }}
34+
LINKCHECK_BASELINE: >-
35+
${{ matrix.noxenv == 'linkcheck' &&
36+
contains(fromJSON('["pull_request", "merge_group"]'), github.event_name) &&
37+
format('{0}/.nox/.cache/linkcheck-baseline.jsonl', github.workspace) || '' }}
3038
strategy:
39+
fail-fast: false
3140
matrix:
3241
noxenv:
3342
- build
3443
continue-on-error:
3544
- false
3645
include:
3746
- noxenv: linkcheck
38-
# Don't block PRs, merge groups, or non-main pushes on unrelated linkcheck failures.
47+
# Pushes monitor all links; only new links block PRs and merge groups.
48+
# Scheduled runs remain blocking to report site-wide link failures.
3949
continue-on-error: >-
40-
${{ toJSON(contains(fromJSON('["merge_group", "pull_request"]'), github.event_name) ||
41-
(github.event_name == 'push' && github.ref_name != github.event.repository.default_branch)) }}
50+
${{ toJSON(github.event_name == 'push') }}
4251
4352
steps:
4453
- uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
@@ -56,13 +65,58 @@ jobs:
5665
run: |
5766
python -m pip install --upgrade nox virtualenv
5867
68+
- name: Restore linkcheck baseline
69+
if: env.LINKCHECK_BASE_REF != ''
70+
uses: actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830 # v4
71+
with:
72+
path: .nox/.cache/linkcheck-baseline.jsonl
73+
key: linkcheck-baseline-v1-${{ env.LINKCHECK_BASE_REF }}
74+
5975
- name: Nox ${{ matrix.noxenv }}
6076
env:
6177
# Authenticate github.com requests during linkcheck to avoid rate limits.
6278
GITHUB_TOKEN: ${{ matrix.noxenv == 'linkcheck' && github.token || '' }}
6379
run: |
6480
python -m nox -s ${{ matrix.noxenv }}
6581
82+
- name: Prepare report for baseline cache
83+
id: baseline-report
84+
if: >-
85+
${{ always() && matrix.noxenv == 'linkcheck' && github.event_name == 'push' &&
86+
github.ref_name == github.event.repository.default_branch }}
87+
run: >-
88+
python scripts/linkcheck.py publish --report build/output.json
89+
--baseline .nox/.cache/linkcheck-baseline.jsonl
90+
91+
- name: Save linkcheck baseline
92+
if: ${{ always() && steps.baseline-report.outcome == 'success' }}
93+
uses: actions/cache/save@0057852bfaa89a56745cba8c7296529d2fc39830 # v4
94+
with:
95+
path: .nox/.cache/linkcheck-baseline.jsonl
96+
key: linkcheck-baseline-v1-${{ github.sha }}
97+
98+
- name: Upload full linkcheck reports
99+
if: >-
100+
${{ always() && matrix.noxenv == 'linkcheck' &&
101+
(github.event_name == 'schedule' || (github.event_name == 'push' &&
102+
github.ref_name == github.event.repository.default_branch)) }}
103+
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
104+
with:
105+
name: linkcheck-reports
106+
path: |
107+
build/output.json
108+
build/output.txt
109+
if-no-files-found: warn
110+
111+
- name: Summarize full linkcheck
112+
if: >-
113+
${{ always() && matrix.noxenv == 'linkcheck' &&
114+
(github.event_name == 'schedule' || (github.event_name == 'push' &&
115+
github.ref_name == github.event.repository.default_branch)) }}
116+
run: >-
117+
python scripts/linkcheck.py summarize --report build/output.json
118+
--summary "$GITHUB_STEP_SUMMARY"
119+
66120
67121
check:
68122
# This job does nothing and is only used for the branch protection

‎noxfile.py‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44
# http://creativecommons.org/licenses/by-sa/3.0.
55

66

7+
import os
8+
79
import nox
810

911
nox.options.sessions = []
@@ -77,6 +79,16 @@ def linkcheck(session):
7779
Check for broken links.
7880
"""
7981
session.install("-r", "requirements.txt")
82+
if base := os.getenv("LINKCHECK_BASE_REF"):
83+
session.run(
84+
"python",
85+
"scripts/linkcheck.py",
86+
"prepare",
87+
"--base",
88+
base,
89+
"--report",
90+
os.environ["LINKCHECK_BASELINE"],
91+
)
8092
session.run(
8193
"sphinx-build",
8294
"-b",

‎scripts/linkcheck.py‎

Lines changed: 150 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,150 @@
1+
"""Prepare exact-URL linkcheck baselines and summarize monitoring reports."""
2+
3+
from __future__ import annotations
4+
5+
import argparse
6+
import html
7+
import json
8+
import os
9+
import re
10+
import shutil
11+
import subprocess
12+
import sys
13+
import tempfile
14+
from pathlib import Path
15+
16+
17+
def read_report(path: Path) -> list[dict]:
18+
"""Read Sphinx's JSONL report, rejecting unusable cache entries."""
19+
records = []
20+
for number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1):
21+
if not line.strip():
22+
continue
23+
try:
24+
record = json.loads(line)
25+
except json.JSONDecodeError as exc:
26+
raise ValueError(f"{path}:{number}: invalid JSON") from exc
27+
if (
28+
not isinstance(record, dict)
29+
or not isinstance(record.get("uri"), str)
30+
or not record["uri"]
31+
or not isinstance(record.get("status"), str)
32+
):
33+
raise ValueError(f"{path}:{number}: invalid linkcheck record")
34+
records.append(record)
35+
return records
36+
37+
38+
def baseline_patterns(path: Path) -> list[str]:
39+
"""Ignore known external URLs, without ignoring new suffixes or local links."""
40+
urls = {
41+
record["uri"]
42+
for record in read_report(path)
43+
if record["uri"].startswith(("http://", "https://"))
44+
}
45+
print(f"Linkcheck baseline: {len(urls)} known external URLs from {path}")
46+
return [r"\A" + re.escape(url) + r"\Z" for url in sorted(urls)]
47+
48+
49+
def copy_report(source: Path, destination: Path) -> None:
50+
read_report(source)
51+
destination.parent.mkdir(parents=True, exist_ok=True)
52+
shutil.copyfile(source, destination)
53+
54+
55+
def prepare_baseline(base: str, report: Path) -> None:
56+
"""Use the cached report or generate one at the exact base revision."""
57+
if not re.fullmatch(r"[0-9a-f]{40}", base):
58+
raise ValueError("The linkcheck base must be a full Git commit SHA")
59+
if report.exists():
60+
read_report(report)
61+
print(f"Linkcheck baseline cache hit: {base}")
62+
return
63+
64+
print(f"Linkcheck baseline cache miss: generating report for {base}", flush=True)
65+
if subprocess.run(
66+
["git", "cat-file", "-e", f"{base}^{{commit}}"],
67+
check=False,
68+
stdout=subprocess.DEVNULL,
69+
stderr=subprocess.DEVNULL,
70+
).returncode:
71+
subprocess.run(
72+
["git", "fetch", "--no-tags", "--depth=1", "origin", base], check=True
73+
)
74+
75+
with tempfile.TemporaryDirectory(prefix="linkcheck-baseline-") as directory:
76+
temporary = Path(directory)
77+
checkout = temporary / "checkout"
78+
output = temporary / "report"
79+
subprocess.run(
80+
["git", "worktree", "add", "--detach", str(checkout), base], check=True
81+
)
82+
try:
83+
env = os.environ.copy()
84+
env.pop("LINKCHECK_BASELINE", None)
85+
env.pop("LINKCHECK_BASE_REF", None)
86+
result = subprocess.run(
87+
[
88+
sys.executable,
89+
"-m",
90+
"sphinx",
91+
"-b",
92+
"linkcheck",
93+
"-d",
94+
str(temporary / "doctrees"),
95+
"-n",
96+
"-W",
97+
"--keep-going",
98+
"source",
99+
str(output),
100+
],
101+
cwd=checkout,
102+
env=env,
103+
check=False,
104+
)
105+
# Sphinx returns 1 for broken links or warnings. Those do not change
106+
# which URLs existed at the base revision; a report is still required.
107+
if result.returncode not in (0, 1):
108+
result.check_returncode()
109+
copy_report(output / "output.json", report)
110+
finally:
111+
subprocess.run(
112+
["git", "worktree", "remove", "--force", str(checkout)], check=True
113+
)
114+
115+
116+
def summarize(report: Path, summary: Path) -> None:
117+
records = read_report(report)
118+
failures = [r for r in records if r["status"] in {"broken", "timeout"}]
119+
lines = ["## Full linkcheck", "", f"{len(failures)} failing URLs.", ""]
120+
for record in failures:
121+
uri = html.escape(record["uri"])
122+
info = html.escape(str(record.get("info", record["status"]))).replace("\n", " ")
123+
lines.append(f"- <code>{uri}</code>: {info}")
124+
with summary.open("a", encoding="utf-8") as stream:
125+
stream.write("\n".join(lines) + "\n")
126+
127+
128+
def main() -> None:
129+
parser = argparse.ArgumentParser(description=__doc__)
130+
commands = parser.add_subparsers(dest="command", required=True)
131+
prepare = commands.add_parser("prepare")
132+
prepare.add_argument("--base", required=True)
133+
prepare.add_argument("--report", type=Path, required=True)
134+
publish = commands.add_parser("publish")
135+
publish.add_argument("--report", type=Path, required=True)
136+
publish.add_argument("--baseline", type=Path, required=True)
137+
summary = commands.add_parser("summarize")
138+
summary.add_argument("--report", type=Path, required=True)
139+
summary.add_argument("--summary", type=Path, required=True)
140+
args = parser.parse_args()
141+
if args.command == "prepare":
142+
prepare_baseline(args.base, args.report.resolve())
143+
elif args.command == "publish":
144+
copy_report(args.report, args.baseline)
145+
else:
146+
summarize(args.report, args.summary)
147+
148+
149+
if __name__ == "__main__":
150+
main()

‎source/conf.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,10 @@
175175
# Archived snapshots don't change, and the Wayback Machine rate-limits CI (429).
176176
r"https://web\.archive\.org/.*",
177177
]
178+
if _baseline := os.getenv("LINKCHECK_BASELINE"):
179+
from scripts.linkcheck import baseline_patterns
180+
181+
linkcheck_ignore.extend(baseline_patterns(pathlib.Path(_baseline)))
178182
linkcheck_retries = 2
179183
linkcheck_timeout = 30
180184
# Ignore anchors for common targets when we know they likely won't be found

0 commit comments

Comments
 (0)