Skip to content

Commit 0013933

Browse files
committed
fix(citations): check Wayback capture ids in the link gate
The capture-id rule runs in tools/check-links.py, which CI already executes on every pull request. A replay URL whose id is not 14 digits still fails. The citation prober is left as it was. Co-authored-by: Mirza Iqbal <support@mirzaiqbal.com>
1 parent c9cb3fe commit 0013933

5 files changed

Lines changed: 112 additions & 72 deletions

File tree

‎docs/CITATION-POLICY.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ followed by the original URL. Those 14 digits are the capture time. A
5252
shorter token, including a bare `2`, is a prefix search. The archive
5353
answers HTTP 200 and then redirects to whichever capture is currently
5454
closest, so a green citation check can leave the reader on a different
55-
page than the one that was read. `tools/validate-refs.py` rejects a replay
55+
page than the one that was read. `tools/check-links.py` rejects a replay
5656
URL whose capture id is not those 14 digits. A record under
5757
`archive.org/details/` is a catalogue item, not a replay URL, and this
5858
rule does not apply to it.

‎tools/check-links-test.py‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,32 @@ def test_broken_internal_link_is_reported(self):
162162
errors = model.markdown_link_errors(page, page.read_text(), root)
163163
self.assertEqual(errors, ["broken internal link: missing.md"])
164164

165+
def test_wayback_prefix_is_rejected_and_a_pinned_capture_is_not(self):
166+
spec = importlib.util.spec_from_file_location(
167+
"check_links", TOOLS / "check-links.py"
168+
)
169+
links = importlib.util.module_from_spec(spec)
170+
spec.loader.exec_module(links)
171+
prefix = (
172+
"See https://web.archive.org/web/2/https://example.com/page, "
173+
"and https://archive.org/details/refactoringimpro0000fowl."
174+
)
175+
errors = links.wayback_replay_errors(prefix)
176+
self.assertEqual(len(errors), 1)
177+
self.assertIn("14 digits", errors[0])
178+
self.assertIn("/web/2/", errors[0])
179+
pinned = (
180+
"https://web.archive.org/web/20221101064556/"
181+
"https://example.com/page"
182+
)
183+
self.assertEqual(links.wayback_replay_errors(pinned), [])
184+
impossible = "https://web.archive.org/web/20221131064556/https://example.com/a"
185+
self.assertIn("calendar time", links.wayback_replay_errors(impossible)[0])
186+
fenced = "```\nhttps://web.archive.org/web/2/https://example.com/page\n```\n"
187+
self.assertEqual(links.wayback_replay_errors(fenced), [])
188+
coded = "Use `https://web.archive.org/web/2/https://example.com/page`.\n"
189+
self.assertEqual(links.wayback_replay_errors(coded), [])
190+
165191
def test_inline_code_is_not_a_link(self):
166192
with tempfile.TemporaryDirectory() as tmp:
167193
root = Path(tmp)

‎tools/check-links.py‎

Lines changed: 82 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
11
#!/usr/bin/env python3
2-
"""Fail on broken internal links, drifted entry ids, or unresolved related refs."""
2+
"""Fail on broken internal links, drifted entry ids, unresolved related refs,
3+
or a Wayback replay URL that does not name one capture."""
34

45
from __future__ import annotations
56

7+
import re
68
import sys
9+
from datetime import datetime
710
from pathlib import Path
811

912
TOOLS = Path(__file__).resolve().parent
@@ -24,6 +27,71 @@
2427
ROOT / "MAINTAINERS.md",
2528
]
2629

30+
# A Wayback replay URL is /web/<capture id>/<original>. The capture id is
31+
# YYYYMMDDhhmmss, optionally followed by a rewrite flag such as id_.
32+
# A shorter id, including a bare 2, is a prefix search. The archive answers
33+
# HTTP 200 and redirects to whichever capture is currently closest.
34+
URL = re.compile(r"https?://[^\s<>\]\"']+")
35+
TRAILING = ".,;:!?"
36+
WAYBACK_REPLAY = re.compile(
37+
r"^https?://web\.archive\.org/web/([^/]+)(?:/.*)?$",
38+
re.IGNORECASE,
39+
)
40+
WAYBACK_FLAGS = ("id_", "js_", "cs_", "im_", "if_", "fw_", "mp_", "oe_")
41+
42+
43+
def clean_url(url: str) -> str:
44+
while url and url[-1] in TRAILING:
45+
url = url[:-1]
46+
while url.endswith(")") and url.count("(") < url.count(")"):
47+
url = url[:-1]
48+
return url
49+
50+
51+
def prose_without_fences(text: str) -> str:
52+
out: list[str] = []
53+
inside = False
54+
for line in text.splitlines():
55+
if line.lstrip().startswith("```"):
56+
inside = not inside
57+
continue
58+
if not inside:
59+
out.append(line)
60+
return re.sub(r"`[^`]*`", " ", "\n".join(out))
61+
62+
63+
def wayback_timestamp_error(url: str) -> str | None:
64+
match = WAYBACK_REPLAY.match(url)
65+
if not match:
66+
return None
67+
token = match.group(1)
68+
digits = token
69+
for flag in WAYBACK_FLAGS:
70+
if token.endswith(flag):
71+
digits = token[: -len(flag)]
72+
break
73+
if not re.fullmatch(r"\d{14}", digits):
74+
return f"wayback capture id must be 14 digits, found '{token}'"
75+
try:
76+
datetime.strptime(digits, "%Y%m%d%H%M%S")
77+
except ValueError:
78+
return f"wayback capture id is not a calendar time, found '{digits}'"
79+
return None
80+
81+
82+
def wayback_replay_errors(text: str) -> list[str]:
83+
errors: list[str] = []
84+
seen: set[str] = set()
85+
for raw in URL.findall(prose_without_fences(text)):
86+
url = clean_url(raw)
87+
if url in seen:
88+
continue
89+
seen.add(url)
90+
error = wayback_timestamp_error(url)
91+
if error:
92+
errors.append(f"{error}: {url}")
93+
return errors
94+
2795

2896
def markdown_files() -> list[Path]:
2997
files: list[Path] = []
@@ -52,22 +120,32 @@ def main() -> int:
52120
for error in errors:
53121
print(f" {error}")
54122
link_failed = 0
123+
wayback_failed = 0
55124
files = markdown_files()
56125
for path in files:
57126
text = path.read_text(encoding="utf-8", errors="replace")
58127
errors = model.markdown_link_errors(path, text, ROOT)
59-
if errors:
60-
link_failed += 1
128+
wayback = wayback_replay_errors(text)
129+
if errors or wayback:
130+
if errors:
131+
link_failed += 1
132+
if wayback:
133+
wayback_failed += 1
61134
rel = path.relative_to(ROOT)
62135
print(f"FAIL {rel}")
63136
for error in errors:
64137
print(f" {error}")
138+
for error in wayback:
139+
print(f" {error}")
65140
entries = len(index.entries)
66141
print(
67142
f"\n{entries - failed}/{entries} entries pass identity and relationship checks"
68143
)
69144
print(f"{len(files) - link_failed}/{len(files)} files pass internal links")
70-
return 1 if failed or link_failed else 0
145+
print(
146+
f"{len(files) - wayback_failed}/{len(files)} files pin every Wayback capture"
147+
)
148+
return 1 if failed or link_failed or wayback_failed else 0
71149

72150

73151
if __name__ == "__main__":

‎tools/validate-refs-test.py‎

Lines changed: 0 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -26,29 +26,6 @@ def test_strip_fences(self):
2626
self.assertIn("line2", stripped)
2727
self.assertNotIn("https://example.com", stripped)
2828

29-
def test_wayback_prefix_timestamp_is_rejected(self):
30-
short = "https://web.archive.org/web/2/https://example.com/page"
31-
self.assertIn("14 digits", validate_refs.wayback_timestamp_error(short))
32-
wildcard = "https://web.archive.org/web/*/https://example.com/page"
33-
self.assertIn("14 digits", validate_refs.wayback_timestamp_error(wildcard))
34-
35-
def test_wayback_pinned_capture_is_accepted(self):
36-
pinned = (
37-
"https://web.archive.org/web/20221101064556/"
38-
"https://karandhillon95.medium.com/the-morning-after-syndrome-4e49096156ed"
39-
)
40-
self.assertIsNone(validate_refs.wayback_timestamp_error(pinned))
41-
flagged = "https://web.archive.org/web/20221101064556id_/https://example.com/a"
42-
self.assertIsNone(validate_refs.wayback_timestamp_error(flagged))
43-
44-
def test_wayback_impossible_calendar_time_is_rejected(self):
45-
bad = "https://web.archive.org/web/20221131064556/https://example.com/a"
46-
self.assertIn("calendar time", validate_refs.wayback_timestamp_error(bad))
47-
48-
def test_archive_catalogue_record_is_not_a_replay_url(self):
49-
record = "https://archive.org/details/refactoringimpro0000fowl"
50-
self.assertIsNone(validate_refs.wayback_timestamp_error(record))
51-
5229
def test_probe_success(self):
5330
mock_response = MagicMock()
5431
mock_response.status = 200

‎tools/validate-refs.py‎

Lines changed: 3 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@
1111
import sys
1212
import urllib.error
1313
import urllib.request
14-
from datetime import datetime
1514
from pathlib import Path
1615

1716
ROOT = Path(__file__).resolve().parent.parent
@@ -23,14 +22,6 @@
2322

2423
UA = "Mozilla/5.0 (compatible; patterns-ref-validator/1.0; +https://github.com/mjmirza/patterns)"
2524

26-
# A Wayback replay URL is /web/<capture id>/<original>. The capture id is
27-
# YYYYMMDDhhmmss, optionally followed by a rewrite flag such as id_.
28-
WAYBACK_REPLAY = re.compile(
29-
r"^https?://web\.archive\.org/web/([^/]+)(?:/.*)?$",
30-
re.IGNORECASE,
31-
)
32-
WAYBACK_FLAGS = ("id_", "js_", "cs_", "im_", "if_", "fw_", "mp_", "oe_")
33-
3425
ALLOW_UNREACHABLE = {
3526
# Publishers that block automated HEAD requests but are stable citations.
3627
"dl.acm.org",
@@ -67,30 +58,6 @@
6758
}
6859

6960

70-
def wayback_timestamp_error(url: str) -> str | None:
71-
"""A short Wayback timestamp is a prefix search, not a citation.
72-
73-
/web/2/ answers HTTP 200 and redirects to whichever capture is currently
74-
closest. The cached status then stays green while the page changes.
75-
"""
76-
match = WAYBACK_REPLAY.match(url)
77-
if not match:
78-
return None
79-
token = match.group(1)
80-
digits = token
81-
for flag in WAYBACK_FLAGS:
82-
if token.endswith(flag):
83-
digits = token[: -len(flag)]
84-
break
85-
if not re.fullmatch(r"\d{14}", digits):
86-
return f"wayback capture id must be 14 digits, found '{token}'"
87-
try:
88-
datetime.strptime(digits, "%Y%m%d%H%M%S")
89-
except ValueError:
90-
return f"wayback capture id is not a calendar time, found '{digits}'"
91-
return None
92-
93-
9461
def clean(u: str) -> str:
9562
while u and u[-1] in TRAILING:
9663
u = u[:-1]
@@ -164,18 +131,10 @@ def main() -> int:
164131
return 0
165132

166133
cache = json.loads(CACHE.read_text()) if CACHE.exists() else {}
167-
bad: list[tuple[str, object, list[str]]] = []
168-
# A cached 200 does not excuse a prefix timestamp. The archive returns
169-
# 200 for /web/2/ and then redirects, so the cache would hide it forever.
170-
structural = {u for u in urls if wayback_timestamp_error(u)}
171-
for url in sorted(structural):
172-
bad.append((url, wayback_timestamp_error(url), urls[url]))
173-
todo = [
174-
u
175-
for u in urls
176-
if u not in structural and str(cache.get(u)) not in {"200", "301", "302"}
177-
]
134+
todo = [u for u in urls if str(cache.get(u)) not in {"200", "301", "302"}]
178135
print(f"{len(urls)} distinct citations, {len(todo)} to probe")
136+
137+
bad: list[tuple[str, object, list[str]]] = []
179138
with cf.ThreadPoolExecutor(max_workers=args.workers) as ex:
180139
for url, status in ex.map(lambda u: probe(u, args.timeout), todo):
181140
cache[url] = status

0 commit comments

Comments
 (0)