-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcheck_markdown_links.py
More file actions
executable file
·84 lines (64 loc) · 2.23 KB
/
Copy pathcheck_markdown_links.py
File metadata and controls
executable file
·84 lines (64 loc) · 2.23 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
#!/usr/bin/env python3
"""Check local Markdown links for missing files or directories."""
from __future__ import annotations
import re
import sys
from pathlib import Path
from urllib.parse import unquote, urlparse
ROOT = Path(__file__).resolve().parents[1]
LINK_PATTERN = re.compile(r"(?<!!)\[[^\]]+\]\(([^)]+)\)")
def is_external(target: str) -> bool:
parsed = urlparse(target)
return parsed.scheme in {"http", "https", "mailto", "tel"}
def normalize_target(raw_target: str) -> str:
target = raw_target.strip()
if not target:
return target
if target[0] in {"'", '"'} and target[-1:] == target[0]:
target = target[1:-1]
target = target.split("#", 1)[0]
return unquote(target)
def iter_markdown_files() -> list[Path]:
return sorted(
path
for path in ROOT.rglob("*.md")
if ".git" not in path.parts and path.is_file()
)
def main() -> int:
broken: list[str] = []
checked = 0
for md_file in iter_markdown_files():
text = md_file.read_text(encoding="utf-8", errors="replace")
for match in LINK_PATTERN.finditer(text):
raw_target = match.group(1).strip()
target = normalize_target(raw_target)
if not target or is_external(target):
continue
if target.startswith("#"):
continue
checked += 1
resolved = (md_file.parent / target).resolve()
try:
resolved.relative_to(ROOT)
except ValueError:
broken.append(
f"{md_file.relative_to(ROOT)}: link escapes repo: {raw_target}"
)
continue
if not resolved.exists():
broken.append(
f"{md_file.relative_to(ROOT)}: missing target: {raw_target}"
)
print("Markdown link check")
print("===================")
print(f"Markdown files: {len(iter_markdown_files())}")
print(f"Local links checked: {checked}")
if broken:
print("\nBroken links:")
for item in broken:
print(f"- {item}")
return 1
print("\nAll local Markdown links resolved.")
return 0
if __name__ == "__main__":
sys.exit(main())