|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +Simple script to check internal links with HTTP requests. |
| 4 | +""" |
| 5 | + |
| 6 | +import json |
| 7 | +import re |
| 8 | +from pathlib import Path |
| 9 | +from urllib.parse import urljoin |
| 10 | + |
| 11 | +import requests |
| 12 | + |
| 13 | + |
| 14 | +def find_internal_links(content): |
| 15 | + """Find all internal links in markdown content.""" |
| 16 | + links = [] |
| 17 | + pattern = r"\[([^\]]+)\]\(([^)]+)\)" |
| 18 | + |
| 19 | + for match in re.finditer(pattern, content): |
| 20 | + text = match.group(1) |
| 21 | + url = match.group(2) |
| 22 | + |
| 23 | + # Skip external links |
| 24 | + if url.startswith(("http://", "https://", "mailto:", "tel:")): |
| 25 | + continue |
| 26 | + |
| 27 | + links.append((text, url)) |
| 28 | + |
| 29 | + return links |
| 30 | + |
| 31 | + |
| 32 | +def resolve_link_url(base_url, md_file, link_url): |
| 33 | + """Resolve the real URL as a browser would from the markdown file location.""" |
| 34 | + # If link is absolute (starts with /), join with base_url |
| 35 | + if link_url.startswith("/"): |
| 36 | + return urljoin(base_url, link_url) |
| 37 | + # If link is relative, join with the file's directory path |
| 38 | + else: |
| 39 | + # Get the directory of the markdown file relative to docs/ |
| 40 | + md_dir = Path(md_file).parent |
| 41 | + # Build the relative path as it would be in the site |
| 42 | + rel_path = (md_dir / link_url).as_posix() |
| 43 | + # Remove any leading './' for clean URLs |
| 44 | + if rel_path.startswith("./"): |
| 45 | + rel_path = rel_path[2:] |
| 46 | + return urljoin(base_url + "/", rel_path) |
| 47 | + |
| 48 | + |
| 49 | +def check_link(base_url, link_url, current_file): |
| 50 | + """Check if a link returns 200 or 404.""" |
| 51 | + try: |
| 52 | + # Handle anchor links - they should resolve from current page |
| 53 | + if link_url.startswith("#"): |
| 54 | + # Build URL from current file path |
| 55 | + file_path = current_file.replace(".md", "/") |
| 56 | + if not file_path.startswith("/"): |
| 57 | + file_path = "/" + file_path |
| 58 | + full_url = urljoin(base_url, file_path + link_url) |
| 59 | + else: |
| 60 | + # For relative links, resolve from current file's directory |
| 61 | + if not link_url.startswith("/"): |
| 62 | + # Get current file's directory |
| 63 | + current_dir = str(Path(current_file).parent) |
| 64 | + if current_dir != ".": |
| 65 | + # Resolve relative to current directory |
| 66 | + resolved_path = str(Path(current_dir) / link_url) |
| 67 | + else: |
| 68 | + resolved_path = link_url |
| 69 | + |
| 70 | + # Convert to URL format |
| 71 | + if not resolved_path.startswith("/"): |
| 72 | + resolved_path = "/" + resolved_path |
| 73 | + full_url = urljoin(base_url, resolved_path) |
| 74 | + else: |
| 75 | + # Absolute path from site root |
| 76 | + full_url = urljoin(base_url, link_url) |
| 77 | + |
| 78 | + # Make request |
| 79 | + response = requests.get(full_url, timeout=5) |
| 80 | + |
| 81 | + if response.status_code == 200: |
| 82 | + return True, "200 OK" |
| 83 | + elif response.status_code == 404: |
| 84 | + return False, "404 Not Found" |
| 85 | + else: |
| 86 | + return False, f"HTTP {response.status_code}" |
| 87 | + |
| 88 | + except requests.RequestException as e: |
| 89 | + return False, f"Error: {e}" |
| 90 | + |
| 91 | + |
| 92 | +def main(): |
| 93 | + base_url = "http://127.0.0.1:8000" |
| 94 | + docs_dir = Path("docs") |
| 95 | + |
| 96 | + print(f"🔍 Checking internal links against {base_url}") |
| 97 | + print("=" * 50) |
| 98 | + |
| 99 | + broken_links = [] |
| 100 | + working_links = [] |
| 101 | + |
| 102 | + # Find all markdown files |
| 103 | + for md_file in docs_dir.rglob("*.md"): |
| 104 | + try: |
| 105 | + with open(md_file, "r", encoding="utf-8") as f: |
| 106 | + content = f.read() |
| 107 | + |
| 108 | + links = find_internal_links(content) |
| 109 | + |
| 110 | + for text, url in links: |
| 111 | + is_working, status = check_link( |
| 112 | + base_url, url, str(md_file.relative_to(docs_dir)) |
| 113 | + ) |
| 114 | + |
| 115 | + result = { |
| 116 | + "file": str(md_file.relative_to(docs_dir)), |
| 117 | + "text": text, |
| 118 | + "url": url, |
| 119 | + "full_url": ( |
| 120 | + urljoin(base_url, url) |
| 121 | + if not url.startswith("#") |
| 122 | + else urljoin( |
| 123 | + base_url, |
| 124 | + str(md_file.relative_to(docs_dir)).replace(".md", "/") |
| 125 | + + url, |
| 126 | + ) |
| 127 | + ), |
| 128 | + "status": status, |
| 129 | + "line": content[: content.find(f"[{text}]({url})")].count("\n") + 1, |
| 130 | + } |
| 131 | + |
| 132 | + if is_working: |
| 133 | + working_links.append(result) |
| 134 | + else: |
| 135 | + broken_links.append(result) |
| 136 | + |
| 137 | + except Exception as e: |
| 138 | + print(f"❌ Error reading {md_file}: {e}") |
| 139 | + |
| 140 | + # Print summary |
| 141 | + print(f"✅ Working links: {len(working_links)}") |
| 142 | + print(f"❌ Broken links: {len(broken_links)}") |
| 143 | + |
| 144 | + # Save results to JSON |
| 145 | + results = { |
| 146 | + "summary": { |
| 147 | + "total_files_scanned": len(list(docs_dir.rglob("*.md"))), |
| 148 | + "working_links": len(working_links), |
| 149 | + "broken_links": len(broken_links), |
| 150 | + "base_url": base_url, |
| 151 | + }, |
| 152 | + "broken_links": broken_links, |
| 153 | + "working_links": working_links, |
| 154 | + } |
| 155 | + |
| 156 | + # Save to JSON file |
| 157 | + output_file = "broken_links.json" |
| 158 | + with open(output_file, "w", encoding="utf-8") as f: |
| 159 | + json.dump(results, f, indent=2, ensure_ascii=False) |
| 160 | + |
| 161 | + print(f"\n📄 Results saved to: {output_file}") |
| 162 | + |
| 163 | + # Show some broken links in console |
| 164 | + if broken_links: |
| 165 | + print(f"\n🔴 BROKEN LINKS (showing first 10):") |
| 166 | + print("-" * 50) |
| 167 | + for link in broken_links[:10]: |
| 168 | + print(f"📄 {link['file']}:{link['line']}") |
| 169 | + print(f" Text: {link['text']}") |
| 170 | + print(f" URL: {link['url']}") |
| 171 | + print(f" Full URL: {link['full_url']}") |
| 172 | + print(f" Status: {link['status']}") |
| 173 | + print() |
| 174 | + |
| 175 | + |
| 176 | +if __name__ == "__main__": |
| 177 | + main() |
0 commit comments