153 lines
6.1 KiB
Python
153 lines
6.1 KiB
Python
#!/usr/bin/env python3
|
|
"""Stage a self-contained Windows native editor and its TeX resource trees."""
|
|
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
import lzma
|
|
from pathlib import Path
|
|
import shutil
|
|
import struct
|
|
import tarfile
|
|
import tempfile
|
|
|
|
|
|
MIRROR = "https://ctan.math.illinois.edu/systems/texlive/tlnet"
|
|
WEB_FILES = ("index.html", "styles.css", "favicon.svg", "app.js")
|
|
TOOLS = {
|
|
"bibtex.windows": ("bibtex.exe",),
|
|
"kpathsea.windows": ("kpsewhich.exe", "kpathsealibw64.dll", "msvcr100.dll"),
|
|
}
|
|
|
|
|
|
def digest(path, algorithm="sha256"):
|
|
with path.open("rb") as stream:
|
|
return hashlib.file_digest(stream, algorithm).hexdigest()
|
|
|
|
|
|
def require_amd64_pe(path):
|
|
with path.open("rb") as stream:
|
|
header = stream.read(64)
|
|
if len(header) == 64 and header[:2] == b"MZ":
|
|
stream.seek(struct.unpack_from("<I", header, 60)[0])
|
|
if stream.read(6) == b"PE\0\0\x64\x86":
|
|
return
|
|
raise ValueError(f"Expected an x64 Windows executable: {path}")
|
|
|
|
|
|
def stage_bibtex(output, downloads):
|
|
output.mkdir(parents=True)
|
|
with lzma.open(downloads / "texlive.tlpdb.xz", "rt") as stream:
|
|
db = stream.read()
|
|
receipts = {}
|
|
for package, names in TOOLS.items():
|
|
record = next(block for block in db.split("\n\n") if block.startswith(f"name {package}\n"))
|
|
fields = dict(line.split(" ", 1) for line in record.splitlines() if " " in line)
|
|
archive = downloads / f"{package}.tar.xz"
|
|
checksum = fields["containerchecksum"]
|
|
if digest(archive, "sha512") != checksum:
|
|
raise ValueError(f"TeX Live archive checksum differs for {package}")
|
|
with tarfile.open(archive, "r:xz") as bundle:
|
|
for name in names:
|
|
member = bundle.getmember(f"bin/windows/{name}")
|
|
if not member.isfile():
|
|
raise ValueError(f"Expected a regular TeX Live file: {name}")
|
|
with bundle.extractfile(member) as source, (output / name).open("wb") as target:
|
|
shutil.copyfileobj(source, target)
|
|
require_amd64_pe(output / name)
|
|
receipts[package] = {"revision": fields["revision"], "sha512": checksum}
|
|
# Match TeX Live's width so a wrapped bibliography comment stays a comment.
|
|
(output / "texmf.cnf").write_text(
|
|
"BIBINPUTS = .\nBSTINPUTS = .\nopenin_any = p\nopenout_any = p\nshell_escape = f\n"
|
|
"max_print_line = 79\n",
|
|
encoding="ascii",
|
|
)
|
|
return receipts
|
|
|
|
|
|
def copy_texmf(source, target, skip_generated):
|
|
target.mkdir(parents=True)
|
|
for path in sorted(source.rglob("*")):
|
|
if path.is_symlink() or not path.is_file():
|
|
continue
|
|
if skip_generated and path.suffix in {".fmt", ".log"}:
|
|
continue
|
|
staged = target / path.relative_to(source)
|
|
staged.parent.mkdir(parents=True, exist_ok=True)
|
|
shutil.copy2(path, staged)
|
|
|
|
|
|
def stage(args, output):
|
|
reference = json.loads((args.reference / "bundle.json").read_text())
|
|
desktop = json.loads((args.reference / "desktop-bundle.json").read_text())
|
|
tree_names = ("overlay", "dist", "var")
|
|
roots = reference["texmf_roots"]
|
|
if len(roots) != len(tree_names):
|
|
raise ValueError("Expected overlay, distribution and generated TeX trees")
|
|
texmf = output / "texmf"
|
|
for name, path in zip(tree_names, roots, strict=True):
|
|
copy_texmf(Path(path).resolve(strict=True), texmf / name, name == "var")
|
|
font_maps = Path(reference["environment"]["TEXFONTMAPS"].rstrip(":"))
|
|
(texmf / "fonts").mkdir()
|
|
shutil.copy2(font_maps / "pdftex.map", texmf / "fonts")
|
|
if not (texmf / "dist/tex/latex/tex-ini-files/pdflatex.ini").is_file():
|
|
raise ValueError("Missing pdfLaTeX initialization source")
|
|
|
|
web = output / "web"
|
|
web.mkdir()
|
|
for name in WEB_FILES:
|
|
source = args.reference / "web" / name
|
|
if digest(source) != desktop["sha256"][f"web/{name}"]:
|
|
raise ValueError(f"Reference Web asset has changed: {name}")
|
|
shutil.copyfile(source, web / name)
|
|
tools = stage_bibtex(output / "tools/bibtex", args.downloads)
|
|
(output / "bin").mkdir()
|
|
require_amd64_pe(args.editor)
|
|
shutil.copyfile(args.editor, output / "bin/native_editor.exe")
|
|
(output / "THIRD-PARTY.txt").write_text(
|
|
"TeX Live resources and bundled BibTeX and Kpathsea binaries\n"
|
|
"TeX Live licensing and sources: https://tug.org/texlive/copying.html\n"
|
|
"TeX Live source archives: https://tug.org/texlive/svn/\n"
|
|
f"TeX Live binaries and package metadata: {MIRROR}\n",
|
|
encoding="ascii",
|
|
)
|
|
license_source = Path(__file__).resolve().with_name("licenses")
|
|
shutil.copytree(license_source, output / "licenses")
|
|
|
|
files = {
|
|
path.relative_to(output).as_posix(): digest(path)
|
|
for path in sorted(output.rglob("*")) if path.is_file()
|
|
}
|
|
fingerprints = json.dumps(files, sort_keys=True).encode("utf-8")
|
|
(output / "windows-bundle.json").write_text(json.dumps({
|
|
"schema": 1,
|
|
"engine_source": args.commit,
|
|
"web_commit": desktop["web_commit"],
|
|
"resources_sha256": hashlib.sha256(fingerprints).hexdigest(),
|
|
"texlive_tools": tools,
|
|
"sha256": files,
|
|
}, indent=2, sort_keys=True) + "\n")
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("output", type=Path)
|
|
parser.add_argument("--editor", type=Path, required=True)
|
|
parser.add_argument("--reference", type=Path, required=True)
|
|
parser.add_argument("--downloads", type=Path, required=True)
|
|
parser.add_argument("--commit", required=True)
|
|
args = parser.parse_args()
|
|
args.output.parent.mkdir(parents=True, exist_ok=True)
|
|
if args.output.exists():
|
|
parser.error(f"Output already exists: {args.output}")
|
|
if len(args.commit) != 40 or any(char not in "0123456789abcdef" for char in args.commit):
|
|
parser.error("A full Git commit is required")
|
|
with tempfile.TemporaryDirectory(prefix=".windows-backend-", dir=args.output.parent) as temporary:
|
|
output = Path(temporary) / "backend"
|
|
stage(args, output)
|
|
output.rename(args.output)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|