|
| 1 | +# Copyright (c) Microsoft Corporation. |
| 2 | +# Licensed under the MIT license. |
| 3 | + |
| 4 | +"""Build the configured documentation PDF and verify the export, not just the exit code.""" |
| 5 | + |
| 6 | +from __future__ import annotations |
| 7 | + |
| 8 | +import re |
| 9 | +import shutil |
| 10 | +import subprocess |
| 11 | +import sys |
| 12 | +from pathlib import Path |
| 13 | + |
| 14 | +import yaml |
| 15 | +from pypdf import PdfReader |
| 16 | +from pypdf.errors import PdfReadError |
| 17 | + |
| 18 | + |
| 19 | +def _pdf_output(doc_root: Path) -> Path: |
| 20 | + config = yaml.safe_load((doc_root / "myst.yml").read_text(encoding="utf-8")) |
| 21 | + project = config.get("project") if isinstance(config, dict) else None |
| 22 | + exports = project.get("exports") if isinstance(project, dict) else None |
| 23 | + if not isinstance(exports, list): |
| 24 | + raise ValueError("myst.yml must declare a project PDF export.") |
| 25 | + pdf_exports = [export for export in exports if isinstance(export, dict) and export.get("format") == "pdf"] |
| 26 | + if len(pdf_exports) != 1: |
| 27 | + raise ValueError("Expected exactly one project PDF export in myst.yml.") |
| 28 | + export = pdf_exports[0] |
| 29 | + if export.get("template") != "plain_latex_book": |
| 30 | + raise ValueError("The checked PDF build supports plain_latex_book with xelatex.") |
| 31 | + output = export.get("output") |
| 32 | + if not isinstance(output, str) or not output or Path(output).suffix != ".pdf": |
| 33 | + raise ValueError("The PDF export must declare an output ending in .pdf.") |
| 34 | + output_path = (doc_root / output).resolve() |
| 35 | + if not output_path.is_relative_to(doc_root.resolve()): |
| 36 | + raise ValueError("The PDF output must stay inside the documentation directory.") |
| 37 | + return output_path |
| 38 | + |
| 39 | + |
| 40 | +def _signature(path: Path) -> tuple[int, int, int] | None: |
| 41 | + if not path.exists(): |
| 42 | + return None |
| 43 | + stat = path.stat() |
| 44 | + return stat.st_mtime_ns, stat.st_ctime_ns, stat.st_size |
| 45 | + |
| 46 | + |
| 47 | +def _require_fresh_file(*, path: Path, previous: tuple[int, int, int] | None) -> None: |
| 48 | + if not path.is_file() or path.stat().st_size == 0: |
| 49 | + raise ValueError(f"PDF export did not produce a nonempty file: {path}") |
| 50 | + if _signature(path) == previous: |
| 51 | + raise ValueError(f"PDF export left a stale file unchanged: {path}") |
| 52 | + |
| 53 | + |
| 54 | +def _check_engine_log(path: Path) -> None: |
| 55 | + fatal = re.compile( |
| 56 | + r"^!|(?:LaTeX|Package \S+|Class \S+) Error:|Emergency stop|Fatal error occurred" |
| 57 | + r"|^Latexmk: (?:Errors|Failure)|^Collected error summary" |
| 58 | + ) |
| 59 | + for line_number, line in enumerate(path.read_text(encoding="utf-8", errors="replace").splitlines(), start=1): |
| 60 | + if fatal.search(line): |
| 61 | + raise ValueError(f"Fatal LaTeX diagnostic in {path}:{line_number}: {line}") |
| 62 | + |
| 63 | + |
| 64 | +def build_pdf(doc_root: Path) -> int: |
| 65 | + """Build the repository's XeLaTeX PDF export and reject missing, stale, or failed output.""" |
| 66 | + output = _pdf_output(doc_root) |
| 67 | + missing = [tool for tool in ("latexmk", "xelatex") if shutil.which(tool) is None] |
| 68 | + if missing: |
| 69 | + raise ValueError( |
| 70 | + f"Missing PDF prerequisites on PATH: {', '.join(missing)}. " |
| 71 | + "Provision LaTeX separately; use the HTML-only build if a PDF is not needed." |
| 72 | + ) |
| 73 | + logs_dir = output.parent / f"{output.stem}_pdf_logs" |
| 74 | + logs = [logs_dir / f"{output.stem}.log", logs_dir / f"{output.stem}.shell.log"] |
| 75 | + previous = {path: _signature(path) for path in [output, *logs]} |
| 76 | + result = subprocess.run( |
| 77 | + [sys.executable, "-m", "jupyter_book", "build", "--site", "--pdf", "--strict", "--logs"], |
| 78 | + cwd=doc_root, |
| 79 | + check=False, |
| 80 | + ) |
| 81 | + if result.returncode != 0: |
| 82 | + print(f"ERROR: Jupyter Book PDF build exited with code {result.returncode}.", file=sys.stderr) |
| 83 | + return result.returncode |
| 84 | + for path in [output, *logs]: |
| 85 | + _require_fresh_file(path=path, previous=previous[path]) |
| 86 | + for log in logs: |
| 87 | + _check_engine_log(log) |
| 88 | + reader = PdfReader(output, strict=True) |
| 89 | + if not reader.pages: |
| 90 | + raise ValueError(f"PDF export contains no pages: {output}") |
| 91 | + print(f"[OK] Verified fresh PDF export and native LaTeX logs: {output}") |
| 92 | + return 0 |
| 93 | + |
| 94 | + |
| 95 | +def main() -> int: |
| 96 | + """Run the checked export from this checkout's documentation directory.""" |
| 97 | + doc_root = Path(__file__).resolve().parents[1] / "doc" |
| 98 | + try: |
| 99 | + return build_pdf(doc_root) |
| 100 | + except (OSError, ValueError, yaml.YAMLError, PdfReadError) as error: |
| 101 | + print(f"ERROR: {error}", file=sys.stderr) |
| 102 | + return 1 |
| 103 | + |
| 104 | + |
| 105 | +if __name__ == "__main__": |
| 106 | + sys.exit(main()) |
0 commit comments