File size: 3,901 Bytes
d165388
 
 
 
 
 
 
 
 
 
 
 
 
 
1214afa
d165388
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
#!/usr/bin/env python3

from __future__ import annotations

import argparse
import hashlib
import os
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path

ROOT = Path(__file__).resolve().parent
DEFAULT_OUTPUT = ROOT.parent / "docs" / "canvas-4b-design-model-proposal.pdf"
SOURCE_DATE_EPOCH = "1785542400"


def sha256(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as handle:
        while chunk := handle.read(1024 * 1024):
            digest.update(chunk)
    return digest.hexdigest()


def source_id() -> str:
    digest = hashlib.sha256()
    paths = [
        ROOT / "paper.md",
        ROOT / "main.tex",
        ROOT / "capyresearch.sty",
        ROOT / "prepare_content.py",
        ROOT / "references.bib",
        *sorted((ROOT / "assets").iterdir()),
    ]
    for path in paths:
        digest.update(path.relative_to(ROOT).as_posix().encode())
        digest.update(b"\0")
        digest.update(path.read_bytes())
        digest.update(b"\0")
    return digest.hexdigest()[:32].upper()


def require_commands() -> None:
    missing = [
        command
        for command in ("pandoc", "latexmk", "lualatex")
        if shutil.which(command) is None
    ]
    if missing:
        raise SystemExit("missing paper build commands: " + ", ".join(missing))


def render(output: Path) -> Path:
    require_commands()
    with tempfile.TemporaryDirectory(prefix="capy-canvas-paper-") as directory:
        build = Path(directory)
        for name in (
            "paper.md",
            "main.tex",
            "capyresearch.sty",
            "prepare_content.py",
            "references.bib",
        ):
            shutil.copy2(ROOT / name, build / name)
        shutil.copytree(ROOT / "assets", build / "assets")
        main = build / "main.tex"
        main.write_text(
            main.read_text().replace("CAPY_PDF_TRAILER_ID", source_id())
        )
        environment = {
            **os.environ,
            "SOURCE_DATE_EPOCH": SOURCE_DATE_EPOCH,
            "FORCE_SOURCE_DATE": "1",
            "TZ": "UTC",
        }
        subprocess.run(
            [sys.executable, "prepare_content.py"],
            cwd=build,
            env=environment,
            check=True,
        )
        subprocess.run(
            [
                "latexmk",
                "-lualatex",
                "-interaction=nonstopmode",
                "-halt-on-error",
                "main.tex",
            ],
            cwd=build,
            env=environment,
            check=True,
        )
        output.parent.mkdir(parents=True, exist_ok=True)
        temporary = output.with_name(f".{output.name}.tmp")
        shutil.copy2(build / "main.pdf", temporary)
        os.replace(temporary, output)
    return output


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--output", type=Path, default=DEFAULT_OUTPUT)
    parser.add_argument(
        "--check",
        action="store_true",
        help="Render to a temporary file and require an exact canonical-PDF match.",
    )
    args = parser.parse_args()
    if args.check:
        with tempfile.TemporaryDirectory(prefix="capy-canvas-paper-check-") as directory:
            rendered = render(Path(directory) / DEFAULT_OUTPUT.name)
            if not DEFAULT_OUTPUT.exists():
                raise SystemExit(f"canonical PDF is missing: {DEFAULT_OUTPUT}")
            if rendered.read_bytes() != DEFAULT_OUTPUT.read_bytes():
                raise SystemExit(
                    "canonical PDF is stale: "
                    f"expected {sha256(rendered)}, found {sha256(DEFAULT_OUTPUT)}"
                )
            print(f"paper is reproducible: {sha256(rendered)}")
        return
    rendered = render(args.output.expanduser().resolve())
    print(f"rendered {rendered} ({sha256(rendered)})")


if __name__ == "__main__":
    main()