|
| 1 | +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. |
| 2 | +# SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +"""Warm link caches or check rendered HTML through the configured pre-commit hooks.""" |
| 5 | + |
| 6 | +from __future__ import annotations |
| 7 | + |
| 8 | +import argparse |
| 9 | +import json |
| 10 | +import os |
| 11 | +import subprocess |
| 12 | +import sys |
| 13 | +import uuid |
| 14 | +from pathlib import Path |
| 15 | + |
| 16 | +from retry_lychee import LINK_CHECK_FAILURE, read_report, retry_lychee |
| 17 | + |
| 18 | +ROOT = Path(__file__).resolve().parents[2] |
| 19 | + |
| 20 | + |
| 21 | +def collect_reports(directory: Path, output: Path, precommit_code: int) -> int: |
| 22 | + """Distinguish native link failures from pre-commit setup or hook failures.""" |
| 23 | + statuses = sorted(directory.glob("*.status.json")) |
| 24 | + reports = set(directory.glob("*.json")) - set(statuses) |
| 25 | + expected = {path.with_name(path.name.removesuffix(".status.json") + ".json") for path in statuses} |
| 26 | + if not statuses: |
| 27 | + raise ValueError("The configured Lychee hook produced no native status; pre-commit setup or execution failed") |
| 28 | + merged = {"total": 0, "errors": 0, "timeouts": 0, "error_map": {}, "timeout_map": {}} |
| 29 | + native_codes = [] |
| 30 | + for status in statuses: |
| 31 | + metadata = json.loads(status.read_text(encoding="utf-8")) |
| 32 | + if not isinstance(metadata, dict) or type(metadata.get("exit_code")) is not int: |
| 33 | + raise ValueError(f"Invalid native Lychee status: {status}") |
| 34 | + code = metadata["exit_code"] |
| 35 | + if code not in (0, LINK_CHECK_FAILURE): |
| 36 | + raise ValueError(f"Native Lychee execution failed with exit code {code}: {status}") |
| 37 | + native_codes.append(code) |
| 38 | + report = status.with_name(status.name.removesuffix(".status.json") + ".json") |
| 39 | + # A pre-commit chunk can contain no links; the complete scan must not be empty. |
| 40 | + read_report(report, code, allow_empty=True) |
| 41 | + data = json.loads(report.read_text(encoding="utf-8")) |
| 42 | + for name in ("total", "errors", "timeouts"): |
| 43 | + merged[name] += data[name] |
| 44 | + for name in ("error_map", "timeout_map"): |
| 45 | + for source, responses in data[name].items(): |
| 46 | + merged[name].setdefault(source, []).extend(responses) |
| 47 | + if reports != expected: |
| 48 | + raise ValueError("Native Lychee reports and completed invocation statuses do not match") |
| 49 | + code = LINK_CHECK_FAILURE if LINK_CHECK_FAILURE in native_codes else 0 |
| 50 | + if precommit_code != int(code != 0): |
| 51 | + raise ValueError(f"pre-commit exit {precommit_code} disagrees with native Lychee exit {code}") |
| 52 | + output.write_text(json.dumps(merged), encoding="utf-8") |
| 53 | + read_report(output, code) |
| 54 | + return code |
| 55 | + |
| 56 | + |
| 57 | +def run_hook(kind: str, report: Path) -> int: |
| 58 | + """Run the real hook, retaining every native chunk report for diagnostics.""" |
| 59 | + directory = report.parent / f"{report.stem}-parts" / uuid.uuid4().hex |
| 60 | + directory.mkdir(parents=True) |
| 61 | + hook = "lychee" if kind == "authored" else "lychee-rendered" |
| 62 | + environment = os.environ.copy() |
| 63 | + environment["LYCHEE_REPORT_DIR"] = str(directory) |
| 64 | + environment["PYTHONUTF8"] = "1" |
| 65 | + environment["SKIP"] = ",".join( |
| 66 | + name.strip() for name in environment.get("SKIP", "").split(",") if name.strip() and name.strip() != hook |
| 67 | + ) |
| 68 | + command = [sys.executable, "-m", "pre_commit", "run", hook, "--all-files", "--show-diff-on-failure"] |
| 69 | + if kind == "rendered": |
| 70 | + command.extend(["--hook-stage", "manual"]) |
| 71 | + result = subprocess.run(command, cwd=ROOT, env=environment, check=False) # noqa: S603 |
| 72 | + return collect_reports(directory, report, result.returncode) |
| 73 | + |
| 74 | + |
| 75 | +def run_checks(kind: str, report: Path, max_attempts: int = 3, *, policy: str = "check") -> int: |
| 76 | + if max_attempts < 1: |
| 77 | + raise ValueError("max-attempts must be positive") |
| 78 | + report = report.resolve() |
| 79 | + report.parent.mkdir(parents=True, exist_ok=True) |
| 80 | + return retry_lychee( |
| 81 | + run_hook(kind, report), |
| 82 | + report, |
| 83 | + max_attempts, |
| 84 | + policy=policy, |
| 85 | + run_attempt=lambda path: run_hook(kind, path), |
| 86 | + ) |
| 87 | + |
| 88 | + |
| 89 | +def main(arguments: list[str] | None = None) -> int: |
| 90 | + parser = argparse.ArgumentParser(description=__doc__) |
| 91 | + parser.add_argument("kind", choices=("authored", "rendered")) |
| 92 | + parser.add_argument("--policy", choices=("cache-warm", "check"), default="check") |
| 93 | + parser.add_argument("--max-attempts", type=int, default=3) |
| 94 | + parser.add_argument("--report", type=Path, required=True) |
| 95 | + args = parser.parse_args(arguments) |
| 96 | + try: |
| 97 | + return run_checks(args.kind, args.report, args.max_attempts, policy=args.policy) |
| 98 | + except (OSError, ValueError) as error: |
| 99 | + print(f"::error::{error}", flush=True) |
| 100 | + return 1 |
| 101 | + |
| 102 | + |
| 103 | +if __name__ == "__main__": |
| 104 | + raise SystemExit(main()) |
0 commit comments