#!/usr/bin/env python3 """Freeze actual pdfLaTeX format/article inputs from recorder output. This is reference infrastructure, never a runtime compiler fallback. Two full reference runs verify that the discovered source/resource closure stayed fixed. Generated fmt/aux/PDF files are artifacts, not native-format implementations. """ import argparse from concurrent.futures import ThreadPoolExecutor import hashlib import json import os from pathlib import Path import re import shutil import stat import subprocess import xml.etree.ElementTree as ET ROOT = Path(__file__).resolve().parents[1] FIXTURES = ROOT / "examples/native-format-stage" CASES = ["a0-minimal", "a1-fonts-10", "a1-fonts-11", "a1-fonts-12", "a2-math", "a3-pages", "a4-project"] ROOT_VARIABLES = ["TEXMFDIST", "TEXMFLOCAL", "TEXMFSYSCONFIG", "TEXMFSYSVAR", "TEXMFCONFIG", "TEXMFVAR", "TEXMFHOME"] def sha(path): return hashlib.sha256(path.read_bytes()).hexdigest() def command(args, cwd, env=None): result = subprocess.run([str(x) for x in args], cwd=cwd, env=env, capture_output=True, text=True, timeout=120) return result def roots(): result = {} for variable in ROOT_VARIABLES: value = subprocess.check_output(["kpsewhich", f"--var-value={variable}"], text=True).strip() if value and Path(value).is_dir(): result[variable] = Path(value).resolve() return result def classify(path, job, root_paths): if path.is_relative_to(FIXTURES): return "PROJECT", path.relative_to(FIXTURES).as_posix() if path.is_relative_to(job): return "GENERATED", path.relative_to(job).as_posix() for name, root in sorted(root_paths.items(), key=lambda x: len(str(x[1])), reverse=True): if path.is_relative_to(root): return name, path.relative_to(root).as_posix() return "EXTERNAL", path.as_posix() def recorder(path, job, root_paths): resources = {} reads = [] specials = [] for line in path.read_text().splitlines(): if not line.startswith("INPUT "): continue name = line[6:] actual = (job / name).resolve() mode = actual.stat().st_mode namespace, relative = classify(actual, job.parent, root_paths) if namespace == "GENERATED": reads.append({"namespace": namespace, "path": relative}) elif stat.S_ISREG(mode): key = namespace + ":" + relative item = dict(namespace=namespace, path=relative, bytes=actual.stat().st_size, sha256=sha(actual)) resources[key] = (actual, item) reads.append({"namespace": namespace, "path": relative}) else: # A real device input (such as /dev/null) is recorded as a device, # never fabricated as an empty regular source or omitted silently. specials.append(dict(path=str(actual), mode=stat.S_IFMT(mode))) return resources, reads, specials def run_reference(output, entry, root_paths): output.mkdir(parents=True, exist_ok=True) format_dir = output / "format" format_dir.mkdir(exist_ok=True) env = {**os.environ, "TEXINPUTS": ":"} result = command(["pdftex", "-ini", "-etex", "-interaction=nonstopmode", "-halt-on-error", "-recorder", "-jobname=reference", entry], format_dir, env) (format_dir / "stdout.txt").write_text(result.stdout) (format_dir / "stderr.txt").write_text(result.stderr) if result.returncode or not (format_dir / "reference.fmt").is_file(): raise RuntimeError(f"real format creation failed; see {format_dir}") resources, format_reads, specials = recorder(format_dir / "reference.fls", format_dir, root_paths) def compile_case(name): project = FIXTURES / name source = project / "main.tex" directory = output / name directory.mkdir(exist_ok=True) env = {**os.environ, "TEXINPUTS": str(project) + os.pathsep} auxiliary = [] for number in range(1, 4): result = command(["pdftex", "-fmt=" + str(format_dir / "reference.fmt"), "-interaction=nonstopmode", "-halt-on-error", "-recorder", source], directory, env) (directory / f"pass-{number}-stdout.txt").write_text(result.stdout) (directory / f"pass-{number}-stderr.txt").write_text(result.stderr) if result.returncode: raise RuntimeError(f"real article {name} pass {number} failed; see {directory}") auxiliary.append({p.name: sha(p) for p in directory.glob("*.aux")}) if auxiliary[1] != auxiliary[2]: raise RuntimeError(f"aux files did not converge for {name}") if "undefined references" in result.stdout or re.search(r"LaTeX Warning: Reference .* undefined", result.stdout): raise RuntimeError(f"unresolved reference in {name}") pdf = directory / "main.pdf" info = subprocess.check_output(["pdfinfo", str(pdf)], text=True) pages = int(re.search(r"^Pages:\s*(\d+)", info, re.M)[1]) if (name == "a0-minimal" and pages != 1) or (name == "a3-pages" and pages < 2): raise RuntimeError(f"unexpected page count in {name}: {pages}") bbox = subprocess.check_output(["pdftotext", "-bbox", str(pdf), "-"]) (directory / "main.bbox.html").write_bytes(bbox) bbox_error = None try: words = sum(1 for node in ET.fromstring(bbox).iter() if node.tag.endswith("}word")) except ET.ParseError as error: # Legacy reference math-font extraction can contain XML 1.0 # control codes. Keep those exact bytes and flag the issue. This # counts reference word tags only; it certifies no Unicode match. bbox_error = str(error) words = len(re.findall(rb"