File size: 4,833 Bytes
549e098 7d6e4e0 549e098 37ae1e2 549e098 37ae1e2 1e54930 549e098 7d6e4e0 549e098 7d6e4e0 549e098 37ae1e2 549e098 7d6e4e0 37ae1e2 549e098 37ae1e2 549e098 1e54930 549e098 | 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 | #!/usr/bin/env python3
"""Lightweight URL checker for Markdown files.
This script intentionally uses only the Python standard library so contributors
can run it without installing project dependencies.
"""
from __future__ import annotations
import argparse
import concurrent.futures as futures
import re
import ssl
import sys
import time
import urllib.error
import urllib.request
from pathlib import Path
from urllib.parse import urlparse
URL_RE = re.compile(r'https?://[^\s)\]}>"]+')
CLAUDE_DOC_HOSTS = {"code.claude.com", "docs.anthropic.com"}
RETRYABLE_HTTP_CODES = {408, 425, 500, 502, 503, 504}
class RedirectHandler(urllib.request.HTTPRedirectHandler):
"""Follow permanent HTTP 308 redirects on Python versions that omit them."""
def http_error_308(self, req, fp, code, msg, headers): # type: ignore[no-untyped-def]
return self.http_error_302(req, fp, code, msg, headers)
def redirect_request(self, req, fp, code, msg, headers, newurl): # type: ignore[no-untyped-def]
if code == 308 and req.get_method() in {"GET", "HEAD"}:
code = 307
return super().redirect_request(req, fp, code, msg, headers, newurl)
def iter_urls(paths: list[Path]) -> list[str]:
urls: set[str] = set()
for path in paths:
if path.is_dir():
markdown_files = path.rglob("*.md")
else:
markdown_files = [path]
for markdown_file in markdown_files:
if ".git" in markdown_file.parts:
continue
text = markdown_file.read_text(encoding="utf-8")
urls.update(match.group(0).rstrip(".,;") for match in URL_RE.finditer(text))
return sorted(urls)
def check_url(url: str, timeout: float, attempts: int) -> tuple[bool, str]:
context = ssl._create_unverified_context()
opener = urllib.request.build_opener(
urllib.request.HTTPSHandler(context=context),
RedirectHandler(),
)
last_error = "unknown"
source_host = urlparse(url).netloc.lower()
for attempt in range(1, attempts + 1):
for method in ("HEAD", "GET"):
request = urllib.request.Request(
url,
method=method,
headers={"User-Agent": "awesome-loop-engineering-url-checker"},
)
try:
with opener.open(request, timeout=timeout) as response:
final_host = urlparse(response.geturl()).netloc.lower()
if source_host == "code.claude.com" and final_host not in CLAUDE_DOC_HOSTS:
return True, f"{response.status} restricted redirect"
return response.status < 400, f"{response.status} {method}"
except urllib.error.HTTPError as error:
final_host = urlparse(error.geturl()).netloc.lower()
if source_host == "code.claude.com" and final_host not in CLAUDE_DOC_HOSTS:
return True, f"{error.code} restricted redirect"
if error.code in {401, 403, 405, 406, 418, 429, 999}:
return True, f"{error.code} restricted"
if method == "HEAD":
continue
last_error = f"{error.code} {method}"
if error.code in RETRYABLE_HTTP_CODES:
break
return False, last_error
except Exception as error: # noqa: BLE001 - report URL checker failures plainly.
last_error = error.__class__.__name__
if method == "HEAD":
continue
if attempt < attempts:
time.sleep(min(1.5, 0.25 * attempt))
return False, last_error
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("paths", nargs="*", type=Path, default=[Path(".")])
parser.add_argument("--timeout", type=float, default=8.0)
parser.add_argument("--workers", type=int, default=12)
parser.add_argument("--attempts", type=int, default=3)
args = parser.parse_args()
failures: list[tuple[str, str]] = []
urls = iter_urls(args.paths)
with futures.ThreadPoolExecutor(max_workers=args.workers) as executor:
checks = {executor.submit(check_url, url, args.timeout, args.attempts): url for url in urls}
for check in futures.as_completed(checks):
url = checks[check]
ok, detail = check.result()
status = "ok" if ok else "fail"
print(f"{status:4} {detail:14} {url}", flush=True)
if not ok:
failures.append((url, detail))
if failures:
print("\nFailed URLs:", file=sys.stderr)
for url, detail in failures:
print(f"- {url} ({detail})", file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
raise SystemExit(main())
|