#!/usr/bin/env python3 """Compile the main article in a temporary directory and copy the PDF out.""" from pathlib import Path import argparse import shutil import subprocess import sys import tempfile ROOT = Path(__file__).resolve().parent PACKAGE = ROOT.parent def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--output-dir', type=Path, default=PACKAGE, help='Directory for main.pdf; defaults to the package root.') args = parser.parse_args() tex = shutil.which('pdflatex') bib = next((shutil.which(name) for name in ('bibtex', 'bibtex.original', 'bibtex8') if shutil.which(name)), None) if tex is None or bib is None: raise RuntimeError('pdfLaTeX and BibTeX are required.') with tempfile.TemporaryDirectory(prefix='dis-dae-build-') as directory: work = Path(directory) for name in ('main.tex', 'references.bib'): shutil.copyfile(PACKAGE / name, work / name) for name in ('figures', 'tables'): shutil.copytree(PACKAGE / name, work / name) latex = [tex, '-interaction=nonstopmode', '-halt-on-error', 'main.tex'] for command in (latex, [bib, 'main'], latex, latex): result = subprocess.run(command, cwd=work, text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) print(result.stdout, end='', flush=True) if result.returncode: raise RuntimeError('Compilation failed: ' + ' '.join(command)) log = (work / 'main.log').read_text(errors='replace') problems = [message for message in ( 'There were undefined references', 'undefined on input line', 'Missing character:', 'Overfull \\hbox', 'Overfull \\vbox' ) if message in log] if problems: raise RuntimeError('Typesetting warnings: ' + ', '.join(problems)) args.output_dir.mkdir(parents=True, exist_ok=True) target = args.output_dir / 'main.pdf' shutil.copyfile(work / 'main.pdf', target) print('Built', target.resolve()) if __name__ == '__main__': try: main() except (OSError, RuntimeError) as exc: print(exc, file=sys.stderr) sys.exit(1)