#!/usr/bin/env python3 """Broken-link check for a repo's user-facing docs and a GitHub Release body. Usage: check_doc_links.py [ ] [--files README.md AI_KURULUM.md ...] Reads files from (e.g. origin/main or a release branch) via `git show`, so the worktree state does not matter. Checks: - external http(s) links: curl -L, anything but 200 is reported - relative links: target must exist in 's tree - in-page anchors (#...): must match a heading slug (GitHub style, emoji dropped) With the release notes body (`gh release view`) is checked too. Code blocks are skipped; 127.0.0.1/localhost links are ignored. Exit code 1 if anything is broken. """ import os, re, subprocess, sys DEFAULT_FILES = ["README.md", "AI_KURULUM.md", "LICENSE", "docs/macos-yayin.md", "ACCEPTANCE_RESULTS.md"] LINK = re.compile(r'\[([^\]]*)\]\(([^)\s]+)(?:\s+"[^"]*")?\)') BARE = re.compile(r'(?\]`"\']+)') def run(*a): r = subprocess.run(a, capture_output=True, text=True) return r.stdout if r.returncode == 0 else None def slug(h): h = re.sub(r'[^\w\- ]', '', h.strip().lower(), flags=re.UNICODE) return h.replace(' ', '-') def main(): args = sys.argv[1:] files = DEFAULT_FILES if "--files" in args: i = args.index("--files"); files = args[i + 1:]; args = args[:i] repo, ref = args[0], args[1] texts = {f: run("git", "-C", repo, "show", f"{ref}:{f}") for f in files} if len(args) >= 4: texts[f"RELEASE {args[3]}"] = run("gh", "release", "view", args[3], "-R", args[2], "--json", "body", "-q", ".body") tree = set((run("git", "-C", repo, "ls-tree", "-r", "--name-only", ref) or "").split("\n")) anchors = {f: {slug(m) for m in re.findall(r'^#{1,6}\s+(.*)$', t or "", flags=re.M)} for f, t in texts.items()} ext, broken = {}, [] for f, t in texts.items(): if t is None: print(f"skip (not in {ref}): {f}"); continue t = re.sub(r'```.*?```', '', t, flags=re.S) for m in LINK.finditer(t): u = m.group(2) if u.startswith("http"): ext.setdefault(u, set()).add(f) elif u.startswith("#"): if u[1:] not in anchors[f]: broken.append(("anchor", f, u)) elif not u.startswith("mailto:"): p = u.partition("#")[0] base = os.path.dirname(f) if f in files else "" tgt = os.path.normpath(os.path.join(base, p)) if tgt not in tree and not any(x.startswith(tgt + "/") for x in tree): broken.append(("relative", f, u)) for m in BARE.finditer(t): ext.setdefault(m.group(1).rstrip('.,;:'), set()).add(f) for u, fs in ext.items(): if "127.0.0.1" in u or "localhost" in u: continue code = run("curl", "-s", "-o", "/dev/null", "-L", "--max-time", "20", "-A", "Mozilla/5.0", "-w", "%{http_code}", u) if (code or "").strip() != "200": broken.append((f"http {code}", ",".join(sorted(fs)), u)) print(f"external links checked: {len(ext)}; broken: {len(broken)}") for b in broken: print(" ", *b) sys.exit(1 if broken else 0) if __name__ == "__main__": main()