|
| 1 | +#!/usr/bin/env python3 |
| 2 | +import re |
| 3 | +import sys |
| 4 | +from pathlib import Path |
| 5 | + |
| 6 | +# Regex for Markdown links: [text](target) |
| 7 | +LINK_RE = re.compile(r"\[([^\]]+)\]\(([^)]+)\)") |
| 8 | + |
| 9 | +def slugify_heading(text: str) -> str: |
| 10 | + """Convert Markdown heading text to MkDocs anchor format.""" |
| 11 | + slug = text.strip().lower() |
| 12 | + slug = re.sub(r"[^\w\s-]", "", slug) # remove punctuation |
| 13 | + slug = re.sub(r"\s+", "-", slug) # spaces -> dashes |
| 14 | + return slug |
| 15 | + |
| 16 | + |
| 17 | +def extract_headings(md_file: Path): |
| 18 | + """Return a set of anchor slugs from headings in md files.""" |
| 19 | + headings = set() |
| 20 | + if not md_file.is_file(): |
| 21 | + return headings |
| 22 | + for line in md_file.read_text(encoding="utf-8").splitlines(): |
| 23 | + if line.startswith("#"): |
| 24 | + heading_text = line.lstrip("#").strip() |
| 25 | + headings.add(slugify_heading(heading_text)) |
| 26 | + return headings |
| 27 | + |
| 28 | +def check_md_file(md_file: Path): |
| 29 | + """Check links in md files.""" |
| 30 | + errors = [] |
| 31 | + if not md_file.is_file(): # <-- add this check |
| 32 | + return errors |
| 33 | + |
| 34 | + for line_number, line in enumerate(md_file.read_text(encoding="utf-8").splitlines(), start=1): |
| 35 | + |
| 36 | + stripped = line.strip() |
| 37 | + # Skip HTML and python comments |
| 38 | + if stripped.startswith("#"): |
| 39 | + continue |
| 40 | + elif stripped.startswith("<!--") and stripped.endswith("-->"): |
| 41 | + continue |
| 42 | + |
| 43 | + for match in LINK_RE.finditer(line): |
| 44 | + text, target = match.groups() |
| 45 | + |
| 46 | + # Skip external links |
| 47 | + if target.startswith(("http://", "https://", "mailto:")): |
| 48 | + continue |
| 49 | + |
| 50 | + # Remove leading slash for site-root relative links |
| 51 | + elif target.startswith("/"): |
| 52 | + target = target[1:] |
| 53 | + |
| 54 | + # Split anchor from file |
| 55 | + if "#" in target: |
| 56 | + if target.startswith("#"): |
| 57 | + file_part, anchor = md_file, target[1:] |
| 58 | + else: |
| 59 | + file_part, anchor = target.split("#", 1) |
| 60 | + else: |
| 61 | + file_part, anchor = target, None |
| 62 | + |
| 63 | + # Resolve relative path' |
| 64 | + target_path = Path(file_part) if isinstance(file_part, Path) else Path(file_part) #Make sure it's a Path object |
| 65 | + target_file = (md_file.parent / target_path).resolve() |
| 66 | + |
| 67 | + if not target_file.exists() and not target_file.suffix: |
| 68 | + target_file = (md_file.parent / (target_path.name + ".md")).resolve() |
| 69 | + if not target_file.exists(): |
| 70 | + errors.append(f"{md_file}:{line_number}: File not found -> {target}") |
| 71 | + continue |
| 72 | + |
| 73 | + if target_file.is_file() and anchor: |
| 74 | + headings = extract_headings(target_file) |
| 75 | + if anchor not in headings: |
| 76 | + errors.append(f"{md_file}:{line_number}: Anchor not found -> {target}") |
| 77 | + |
| 78 | + if target_file.is_dir(): |
| 79 | + continue |
| 80 | + |
| 81 | + return errors |
| 82 | + |
| 83 | + |
| 84 | +def main(md_dir): |
| 85 | + md_dir = Path(md_dir) |
| 86 | + all_errors = [] |
| 87 | + for md_file in md_dir.rglob("*.md"): |
| 88 | + all_errors.extend(check_md_file(md_file)) |
| 89 | + |
| 90 | + if all_errors: |
| 91 | + print(f'Found {len(all_errors)} internal link errors in md files:') |
| 92 | + for e in all_errors: |
| 93 | + print(e) |
| 94 | + return 1 |
| 95 | + print("No internal link errors found.") |
| 96 | + return 0 |
| 97 | + |
| 98 | +if __name__ == "__main__": |
| 99 | + exit(main(sys.argv[1])) |
0 commit comments