274 lines
11 KiB
Python
274 lines
11 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
|
|
import os
|
|
from pathlib import Path, PurePosixPath
|
|
import re
|
|
import shutil
|
|
import stat
|
|
import struct
|
|
import subprocess
|
|
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"),
|
|
}
|
|
FORMAT_MODES = ("pdflatex", "xelatex")
|
|
UNICODE_PACKAGES = ("ctex", "xecjk", "zhnumber", "fandol", "xetex")
|
|
UNICODE_NOTICES = {
|
|
"ctex": {"doc/latex/ctex/README.md": "ctex-README.md"},
|
|
"xecjk": {"doc/xelatex/xecjk/README.md": "xeCJK-README.md"},
|
|
"zhnumber": {"doc/latex/zhnumber/README.md": "zhnumber-README.md"},
|
|
"fandol": {
|
|
"doc/latex/fandol/COPYING": "Fandol-COPYING",
|
|
"doc/latex/fandol/README": "Fandol-README",
|
|
},
|
|
}
|
|
|
|
|
|
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 read_texlive_database(downloads):
|
|
with lzma.open(downloads / "texlive.tlpdb.xz", "rt") as stream:
|
|
records = stream.read().split("\n\n")
|
|
packages = {}
|
|
for record in records:
|
|
if not record.startswith("name "):
|
|
continue
|
|
fields = dict(
|
|
line.split(" ", 1)
|
|
for line in record.splitlines()
|
|
if line and not line[0].isspace() and " " in line
|
|
)
|
|
packages[fields["name"]] = fields
|
|
return packages
|
|
|
|
|
|
def checked_texlive_archive(downloads, database, name):
|
|
package = name.removesuffix(".doc")
|
|
record = database[package]
|
|
field = "doccontainerchecksum" if name.endswith(".doc") else "containerchecksum"
|
|
checksum = record[field]
|
|
archive = downloads / f"{name}.tar.xz"
|
|
if digest(archive, "sha512") != checksum:
|
|
raise ValueError(f"TeX Live archive checksum differs for {name}")
|
|
return archive, {"revision": record["revision"], "sha512": checksum}
|
|
|
|
|
|
def copy_archive_file(archive, member, target):
|
|
if not member.isfile():
|
|
raise ValueError(f"Expected a regular TeX Live file: {member.name}")
|
|
target.parent.mkdir(parents=True, exist_ok=True)
|
|
with archive.extractfile(member) as source, target.open("xb") as output:
|
|
shutil.copyfileobj(source, output)
|
|
|
|
|
|
def stage_bibtex(output, downloads, database):
|
|
output.mkdir(parents=True)
|
|
receipts = {}
|
|
for package, names in TOOLS.items():
|
|
archive, receipts[package] = checked_texlive_archive(downloads, database, package)
|
|
with tarfile.open(archive, "r:xz") as bundle:
|
|
for name in names:
|
|
target = output / name
|
|
copy_archive_file(bundle, bundle.getmember(f"bin/windows/{name}"), target)
|
|
require_amd64_pe(target)
|
|
# 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 stage_unicode_resources(texmf, licenses, downloads, database):
|
|
receipts = {}
|
|
for package in UNICODE_PACKAGES:
|
|
archive, receipts[package] = checked_texlive_archive(downloads, database, package)
|
|
with tarfile.open(archive, "r:xz") as bundle:
|
|
for member in bundle:
|
|
if not member.isfile():
|
|
continue
|
|
# TeX Live archives use either TDS paths or a texmf-dist prefix.
|
|
relative = PurePosixPath(member.name.removeprefix("texmf-dist/"))
|
|
if not relative.parts or relative.parts[0] not in ("tex", "fonts"):
|
|
continue
|
|
if ".." in relative.parts or any("\\" in part or ":" in part for part in relative.parts):
|
|
raise ValueError(f"Invalid TeX Live resource path: {member.name}")
|
|
copy_archive_file(bundle, member, texmf.joinpath(*relative.parts))
|
|
|
|
# CTeX loads this documented configuration before processing user options.
|
|
ctex_options = texmf / "tex/latex/ctex/config/ctexopts.cfg"
|
|
with ctex_options.open("a", encoding="utf-8", newline="\n") as options:
|
|
options.write(
|
|
"\n% Texrra bundles Fandol independently of the system's installed fonts.\n"
|
|
r"\sys_if_engine_xetex:T { \ctex_set:nn { option } { fontset = fandol } }"
|
|
"\n"
|
|
)
|
|
|
|
for package, notices in UNICODE_NOTICES.items():
|
|
name = f"{package}.doc"
|
|
archive, receipts[name] = checked_texlive_archive(downloads, database, name)
|
|
with tarfile.open(archive, "r:xz") as bundle:
|
|
for member, filename in notices.items():
|
|
copy_archive_file(bundle, bundle.getmember(member), licenses / filename)
|
|
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 prepare_formats(output):
|
|
output = output.resolve(strict=True)
|
|
editor = output / "bin/native_editor.exe"
|
|
if os.name == "nt":
|
|
backend = str(output)
|
|
else:
|
|
backend = subprocess.check_output(["wslpath", "-w", str(output)], text=True).strip()
|
|
editor.chmod(editor.stat().st_mode | stat.S_IXUSR)
|
|
subprocess.run(
|
|
[str(editor), "--prepare-windows-formats", backend],
|
|
stdin=subprocess.DEVNULL,
|
|
check=True,
|
|
)
|
|
finish_formats(output)
|
|
|
|
|
|
def finish_formats(output):
|
|
formats = output / "formats"
|
|
for name in FORMAT_MODES:
|
|
directory = formats / name
|
|
for filename in ("latex.tfx", "texsys.aux"):
|
|
path = directory / filename
|
|
if not path.is_file() or not path.stat().st_size:
|
|
raise ValueError(f"Missing generated {name} format input: {filename}")
|
|
(directory / "latex.log").unlink(missing_ok=True)
|
|
# INITEX records its generated files in a private ledger. Only the image
|
|
# and its captured scratch input travel with the release.
|
|
for path in formats.iterdir():
|
|
if path.name in FORMAT_MODES:
|
|
continue
|
|
if not path.is_file() or not re.fullmatch(r"[a-f0-9]{64}\.(json|lock)", path.name):
|
|
raise ValueError(f"Unexpected item in generated formats: {path.name}")
|
|
path.unlink()
|
|
|
|
|
|
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")
|
|
for mode in FORMAT_MODES:
|
|
entry = f"{mode}.ini"
|
|
if not (texmf / "dist/tex/latex/tex-ini-files" / entry).is_file():
|
|
raise ValueError(f"Missing LaTeX initialization source: {entry}")
|
|
|
|
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)
|
|
database = read_texlive_database(args.downloads)
|
|
tools = stage_bibtex(output / "tools/bibtex", args.downloads, database)
|
|
(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"
|
|
"CTeX, xeCJK, zhnumber and Fandol notices: licenses/texlive/\n"
|
|
f"TeX Live binaries and package metadata: {MIRROR}\n",
|
|
encoding="ascii",
|
|
)
|
|
license_source = Path(__file__).resolve().with_name("licenses")
|
|
licenses = output / "licenses"
|
|
shutil.copytree(license_source, licenses)
|
|
unicode_resources = stage_unicode_resources(
|
|
texmf / "overlay", licenses / "texlive", args.downloads, database
|
|
)
|
|
|
|
prepare_formats(output)
|
|
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,
|
|
"texlive_unicode": unicode_resources,
|
|
"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,
|
|
help="TeX Live package archives and texlive.tlpdb.xz from the same mirror snapshot",
|
|
)
|
|
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()
|