Skip to content

Commit a91d998

Browse files
authored
Added broken link fix (#133)
1 parent f8c164d commit a91d998

2 files changed

Lines changed: 122 additions & 0 deletions

File tree

.github/workflows/link-check.yml

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,3 +49,9 @@ jobs:
4949
sudo install ${{ runner.temp }}/htmltest /usr/local/bin/htmltest
5050
- name: Check internal links
5151
run: htmltest
52+
# htmltest only inspects a[href], img[src], script[src] and link[href].
53+
# The JS-driven nav (<option value>) and retina variants (srcset) fall
54+
# outside those attributes, so they are checked separately.
55+
- name: Check links htmltest does not cover
56+
if: always()
57+
run: python3 scripts/check-unchecked-links.py public

scripts/check-unchecked-links.py

Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
#!/usr/bin/env python3
2+
"""Check the internal links that htmltest does not look at.
3+
4+
htmltest inspects a[href], img[src], script[src] and link[href]. Two kinds of
5+
real link live outside those attributes and therefore pass it unnoticed:
6+
7+
<option value> The responsive nav (layouts/partials/site-navigation.html) is
8+
a <select> that navigates via JavaScript, so its URLs sit in
9+
form values. To HTML they are opaque strings.
10+
11+
srcset Retina variants are never fetched by htmltest, so a renamed
12+
@2x image breaks silently for high-DPI screens only.
13+
14+
Usage: check-unchecked-links.py [public_dir]
15+
Exits non-zero and lists every URL that does not resolve to a file.
16+
"""
17+
18+
import re
19+
import sys
20+
from pathlib import Path
21+
from urllib.parse import unquote, urlsplit
22+
23+
OPTION_VALUE = re.compile(r'<option\b[^>]*\bvalue="([^"]*)"', re.IGNORECASE)
24+
SRCSET = re.compile(r'<[^>]*\bsrcset="([^"]*)"', re.IGNORECASE)
25+
26+
# Schemes that point off-site; parity with htmltest's CheckExternal: false.
27+
EXTERNAL = ("http://", "https://", "//", "mailto:", "tel:", "javascript:", "data:")
28+
29+
30+
def is_external(url: str) -> bool:
31+
return url.lower().startswith(EXTERNAL)
32+
33+
34+
def srcset_urls(value: str):
35+
"""Yield the URL of each srcset candidate ("<url> 2x, <url> 1x")."""
36+
for candidate in value.split(","):
37+
candidate = candidate.strip()
38+
if candidate:
39+
# The URL is the first token; anything after it is a descriptor.
40+
yield candidate.split()[0]
41+
42+
43+
def resolves(public: Path, page: Path, url: str) -> bool:
44+
"""True if `url`, as linked from `page`, is served by a file under public/."""
45+
path = urlsplit(url).path
46+
if not path:
47+
return True # pure query or fragment: same document
48+
rel = unquote(path)
49+
50+
if rel.startswith("/"):
51+
base = public
52+
rel = rel.lstrip("/")
53+
else:
54+
base = page.parent # relative URLs resolve against the linking page
55+
56+
if not rel or rel.endswith("/"):
57+
return (base / rel / "index.html").is_file()
58+
59+
target = base / rel
60+
# Hugo serves pretty URLs, so /foo may be foo/index.html or foo.html.
61+
return (
62+
target.is_file()
63+
or (target / "index.html").is_file()
64+
or target.with_name(target.name + ".html").is_file()
65+
)
66+
67+
68+
def main() -> int:
69+
public = Path(sys.argv[1] if len(sys.argv) > 1 else "public")
70+
if not public.is_dir():
71+
print(f"error: no such directory: {public}", file=sys.stderr)
72+
return 2
73+
74+
documents = 0
75+
checked = 0
76+
failures = []
77+
78+
for page in sorted(public.rglob("*.html")):
79+
documents += 1
80+
html = page.read_text(encoding="utf-8", errors="replace")
81+
where = page.relative_to(public)
82+
83+
for value in OPTION_VALUE.findall(html):
84+
value = value.strip()
85+
# Not every <option> is a link. Only absolute paths are treated as
86+
# navigation targets, so plain form values (a country code, say)
87+
# and pure fragments are left alone.
88+
if not value.startswith("/") or is_external(value):
89+
continue
90+
checked += 1
91+
if not resolves(public, page, value):
92+
failures.append((where, "option value", value))
93+
94+
for value in SRCSET.findall(html):
95+
for url in srcset_urls(value):
96+
# Every srcset candidate is a URL by spec, so relative ones are
97+
# resolved too — unlike <option value> above.
98+
if is_external(url) or url.startswith("#"):
99+
continue
100+
checked += 1
101+
if not resolves(public, page, url):
102+
failures.append((where, "srcset", url))
103+
104+
for where, kind, value in failures:
105+
print(f" target does not exist --- {where} --> {value} [{kind}]")
106+
107+
print("=" * 72)
108+
if failures:
109+
print(f"✘✘✘ {len(failures)} broken link(s) in {documents} documents")
110+
return 1
111+
print(f"✔✔✔ passed — {checked} unchecked-by-htmltest links in {documents} documents")
112+
return 0
113+
114+
115+
if __name__ == "__main__":
116+
sys.exit(main())

0 commit comments

Comments
 (0)