#!/usr/bin/env python3 """Lightweight relative-link check for active Markdown (not historical docs). Understands review-compact layout: links are resolved from the file's package path. Historical trees (docs/historical/, reference/historical/) are ignored. """ from __future__ import annotations import argparse import json import re import sys import zipfile from pathlib import Path from typing import Any, Iterable ROOT = Path(__file__).resolve().parents[1] TOOLS = Path(__file__).resolve().parent if str(TOOLS) not in sys.path: sys.path.insert(0, str(TOOLS)) MD_LINK_RE = re.compile(r"(? str: text = path.replace("\\", "/") while text.startswith("./"): text = text[2:] return text def _is_historical(path: str) -> bool: lower = f"/{_normalize(path).casefold()}/" return any(marker in lower for marker in ("/docs/historical/", "/reference/historical/")) def _strip_layout_prefix(path: str) -> str: logical = _normalize(path) if logical.casefold().startswith("cpld/"): logical = logical[len("CPLD/") :] if logical.startswith("CPLD/") else logical[5:] if logical.casefold().startswith("source/"): return logical[len("source/") :] return logical def _resolve_link(source_path: str, href: str) -> str | None: href = href.strip() if not href or href.startswith(("#", "http://", "https://", "mailto:")): return None href = href.split("#", 1)[0].split("?", 1)[0].strip() if not href: return None if href.startswith("/"): return href.lstrip("/") source_dir = Path(_strip_layout_prefix(source_path)).parent resolved = (source_dir / href).as_posix() # Normalize .. segments without escaping package root. parts: list[str] = [] for part in resolved.split("/"): if part in ("", "."): continue if part == "..": if parts: parts.pop() continue parts.append(part) return "/".join(parts) def iter_markdown_members(names: Iterable[str]) -> list[str]: out: list[str] = [] for name in names: logical = _normalize(name) if not logical.casefold().endswith((".md", ".markdown")): continue if _is_historical(logical): continue # Only check active software docs under source/ (or bare repo paths). stripped = _strip_layout_prefix(logical) if logical.casefold().startswith("cpld/") and not logical.casefold().startswith( "cpld/source/" ): # evidence/ copies are review entry points; links live in source/. continue if stripped.casefold().startswith(("docs/historical/", "reference/historical/")): continue out.append(logical) return sorted(out) def check_members( *, members: set[str], texts: dict[str, str], ) -> dict[str, Any]: """Check relative links among package/repo members. ``members`` keys are layout-normalized (may include CPLD/source/...). ``texts`` maps the same keys to markdown body. """ present_repo = {_strip_layout_prefix(m) for m in members} present_full = {_normalize(m) for m in members} failures: list[str] = [] present_dirs = { str(Path(p).parent.as_posix()) for p in present_repo if Path(p).parent.as_posix() not in {"", "."} } present_dirs.update( { p.rstrip("/") for p in present_repo if p.endswith("/") } ) for source, text in sorted(texts.items()): if _is_historical(source): continue for match in MD_LINK_RE.finditer(text): href = match.group(1) target = _resolve_link(source, href) if target is None: continue # Active docs may point at historical archives; those are not a release gate. if _is_historical(target) or target.casefold().rstrip("/").endswith( ("/historical", "docs/historical", "reference/historical") ): continue # Allow either repo-relative or full package path hits. ok = ( target in present_repo or target.rstrip("/") in present_dirs or target in present_full or f"source/{target}" in present_full or f"CPLD/source/{target}" in present_full or f"cpld/source/{target}".casefold() in {p.casefold() for p in present_full} ) if not ok: failures.append( f"broken_relative_link:{_strip_layout_prefix(source)}->{href}" ) # Explicit regression targets (remote audit reproductions). for source_rel, target_rel in REQUIRED_ACTIVE_TARGETS: source_keys = [ key for key in texts if _strip_layout_prefix(key).casefold() == source_rel.casefold() ] if not source_keys: failures.append(f"missing_active_doc:{source_rel}") continue if target_rel not in present_repo and f"source/{target_rel}" not in { _normalize(m) for m in members } and not any( _strip_layout_prefix(m).casefold() == target_rel.casefold() for m in members ): failures.append(f"missing_link_target:{source_rel}->{target_rel}") status = "pass" if not failures else "fail" return { "schema": "cpld-active-markdown-link-check-v1", "status": status, "failures": sorted(set(failures)), "checked_files": sorted(_strip_layout_prefix(k) for k in texts), "hardware_validation": "not_run", } def check_repo_root(root: Path) -> dict[str, Any]: root = root.resolve(strict=True) members: set[str] = set() texts: dict[str, str] = {} for path in root.rglob("*"): if path.is_symlink(): continue if not path.is_file() and not path.is_dir(): continue rel = path.relative_to(root).as_posix() # Keep historical paths in the member set so active docs may link to them, # but never treat historical markdown as sources under check. members.add(rel) if not path.is_file(): continue if rel.casefold().endswith((".md", ".markdown")) and not _is_historical(rel): # Skip non-active trees already filtered; also skip deep vendor. if any( part.startswith(".") for part in Path(rel).parts if part not in {".", ".."} ): continue if rel.casefold().startswith(("node_modules/", "reference/original/")): continue try: texts[rel] = path.read_text(encoding="utf-8") except (OSError, UnicodeError): failures_note = f"unreadable_markdown:{rel}" return { "schema": "cpld-active-markdown-link-check-v1", "status": "fail", "failures": [failures_note], "checked_files": [], "hardware_validation": "not_run", } # Restrict texts to active docs of interest + README/docs/*.md active_texts = { key: value for key, value in texts.items() if key in {"README.zh-CN.md", "README.md"} or key.casefold().startswith("docs/") or key.casefold().endswith("readme.zh-cn.md") } return check_members(members=members, texts=active_texts) def check_review_zip(zip_path: Path) -> dict[str, Any]: zip_path = zip_path.resolve(strict=True) members: set[str] = set() texts: dict[str, str] = {} with zipfile.ZipFile(zip_path, "r", allowZip64=True) as archive: names = list(archive.namelist()) members = {_normalize(name) for name in names if not name.endswith("/")} for name in iter_markdown_members(names): try: texts[name] = archive.read(name).decode("utf-8") except (KeyError, UnicodeDecodeError): return { "schema": "cpld-active-markdown-link-check-v1", "status": "fail", "failures": [f"unreadable_markdown:{name}"], "checked_files": [], "hardware_validation": "not_run", } return check_members(members=members, texts=texts) def check_extracted_review(root: Path) -> dict[str, Any]: """Fresh extraction root containing CPLD/source or source/.""" root = root.resolve(strict=True) source_root = root / "CPLD" / "source" if not source_root.is_dir(): source_root = root / "source" if not source_root.is_dir(): return { "schema": "cpld-active-markdown-link-check-v1", "status": "fail", "failures": ["missing_source_tree"], "checked_files": [], "hardware_validation": "not_run", } # Include evidence paths as present members so duplicated review entry # targets also count, but only validate links from source/. members: set[str] = set() for path in root.rglob("*"): if path.is_file() and not path.is_symlink(): members.add(path.relative_to(root).as_posix()) texts: dict[str, str] = {} for path in source_root.rglob("*.md"): if path.is_symlink(): continue rel = path.relative_to(root).as_posix() if _is_historical(rel): continue texts[rel] = path.read_text(encoding="utf-8") return check_members(members=members, texts=texts) def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--repo-root", type=Path, default=None) parser.add_argument("--zip", type=Path, default=None) parser.add_argument("--extract-root", type=Path, default=None) parser.add_argument("--json-out", type=Path, default=None) return parser def main(argv: list[str] | None = None) -> int: args = build_parser().parse_args(argv) if args.zip is not None: report = check_review_zip(args.zip) elif args.extract_root is not None: report = check_extracted_review(args.extract_root) else: report = check_repo_root(args.repo_root or ROOT) text = json.dumps(report, ensure_ascii=False, indent=2) + "\n" if args.json_out is not None: args.json_out.parent.mkdir(parents=True, exist_ok=True) args.json_out.write_text(text, encoding="utf-8") sys.stdout.write(text) return 0 if report.get("status") == "pass" else 1 if __name__ == "__main__": raise SystemExit(main())