Files

124 lines
5.9 KiB
Python
Raw Permalink Normal View History

#!/usr/bin/env python3
"""Build the manual in a fresh workspace; publish a PDF only after success.
Requires the recorded CI image to supply latexmk, TeX Live, minted support,
BibTeX, makeindex, and pypdf. Run from a checked-out repository.
"""
import argparse
import hashlib
import json
import os
from pathlib import Path
import re
import shutil
import subprocess
import tempfile
def build_metadata(sha, run_number, run_id, attempt):
if not re.fullmatch(r"[0-9a-f]{40}|[0-9a-f]{64}", sha):
raise ValueError("A full lowercase Git commit hash is required")
for name, value in (("run number", run_number), ("run ID", run_id), ("attempt", attempt)):
if not re.fullmatch(r"[1-9][0-9]*", value):
raise ValueError(f"Invalid {name}: a positive integer is required")
short = sha[:7]
suffix = f"+build.{run_number}.{short}.attempt.{attempt}"
url = f"https://myfileagent.tech/myfileagent/myfileagent-pipeline/actions/runs/{run_id}"
return {
"commit": sha, "run_number": run_number, "run_id": run_id,
"attempt": attempt, "suffix": suffix, "run_url": url,
}
def latex_metadata(metadata):
# All interpolated fields were validated above or use a fixed trusted URL.
fields = {
"BuildSuffix": metadata["suffix"],
"BuildCommit": metadata["commit"],
"BuildRun": metadata["run_number"],
"BuildRunURL": metadata["run_url"],
}
return "% Generated in the build workspace. Do not commit.\n" + "".join(
f"\\renewcommand{{\\{key}}}{{{value}}}\n" for key, value in fields.items()
)
def copy_sources(source, destination):
extensions = {".tex", ".cls", ".sty", ".bst", ".bib", ".png", ".jpg", ".jpeg", ".svg", ".txt"}
excluded = {".git", "_minted", "build", "output", "outputs", "__pycache__", "node_modules"}
for path in source.rglob("*"):
relative = path.relative_to(source)
if any(part in excluded or part.startswith("_minted-") for part in relative.parts):
continue
if path.is_symlink():
raise ValueError(f"Unexpected source symlink: {relative}")
if path.is_file() and path.suffix.lower() in extensions and path.name != "build-metadata.tex":
target = destination / relative
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(path, target)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--sha", default=os.environ.get("GITEA_SHA", ""))
parser.add_argument("--run-number", default=os.environ.get("GITEA_RUN_NUMBER", ""))
parser.add_argument("--run-id", default=os.environ.get("GITEA_RUN_ID", ""))
parser.add_argument("--attempt", default=os.environ.get("GITEA_RUN_ATTEMPT", "1"))
args = parser.parse_args()
metadata = build_metadata(args.sha, args.run_number, args.run_id, args.attempt)
source = Path(__file__).resolve().parents[1]
revision = subprocess.check_output(["git", "-C", str(source), "rev-parse", "HEAD"], text=True).strip()
if revision != metadata["commit"]:
raise ValueError("Checked-out HEAD differs from the triggering commit")
version_match = re.search(r"\\newcommand\{\\DocumentVersion\}\{([^}]+)\}", (source / "main.tex").read_text())
if not version_match:
raise ValueError("Human-maintained document version is missing")
metadata["document_version"] = version_match.group(1)
output = source / "build"
output.mkdir(exist_ok=True)
# Remove only this build's known publish targets, so a failed rebuild cannot
# leave an older PDF available for upload.
for name in ("main.pdf", "build-manifest.json"):
(output / name).unlink(missing_ok=True)
with tempfile.TemporaryDirectory(prefix="manual-ci-") as temp:
workspace = Path(temp)
copy_sources(source, workspace)
(workspace / "build-metadata.tex").write_text(latex_metadata(metadata), encoding="utf-8")
# Shell escape is needed by the current minted source. Run only trusted
# team source in the isolated job, with no host/Docker socket mounts.
command = ["latexmk", "-pdf", "-shell-escape", "-interaction=nonstopmode", "-halt-on-error", "-file-line-error", "main.tex"]
try:
result = subprocess.run(command, cwd=workspace, check=False)
log_path = workspace / "main.log"
if log_path.exists():
shutil.copy2(log_path, output / "main.log")
if result.returncode:
raise RuntimeError(f"LaTeX compilation failed (exit {result.returncode})")
pdf = workspace / "main.pdf"
if not pdf.is_file() or pdf.stat().st_size == 0:
raise RuntimeError("Compilation did not create a nonempty main.pdf")
from pypdf import PdfReader
reader = PdfReader(pdf)
if not reader.pages:
raise RuntimeError("Generated PDF has no pages")
text = "\n".join(page.extract_text() or "" for page in reader.pages[:5])
for expected in (metadata["suffix"], metadata["commit"]):
if expected not in text:
raise RuntimeError(f"Visible PDF build identity is missing: {expected}")
if log_path.exists():
log = log_path.read_text(errors="replace")
if re.search(r"There were undefined (references|citations)|There were multiply-defined labels", log):
raise RuntimeError("Unresolved references/citations or duplicate labels in PDF")
metadata["pdf_sha256"] = hashlib.sha256(pdf.read_bytes()).hexdigest()
metadata["pages"] = len(reader.pages)
shutil.copy2(pdf, output / "main.pdf")
(output / "build-manifest.json").write_text(json.dumps(metadata, indent=2) + "\n", encoding="utf-8")
finally:
# A compiler failure must never be hidden by artifact publication.
pass
print(json.dumps(metadata, indent=2))
if __name__ == "__main__":
main()