forked from EchinopsisM/docusaurus-link-checker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcheck_links.py
More file actions
1479 lines (1245 loc) · 57.7 KB
/
Copy pathcheck_links.py
File metadata and controls
1479 lines (1245 loc) · 57.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Link checker for Docusaurus sites.
Checks:
1. Internal links in source docs (markdown/mdx) — verified against the BUILD output:
• page existence checked by looking up the corresponding HTML file in build/
• anchor existence checked by reading actual id attributes from rendered HTML
No slug inference — only what Docusaurus actually produced is trusted.
2. Internal links in build output (HTML) — file existence + anchors
3. External links in source docs — real HTTP requests (HEAD/GET)
Run from your Docusaurus project root:
python check_links.py [--site-domain your-site.com] [--no-external] [--threads N]
python check_links.py --mode live [--site-domain your-site.com]
"""
import os
import re
import sys
import time
import threading
import queue
import subprocess
from pathlib import Path
from html.parser import HTMLParser
from urllib.parse import urlparse, unquote
from collections import defaultdict
from urllib.request import Request, urlopen, HTTPRedirectHandler, build_opener
from urllib.error import URLError, HTTPError
import http.client
import socket
import argparse
# ─────────────────────────────────────────────
# Configuration
# ─────────────────────────────────────────────
PROJECT_DIR = Path.cwd()
DOCS_DIR = PROJECT_DIR / "docs"
BUILD_DIR = PROJECT_DIR / "build"
STATIC_DIR = PROJECT_DIR / "static"
REPORT_PATH = PROJECT_DIR / "link-reports/dead_links_report.md"
HUMAN_REPORT_PATH = PROJECT_DIR / "link-reports/dead_links_audit.md"
# The live domain — full-URL links using this domain are treated as internal
# and checked against the local build directory instead of via HTTP.
# Override with --site-domain on the command line.
SITE_DOMAIN = "" # set via CLI arg; auto-detected from docusaurus.config.* if empty
SITE_BASE_URL = ""
# External link checker settings
EXT_TIMEOUT = 15 # seconds per request
EXT_THREADS = 8 # concurrent HTTP workers
EXT_DELAY = 0.15 # seconds between requests per thread (politeness)
USER_AGENT = (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/122.0 Safari/537.36 bee-docs-link-checker/2.0"
)
# Schemes to collect for external checking (everything http/https)
EXTERNAL_SCHEMES = ("http://", "https://")
# Schemes to ignore entirely
IGNORE_SCHEMES = ("mailto:", "javascript:", "tel:", "ftp:", "data:")
# Internal path prefixes where anchor checking is skipped (JS-rendered pages)
SKIP_ANCHOR_PATHS = (
"/api/",
"/api#",
)
# Hostnames/prefixes to skip — example/placeholder URLs in documentation
IGNORE_HOSTS = (
"localhost",
"127.0.0.1",
"192.168.",
"10.0.",
"0.0.0.0",
)
# ─────────────────────────────────────────────
# Helpers — markdown link extraction
# ─────────────────────────────────────────────
def strip_code_blocks(content):
content = re.sub(r'<!--[\s\S]*?-->', '', content) # HTML comments
content = re.sub(r'```[^\n]*\n[\s\S]*?```', '', content)
content = re.sub(r'~~~[^\n]*\n[\s\S]*?~~~', '', content)
content = re.sub(r'`[^`\n]+`', '', content)
return content
def extract_md_links(content):
"""Return list of (link_text, url) from markdown content."""
content = strip_code_blocks(content)
links = []
# Inline links: [text](url) or [text](url "title")
# The URL pattern allows balanced parentheses (e.g. Wikipedia URLs like /wiki/APT_(software))
for m in re.finditer(r'\[([^\]]*)\]\(((?:[^)(]|\([^)]*\))*?)(?:\s+"[^"]*")?\)', content):
url = m.group(2).strip().split('"')[0].strip().split("'")[0].strip()
links.append((m.group(1), url))
# Reference-style definitions
ref_defs = {}
for m in re.finditer(r'^\[([^\]]+)\]:\s*(\S+)', content, re.MULTILINE):
ref_defs[m.group(1).lower()] = m.group(2)
# Reference-style uses
for m in re.finditer(r'\[([^\]]+)\]\[([^\]]*)\]', content):
text = m.group(1)
ref = m.group(2).lower() if m.group(2) else text.lower()
if ref in ref_defs:
links.append((text, ref_defs[ref]))
# HTML anchors and images in markdown
for m in re.finditer(r'<a\s[^>]*href=["\']([^"\']+)["\']', content, re.IGNORECASE):
links.append(('', m.group(1)))
for m in re.finditer(r'<img\s[^>]*src=["\']([^"\']+)["\']', content, re.IGNORECASE):
links.append(('', m.group(1)))
# Bare URLs — plain http(s) URLs not inside a markdown link or HTML attribute.
# Collect all URL positions already captured above to avoid double-reporting.
seen_spans = set()
for m in re.finditer(r'\[([^\]]*)\]\(([^)]+)\)', content):
seen_spans.add(m.start(2))
for m in re.finditer(r'^\[([^\]]+)\]:\s*(\S+)', content, re.MULTILINE):
seen_spans.add(m.start(2))
for m in re.finditer(r'(?:href|src)=["\']([^"\']+)["\']', content, re.IGNORECASE):
seen_spans.add(m.start(1))
for m in re.finditer(r'https?://[^\s\]>"\'\\<*`]+', content):
if m.start() not in seen_spans:
url = m.group(0).rstrip('.,;:!')
# Strip trailing unbalanced close-parens
while url.endswith(')') and url.count('(') < url.count(')'):
url = url[:-1]
links.append(('', url))
return links
# ─────────────────────────────────────────────
# Helpers — build-output link resolution
# ─────────────────────────────────────────────
def _frontmatter_id(md_file):
"""Return the 'id' value from YAML frontmatter, or None."""
try:
text = md_file.read_text(encoding='utf-8', errors='replace')
if not text.startswith('---'):
return None
end = text.find('\n---', 3)
if end == -1:
return None
for line in text[3:end].splitlines():
if line.startswith('id:'):
return line[3:].strip().strip('"\'')
except Exception:
pass
return None
def _build_docid_map():
"""
Scan all HTML files in the build and return a dict {doc_id: html_path}.
Docusaurus embeds the doc ID in the <html> class as 'docs-doc-id-{id}',
e.g. class="... docs-doc-id-concepts/DISC/disc ...".
This is the ground truth for what page is at what path — no inference needed.
"""
mapping = {}
if not BUILD_DIR.exists():
return mapping
for html_file in BUILD_DIR.rglob('index.html'):
try:
# Only read the <html> opening tag (first ~500 bytes) for performance
with html_file.open(encoding='utf-8', errors='replace') as fh:
head = fh.read(800)
m = re.search(r'docs-doc-id-([^\s"\']+)', head)
if m:
mapping[m.group(1)] = html_file
except Exception:
pass
return mapping
# Populated once at first call to md_path_to_build_html()
_DOCID_MAP = None
def md_path_to_build_html(md_file):
"""Map a source .md/.mdx file to the HTML file Docusaurus built from it.
Uses the build's own HTML files (via the embedded docs-doc-id class) as the
authoritative source — no path inference or slug computation.
Falls back to a computed path when the build map lookup misses.
"""
global _DOCID_MAP
if _DOCID_MAP is None:
_DOCID_MAP = _build_docid_map()
try:
rel = md_file.relative_to(DOCS_DIR)
except ValueError:
return None
# Compute the full doc ID: parent/local_id
local_id = _frontmatter_id(md_file) or rel.with_suffix('').name
parent = str(rel.parent).replace('\\', '/')
doc_id = local_id if parent == '.' else f"{parent}/{local_id}"
# Look up in the reverse map first (authoritative)
if doc_id in _DOCID_MAP:
return _DOCID_MAP[doc_id]
# Fallback: compute expected path
parent_path = rel.parent
if local_id == 'index':
return BUILD_DIR / 'docs' / parent_path / 'index.html'
return BUILD_DIR / 'docs' / parent_path / local_id / 'index.html'
def resolve_internal_to_build_html(source_md, link_path):
"""Resolve an internal (non-http) link path to the build HTML file it corresponds to.
Checks the build/ directory only — no slug inference, no source-file guessing.
Returns (html_path_or_None, error_reason_or_None).
Caller is responsible for splitting off any '#anchor' before calling.
"""
decoded = unquote(link_path)
# ── Absolute path (/docs/… or /static/…) ──
if decoded.startswith('/'):
rel = decoded.lstrip('/')
candidates = [
BUILD_DIR / rel,
BUILD_DIR / rel / 'index.html',
BUILD_DIR / (rel + '.html'),
]
for c in candidates:
if c.exists() and c.is_file():
return c, None
return None, f"Not found in build: /{rel}"
# ── Relative path ──
target = (source_md.parent / decoded).resolve()
# Non-markdown file (image, PDF, asset): check static/ and on-disk path
if target.suffix not in ('', '.md', '.mdx'):
if target.exists():
return target, None
try:
static_candidate = STATIC_DIR / target.relative_to(PROJECT_DIR)
if static_candidate.exists():
return static_candidate, None
except ValueError:
pass
return None, f"File not found: {target.name}"
# Markdown / no extension: find source file → map to build HTML
md_candidates = (
[target] if target.suffix in ('.md', '.mdx')
else [target.with_suffix('.md'), target.with_suffix('.mdx'),
target / 'index.md', target / 'index.mdx']
)
for md_cand in md_candidates:
if md_cand.exists() and md_cand.is_file():
build_html = md_path_to_build_html(md_cand)
if build_html is None:
return None, "Could not map source file to build path"
if build_html.exists():
return build_html, None
return None, "Source file exists but its build HTML was not found — is the build current?"
return None, "Source file not found"
def resolve_site_url_locally(url):
"""Check a full docs.ethswarm.org URL against the local build output."""
parsed = urlparse(url)
rel = parsed.path.rstrip('/').lstrip('/')
candidates = [
BUILD_DIR / rel,
BUILD_DIR / rel / 'index.html',
BUILD_DIR / (rel + '.html'),
]
for c in candidates:
if c.exists() and c.is_file():
return True, str(c)
return False, str(BUILD_DIR / rel)
# ─────────────────────────────────────────────
# External URL checker
# ─────────────────────────────────────────────
EXT_STATUS_OK = 'ok'
EXT_STATUS_404 = '404'
EXT_STATUS_DOWN = 'down'
EXT_STATUS_REDIRECT = 'redirect'
EXT_STATUS_ERROR = 'error'
EXT_STATUS_INTERNAL = 'internal_404' # full site URL that resolves locally but build says 404
class _NoFollowRedirectHandler(HTTPRedirectHandler):
"""Prevent urllib from automatically following redirects."""
def redirect_request(self, req, fp, code, msg, headers, newurl):
return None # returning None makes urllib raise HTTPError with the 3xx code
def _build_no_redirect_opener():
return build_opener(_NoFollowRedirectHandler())
def _fetch(url, headers, method='HEAD', follow_redirects=False):
"""
Make a single HTTP request.
follow_redirects=False: do not follow redirects; 3xx responses return the
code and Location header so the caller can decide what to do.
follow_redirects=True: follow the full redirect chain (standard urlopen behaviour).
Returns (status_code_or_None, final_url, location_header_or_None, error_str_or_None).
"""
try:
req = Request(url, headers=headers, method=method)
if follow_redirects:
with urlopen(req, timeout=EXT_TIMEOUT) as resp:
return resp.status, resp.url, None, None
else:
opener = _build_no_redirect_opener()
with opener.open(req, timeout=EXT_TIMEOUT) as resp:
return resp.status, url, resp.headers.get('Location'), None
except HTTPError as e:
loc = e.headers.get('Location') if hasattr(e, 'headers') and e.headers else None
return e.code, url, loc, None
except (URLError, socket.timeout, socket.error, ConnectionRefusedError,
http.client.RemoteDisconnected, http.client.IncompleteRead) as e:
return None, url, None, str(e)
except Exception as e:
return None, url, None, f'{type(e).__name__}: {str(e)[:80]}'
def _classify_connection_error(result, err):
"""Populate result with the right status for a network-level error string."""
if 'ECONNREFUSED' in err or 'Connection refused' in err:
result['status'] = EXT_STATUS_DOWN
result['error_msg'] = 'ECONNREFUSED — server down'
elif ('Name or service not known' in err or 'getaddrinfo' in err
or 'nodename' in err.lower() or 'No address' in err):
result['status'] = EXT_STATUS_DOWN
result['error_msg'] = 'DNS resolution failed'
elif 'timed out' in err.lower() or 'timeout' in err.lower():
result['status'] = EXT_STATUS_DOWN
result['error_msg'] = 'Connection timed out'
elif 'SSL' in err or 'ssl' in err:
result['status'] = EXT_STATUS_DOWN
result['error_msg'] = f'SSL error: {err[:80]}'
else:
result['status'] = EXT_STATUS_DOWN
result['error_msg'] = f'Connection error: {err[:80]}'
return result
def _check_destination(dest_url, headers):
"""
Verify that a redirect destination is actually reachable (200).
Follows the full redirect chain from dest_url.
Returns (status_code_or_None, final_url, error_str_or_None).
"""
code, final, _, err = _fetch(dest_url, headers, method='HEAD', follow_redirects=True)
if err:
return None, dest_url, err
if code in (403, 405):
# Some servers reject HEAD — retry with GET
code, final, _, err = _fetch(dest_url, headers, method='GET', follow_redirects=True)
if err:
return None, dest_url, err
return code, final or dest_url, None
def check_external_url(url):
"""
Check a single external URL.
Strategy:
1. HEAD request WITHOUT following redirects so we can see whether
the URL itself redirects (and where).
2. If 3xx: explicitly fetch the redirect destination and verify it
returns 200. Only report as EXT_STATUS_REDIRECT if the destination
is reachable. A redirect that leads to a 404/down is reported as
the appropriate broken status.
3. If HEAD is rejected (403/405): retry with GET, same logic.
Returns dict: {url, status, http_code, final_url, error_msg}
"""
result = {
'url': url,
'status': EXT_STATUS_ERROR,
'http_code': None,
'final_url': None,
'error_msg': None,
}
# Special case: links to our own live site — check against local build
parsed = urlparse(url)
if parsed.netloc == SITE_DOMAIN:
exists, tried = resolve_site_url_locally(url)
if exists:
result['status'] = EXT_STATUS_OK
else:
result['status'] = EXT_STATUS_INTERNAL
result['error_msg'] = f"Not in local build: {tried}"
return result
headers = {
'User-Agent': USER_AGENT,
'Accept': 'text/html,application/xhtml+xml,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.9',
}
# ── Step 1: initial request (no auto-redirect) ──
code, _, location, err = _fetch(url, headers, method='HEAD', follow_redirects=False)
if err:
return _classify_connection_error(result, err)
# HEAD rejected → retry with GET (no auto-redirect)
if code in (403, 405):
code, _, location, err = _fetch(url, headers, method='GET', follow_redirects=False)
if err:
return _classify_connection_error(result, err)
if code in (403, 405):
result['status'] = EXT_STATUS_ERROR
result['http_code'] = code
result['error_msg'] = f"HTTP {code} (GET retry)"
result['final_url'] = url
return result
result['http_code'] = code
# ── Step 2: classify based on response code ──
if code is None:
result['status'] = EXT_STATUS_ERROR
return result
if code == 200:
result['status'] = EXT_STATUS_OK
result['final_url'] = url
elif code == 404:
result['status'] = EXT_STATUS_404
result['error_msg'] = 'HTTP 404'
result['final_url'] = url
elif code in (301, 302, 303, 307, 308):
# ── Redirect: verify the destination is actually reachable ──
dest = location or url
# Make dest absolute if it's a relative Location header
if dest and not dest.startswith('http'):
p = urlparse(url)
dest = f"{p.scheme}://{p.netloc}{dest}"
dest_code, dest_final, dest_err = _check_destination(dest, headers)
if dest_err:
result['status'] = EXT_STATUS_DOWN
result['error_msg'] = f"Redirect to {dest!r} failed: {dest_err[:80]}"
result['final_url'] = dest
elif dest_code is None:
result['status'] = EXT_STATUS_DOWN
result['error_msg'] = f"Redirect destination unreachable: {dest!r}"
result['final_url'] = dest
elif dest_code == 200:
if _urls_differ_meaningfully(url, dest_final):
result['status'] = EXT_STATUS_REDIRECT
result['final_url'] = dest_final
else:
result['status'] = EXT_STATUS_OK
result['final_url'] = dest_final
elif dest_code == 404:
result['status'] = EXT_STATUS_404
result['error_msg'] = f"Redirect target returned 404 ({dest!r})"
result['final_url'] = dest
else:
result['status'] = EXT_STATUS_ERROR
result['error_msg'] = f"Redirect target returned HTTP {dest_code}"
result['final_url'] = dest
else:
# Any other 2xx is fine; other codes treated as errors
if 200 <= code < 300:
result['status'] = EXT_STATUS_OK
result['final_url'] = url
else:
result['status'] = EXT_STATUS_ERROR
result['error_msg'] = f"HTTP {code}"
result['final_url'] = url
return result
def _urls_differ_meaningfully(original, final):
"""True if the URLs differ in a way that's worth reporting (not just http→https or trailing slash)."""
if not final or original == final:
return False
o = urlparse(original)
f = urlparse(final)
o_path = o.path.rstrip('/')
f_path = f.path.rstrip('/')
# Same host+path, only scheme or trailing-slash differs → not meaningful
if o.netloc == f.netloc and o_path == f_path and o.query == f.query:
return False
# http → https upgrade on same host/path → not meaningful
if (o.netloc == f.netloc and o_path == f_path
and o.scheme == 'http' and f.scheme == 'https'):
return False
return True
def check_external_urls_threaded(url_to_sources, threads=EXT_THREADS):
"""
Check a dict of {url: [source_files]} concurrently.
Returns dict of {url: check_result_dict}.
"""
urls = list(url_to_sources.keys())
results = {}
lock = threading.Lock()
q = queue.Queue()
for url in urls:
q.put(url)
total = len(urls)
done = [0]
def worker():
while True:
try:
url = q.get_nowait()
except queue.Empty:
break
time.sleep(EXT_DELAY)
res = check_external_url(url)
with lock:
results[url] = res
done[0] += 1
n = done[0]
if n % 10 == 0 or n == total:
print(f" External: {n}/{total} checked...", end='\r', flush=True)
q.task_done()
thread_list = [threading.Thread(target=worker, daemon=True) for _ in range(min(threads, len(urls)))]
for t in thread_list:
t.start()
for t in thread_list:
t.join()
print() # newline after \r progress
return results
# ─────────────────────────────────────────────
# Markdown file checker
# ─────────────────────────────────────────────
def check_markdown_files(check_external=True):
"""
Scan all .md/.mdx source files.
Internal links are verified against the BUILD output:
- page existence: does the corresponding build HTML file exist?
- anchor existence: is the anchor present as an id attribute in the rendered HTML?
No slug inference is performed at any point.
Returns:
- broken_internal: list of broken internal link dicts
- external_url_to_sources: dict {url: [(source_file, link_text)]}
- stats
"""
broken_internal = []
external_url_to_src = defaultdict(list)
files_checked = 0
links_checked = 0
html_id_cache = {} # str(html_path) → frozenset of id strings
if not BUILD_DIR.exists():
print(" WARNING: build/ directory not found.")
print(" Run 'npm run build' first — internal links cannot be checked without it.")
md_files = sorted(list(DOCS_DIR.rglob('*.md')) + list(DOCS_DIR.rglob('*.mdx')))
for md_file in md_files:
files_checked += 1
try:
content = md_file.read_text(encoding='utf-8', errors='replace')
except Exception as e:
broken_internal.append({
'source': str(md_file), 'link_text': '', 'link_url': '',
'resolved': '', 'reason': f'Could not read file: {e}',
})
continue
# Build HTML for this source file — used for anchor-only (#frag) links
source_build_html = md_path_to_build_html(md_file)
links = extract_md_links(content)
for link_text, url in links:
url = url.strip()
if not url or url == '#':
continue
if any(url.startswith(s) for s in IGNORE_SCHEMES):
continue
parsed_url = urlparse(url)
if any(parsed_url.hostname and parsed_url.hostname.startswith(h) for h in IGNORE_HOSTS):
continue
links_checked += 1
# ── External / self-site links ──
if any(url.startswith(s) for s in EXTERNAL_SCHEMES):
if check_external:
external_url_to_src[url].append((str(md_file), link_text))
continue
# ── Split anchor from path ──
anchor = None
link_path = url
if '#' in link_path:
link_path, anchor = link_path.split('#', 1)
# ── Determine target build HTML ──
if not link_path:
# Anchor-only link — same page
target_html = source_build_html
else:
target_html, reason = resolve_internal_to_build_html(md_file, link_path)
if reason or target_html is None or not target_html.exists():
broken_internal.append({
'source': str(md_file),
'link_text': link_text,
'link_url': url,
'resolved': str(target_html) if target_html else link_path,
'reason': reason or 'Build HTML not found',
})
continue
# ── Check anchor in rendered HTML ──
if anchor and any(url.startswith(p) for p in SKIP_ANCHOR_PATHS):
continue # JS-rendered page — anchor not in static HTML
if anchor and target_html and target_html.exists():
key = str(target_html)
if key not in html_id_cache:
html_id_cache[key] = get_html_ids(target_html)
if anchor not in html_id_cache[key]:
broken_internal.append({
'source': str(md_file),
'link_text': link_text,
'link_url': url,
'resolved': f'{target_html}#{anchor}',
'reason': f'Anchor "#{anchor}" not found in rendered HTML',
})
return broken_internal, dict(external_url_to_src), files_checked, links_checked, len(md_files)
# ─────────────────────────────────────────────
# HTML build checker
# ─────────────────────────────────────────────
class LinkExtractor(HTMLParser):
def __init__(self):
super().__init__()
self.links = []
self.ids = set()
def handle_starttag(self, tag, attrs):
attrs_dict = dict(attrs)
if 'id' in attrs_dict:
self.ids.add(attrs_dict['id'])
if tag == 'a' and 'href' in attrs_dict:
self.links.append(('href', attrs_dict['href']))
elif tag in ('img', 'script') and 'src' in attrs_dict:
self.links.append(('src', attrs_dict['src']))
elif tag == 'link' and 'href' in attrs_dict:
self.links.append(('href', attrs_dict['href']))
def get_html_ids(html_file):
try:
content = html_file.read_text(encoding='utf-8', errors='replace')
except Exception:
return set()
parser = LinkExtractor()
parser.feed(content)
return parser.ids
def resolve_html_link(source_html, href, build_root):
anchor = None
if '#' in href:
href, anchor = href.split('#', 1)
href = unquote(href)
if not href:
return None, anchor, None
if href.startswith('/'):
rel = href.lstrip('/')
target = build_root / rel
candidates = [target]
if target.suffix == '':
candidates.append(target / 'index.html')
else:
source_dir = source_html.parent
target = (source_dir / href).resolve()
candidates = [target]
if target.suffix == '':
candidates.append(target / 'index.html')
for c in candidates:
if c.exists() and c.is_file():
return c, anchor, None
return target, anchor, "File not found"
def check_html_files():
broken = []
files_checked = 0
links_checked = 0
id_cache = {}
html_files = sorted(BUILD_DIR.rglob('*.html'))
for html_file in html_files:
files_checked += 1
try:
content = html_file.read_text(encoding='utf-8', errors='replace')
except Exception as e:
broken.append({'source': str(html_file), 'attr': 'href', 'link_url': '',
'resolved': '', 'reason': f'Could not read: {e}'})
continue
parser = LinkExtractor()
parser.feed(content)
file_ids = parser.ids
for attr, url in parser.links:
url = url.strip()
if not url or url == '#':
continue
if any(url.startswith(s) for s in EXTERNAL_SCHEMES + IGNORE_SCHEMES + ('data:',)):
continue
links_checked += 1
if url.startswith('#'):
anchor = url[1:]
if anchor and anchor not in file_ids:
broken.append({'source': str(html_file), 'attr': attr, 'link_url': url,
'resolved': f'{html_file}#{anchor}',
'reason': f'Anchor "#{anchor}" not found in same page'})
continue
resolved, anchor, reason = resolve_html_link(html_file, url, BUILD_DIR)
if reason:
broken.append({'source': str(html_file), 'attr': attr, 'link_url': url,
'resolved': str(resolved) if resolved else url, 'reason': reason})
continue
if anchor and resolved and resolved.exists():
key = str(resolved)
if key not in id_cache:
id_cache[key] = get_html_ids(resolved)
if anchor not in id_cache[key]:
broken.append({'source': str(html_file), 'attr': attr, 'link_url': url,
'resolved': f'{resolved}#{anchor}',
'reason': f'Anchor "#{anchor}" not found in target HTML'})
return broken, files_checked, links_checked, len(html_files)
# ─────────────────────────────────────────────
# Deduplication
# ─────────────────────────────────────────────
def deduplicate_html_broken(broken):
groups = defaultdict(list)
for item in broken:
groups[(item['link_url'], item['reason'])].append(item)
result = []
for (url, reason), items in sorted(groups.items()):
rep = dict(items[0])
rep['count'] = len(items)
rep['example_sources'] = [it['source'] for it in items[:3]]
result.append(rep)
return result
# ─────────────────────────────────────────────
# Report
# ─────────────────────────────────────────────
def make_short_path(path_str, base):
try:
return str(Path(path_str).relative_to(base))
except ValueError:
try:
return str(Path(path_str).relative_to(PROJECT_DIR))
except ValueError:
return path_str
def write_report(
md_broken, ext_results, ext_url_to_src,
md_files_checked, md_links_checked, md_total_files,
html_broken, html_files_checked, html_links_checked, html_total_files,
staged_replacements=None,
):
import datetime
today = datetime.date.today().isoformat()
# Categorise external results
ext_404 = {u: r for u, r in ext_results.items() if r['status'] == EXT_STATUS_404}
ext_down = {u: r for u, r in ext_results.items() if r['status'] == EXT_STATUS_DOWN}
ext_redirect = {u: r for u, r in ext_results.items() if r['status'] == EXT_STATUS_REDIRECT}
ext_internal = {u: r for u, r in ext_results.items() if r['status'] == EXT_STATUS_INTERNAL}
ext_error = {u: r for u, r in ext_results.items() if r['status'] == EXT_STATUS_ERROR}
_staged = staged_replacements or {}
def _repl(url, res=None):
if url in _staged:
return _staged[url]
final = (res or {}).get('final_url') or ''
return final if final and final != url else ''
deduped_html = deduplicate_html_broken(html_broken)
lines = []
lines.append("# Dead Links Report\n")
lines.append(f"Generated: {today}\n")
lines.append("")
# ── Summary ──
lines.append("## Summary\n")
lines.append("| Category | Count |")
lines.append("|---|---|")
lines.append(f"| Source doc files checked | {md_files_checked} / {md_total_files} |")
lines.append(f"| Internal links checked (source) | {md_links_checked} |")
lines.append(f"| **Broken internal links (source)** | **{len(md_broken)}** |")
lines.append(f"| External URLs checked | {len(ext_results)} |")
lines.append(f"| **External 404s** | **{len(ext_404) + len(ext_internal)}** |")
lines.append(f"| **External down / refused** | **{len(ext_down)}** |")
lines.append(f"| **Stale redirects** | **{len(ext_redirect)}** |")
lines.append(f"| External errors (timeout/misc) | {len(ext_error)} |")
lines.append(f"| Build HTML files checked | {html_files_checked} / {html_total_files} |")
lines.append(f"| **Broken links in build output** | **{len(deduped_html)} patterns** |")
lines.append("")
# ── Section 1: Internal broken links ──
lines.append("---\n")
lines.append("## Section 1: Broken Internal Links in Source Docs\n")
if not md_broken:
lines.append("_No broken internal links._\n")
else:
by_file = defaultdict(list)
for item in md_broken:
by_file[item['source']].append(item)
for source in sorted(by_file):
short = make_short_path(source, DOCS_DIR)
lines.append(f"### `{short}`\n")
lines.append("| Link Text | URL | Resolved Path | Reason |")
lines.append("|---|---|---|---|")
for item in by_file[source]:
text = item['link_text'].replace('|', '\\|')[:60]
url = item['link_url'].replace('|', '\\|')[:80]
resolved = make_short_path(item['resolved'], DOCS_DIR).replace('|', '\\|')[:100]
reason = item['reason'].replace('|', '\\|')
lines.append(f"| {text} | `{url}` | `{resolved}` | {reason} |")
lines.append("")
# ── Section 2: External 404s ──
lines.append("---\n")
lines.append("## Section 2: External 404s\n")
all_404 = {**ext_404, **ext_internal}
if not all_404:
lines.append("_No external 404s found._\n")
else:
lines.append("| URL | Notes | Instances (Link Text — File) |")
lines.append("|---|---|---|")
for url, res in sorted(all_404.items()):
instances = _fmt_instances(ext_url_to_src.get(url, []))
code_str = f"HTTP {res['http_code']}" if res['http_code'] else (res['error_msg'] or '')
if res['status'] == EXT_STATUS_INTERNAL:
code_str = "Not found in local build"
lines.append(f"| `{url[:100]}` | {code_str} | {instances} |")
lines.append("")
# ── Section 3: Down / refused ──
lines.append("---\n")
lines.append("## Section 3: Down / Connection Refused\n")
if not ext_down:
lines.append("_No unreachable external links._\n")
else:
lines.append("| URL | Error | Instances (Link Text — File) |")
lines.append("|---|---|---|")
for url, res in sorted(ext_down.items()):
instances = _fmt_instances(ext_url_to_src.get(url, []))
err = res.get('error_msg', '') or ''
lines.append(f"| `{url[:100]}` | {err} | {instances} |")
lines.append("")
# ── Section 4: Stale redirects ──
lines.append("---\n")
lines.append("## Section 4: Stale Redirects (Update to Final URL)\n")
if not ext_redirect:
lines.append("_No stale redirects found._\n")
else:
lines.append("| Original URL | Instances (Link Text — File) |")
lines.append("|---|---|")
for url, res in sorted(ext_redirect.items()):
instances = _fmt_instances(ext_url_to_src.get(url, []))
lines.append(f"| `{url[:80]}` | {instances} |")
lines.append("")
# ── Section 5: Errors / timeouts ──
if ext_error:
lines.append("---\n")
lines.append("## Section 5: External Check Errors (timeout / misc)\n")
lines.append("| URL | Error | Instances (Link Text — File) |")
lines.append("|---|---|---|")
for url, res in sorted(ext_error.items()):
instances = _fmt_instances(ext_url_to_src.get(url, []))
err = res.get('error_msg', '') or ''
lines.append(f"| `{url[:100]}` | {err} | {instances} |")
lines.append("")
# ── Section 6: Build HTML broken links ──
lines.append("---\n")
lines.append("## Section 6: Broken Links in Build Output\n")
lines.append("_Deduplicated by (url, reason) pattern._\n")
if not deduped_html:
lines.append("_No broken links in build output._\n")
else:
lines.append("| Count | URL | Reason | Example Source |")
lines.append("|---|---|---|---|")
for item in sorted(deduped_html, key=lambda x: -x['count']):
url = item['link_url'].replace('|', '\\|')[:80]
reason = item['reason'].replace('|', '\\|')
example = make_short_path(item['example_sources'][0], BUILD_DIR).replace('|', '\\|')[:80]
lines.append(f"| {item['count']} | `{url}` | {reason} | `{example}` |")
lines.append("")
REPORT_PATH.parent.mkdir(parents=True, exist_ok=True)
REPORT_PATH.write_text('\n'.join(lines), encoding='utf-8')
print(f"Report written to: {REPORT_PATH}")
# ─────────────────────────────────────────────
# Human-readable audit report
# ─────────────────────────────────────────────
def _source_to_page_link(path_str):
"""Return a markdown link like [/docs/foo/bar](https://docs.ethswarm.org/docs/foo/bar)."""
try:
rel = Path(path_str).relative_to(DOCS_DIR)
except ValueError:
return path_str
url_path = str(rel).replace('\\', '/').replace('.mdx', '').replace('.md', '')
display = f"/docs/{url_path}"
url = f"https://{SITE_DOMAIN}/docs/{url_path}"
return f"[{display}]({url})"
def _fmt_sources(sources_list, max_show=2):
"""Format a list of (file, text) source tuples into page link(s)."""
if not sources_list:
return "Unknown"
seen = []
for f, _ in sources_list:
lnk = _source_to_page_link(f)
if lnk not in seen:
seen.append(lnk)
if len(seen) > max_show:
return ", ".join(seen[:max_show]) + f" _(+{len(seen)-max_show} more)_"
return ", ".join(seen)