Files
myfileagent-pipeline/documentation/ci/build_manual.py
T

181 lines
9.3 KiB
Python
Raw 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
import sys
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
from ci.final_project import identity, read_bundle, digest
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"))
parser.add_argument("--review-bundle")
parser.add_argument("--release-version")
parser.add_argument("--jenkins-build", default="local")
parser.add_argument("--mode", choices=["fixture", "live"], default="fixture")
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)
review_files = None
if bool(args.review_bundle) != bool(args.release_version):
raise ValueError("Review bundle and release version must be supplied together")
if args.review_bundle:
if not re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+", args.release_version):
raise ValueError("Major.Minor.Changelist required")
if not re.fullmatch(r"[A-Za-z0-9_-]{1,80}", args.jenkins_build):
raise ValueError("Invalid Jenkins build identity")
review_files = read_bundle(args.review_bundle, identity(args.sha, args.run_id, args.attempt, args.mode))
metadata.update(release_version=args.release_version, mode=args.mode,
jenkins_build=args.jenkins_build,
review_sha256=digest(review_files["review.json"]),
reviewed_sha256=digest(review_files["reviewed.py"]))
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)
generated = latex_metadata(metadata)
if review_files:
review = json.loads(review_files["review.json"])
def tex(value):
mapping = {"\\": r"\textbackslash{}", "{": r"\{", "}": r"\}",
"_": r"\_", "%": r"\%", "&": r"\&", "#": r"\#", "$": r"\$",
"^": r"\textasciicircum{}", "~": r"\textasciitilde{}"}
return ''.join(mapping.get(c, c) for c in str(value))
fields = {"FinalVersion": args.release_version, "FinalMode": args.mode,
"FinalJenkinsBuild": args.jenkins_build, "FinalStatus": review["status"],
"FinalModel": review["model_id"], "FinalInputTokens": review["input_tokens"],
"FinalOutputTokens": review["output_tokens"]}
generated += r"\renewcommand{\DocumentVersion}{" + args.release_version + "}\n"
generated += r"\renewcommand{\AssignmentTitle}{DevOps Pipeline Final Project}" + "\n"
generated += r"\renewcommand{\AssignmentNumber}{Final}" + "\n"
generated += r"\renewcommand{\DocumentStatus}{" + args.mode + " validation}\n"
for key, value in fields.items():
generated += "\\newcommand{\\" + key + "}{" + tex(value) + "}\n"
(workspace / "final-reviewed.txt").write_bytes(review_files["reviewed.py"])
(workspace / "final-diff.txt").write_text(review["diff"] or "No changes (unchanged review).", encoding="utf-8")
# Generated run data only; the authored report chapter is maintained separately.
appendix = r"""\clearpage
\chapter*{Automated Review Run}
\noindent Release: \FinalVersion\\
Mode: \FinalMode\\
Status: \FinalStatus\\
Model: \FinalModel\\
Input tokens: \FinalInputTokens\\
Output tokens: \FinalOutputTokens\\
Jenkins build: \FinalJenkinsBuild
\section*{Reviewed source}
\lstinputlisting[basicstyle=\ttfamily\small,breaklines=true]{final-reviewed.txt}
\section*{Change log}
\lstinputlisting[basicstyle=\ttfamily\small,breaklines=true]{final-diff.txt}
"""
main_path = workspace / "main.tex"
main_path.write_text(main_path.read_text().replace(r"\end{document}", appendix + r"\end{document}"))
(workspace / "build-metadata.tex").write_text(generated, 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()