"""Build an offline, relocatable folder with official embedded Python and pywin32.""" from pathlib import Path import argparse import hashlib import json import os import shutil import subprocess import sys import urllib.request import zipfile ROOT = Path(__file__).resolve().parent.parent sys.path.insert(0, str(ROOT)) from mentorexport.core import sha256, write_json PYTHON_VERSION = "3.12.10" PYWIN32_VERSION = "312" def download(url, target, expected=None): target.parent.mkdir(parents=True, exist_ok=True) if not target.exists() or (expected and sha256(target) != expected): temporary = target.with_suffix(target.suffix + ".download") with urllib.request.urlopen(url, timeout=60) as source, temporary.open("wb") as stream: shutil.copyfileobj(source, stream) os.replace(temporary, target) if expected and sha256(target) != expected: raise ValueError("Downloaded package checksum mismatch: " + str(target)) return target def extract(archive, destination): destination.mkdir(parents=True, exist_ok=True) with zipfile.ZipFile(archive) as package: if package.testzip() is not None: raise ValueError("Damaged archive: " + str(archive)) for entry in package.infolist(): if not (destination / entry.filename).resolve().is_relative_to(destination.resolve()): raise ValueError("Archive member escapes target") package.extractall(destination) def prepare_runtime(): cache = ROOT / "build/downloads" python_zip = download( f"https://www.python.org/ftp/python/{PYTHON_VERSION}/python-{PYTHON_VERSION}-embed-amd64.zip", cache / f"python-{PYTHON_VERSION}-embed-amd64.zip") with urllib.request.urlopen(f"https://pypi.org/pypi/pywin32/{PYWIN32_VERSION}/json", timeout=30) as response: metadata = json.load(response) wheel_name = f"pywin32-{PYWIN32_VERSION}-cp312-cp312-win_amd64.whl" wheel_info = next(row for row in metadata["urls"] if row["filename"] == wheel_name) wheel = download(wheel_info["url"], cache / wheel_name, wheel_info["digests"]["sha256"]) runtime = ROOT / "build/runtime" if not (runtime / "python.exe").is_file(): extract(python_zip, runtime) else: with zipfile.ZipFile(python_zip) as package: expected_python = hashlib.sha256(package.read("python.exe")).hexdigest() if sha256(runtime / "python.exe") != expected_python: raise ValueError("Runtime build cache is damaged; preserve it and use a fresh build directory") if not (runtime / f"Lib/site-packages/pywin32-{PYWIN32_VERSION}.dist-info/METADATA").is_file(): extract(wheel, runtime / "Lib/site-packages") pth = "python312.zip\n.\nLib/site-packages\nLib/site-packages/win32\nLib/site-packages/win32/lib\nimport site\n" pth_file = runtime / "python312._pth" if not pth_file.is_file() or pth_file.read_text(encoding="utf-8") != pth: pth_file.write_text(pth, encoding="utf-8") return runtime, { "python": {"version": PYTHON_VERSION, "architecture": "amd64", "archive_sha256": sha256(python_zip), "source": f"https://www.python.org/ftp/python/{PYTHON_VERSION}/"}, "pywin32": {"version": PYWIN32_VERSION, "wheel_sha256": sha256(wheel), "filename": wheel.name}, "user_installation_required": False, } def build(destination): destination = Path(destination).resolve() if destination.exists(): raise ValueError("Choose a new output folder; existing package is preserved: " + str(destination)) runtime, dependencies = prepare_runtime() if not (ROOT / "helpers/native_read.exe").is_file(): raise ValueError("Build the x86 library helper before packaging") destination.mkdir(parents=True) shutil.copytree(runtime, destination / "runtime", ignore=shutil.ignore_patterns("__pycache__", "*.pyc")) shutil.copytree(ROOT / "mentorexport", destination / "mentorexport", ignore=shutil.ignore_patterns("__pycache__", "*.pyc")) shutil.copytree(ROOT / "helpers", destination / "helpers", ignore=shutil.ignore_patterns("*.obj", "*.pdb", "__pycache__")) for name in ("export.py", "导出.cmd", "README.md"): shutil.copy2(ROOT / name, destination / name) # CMD's UTF-8 parser can truncate LF-only lines after chcp; ship native CRLF. launcher = destination / "导出.cmd" launcher.write_bytes(launcher.read_bytes().replace(b"\r\n", b"\n").replace(b"\n", b"\r\n")) (destination / "licenses").mkdir() (destination / "licenses/THIRD_PARTY.md").write_text( "# Runtime notices\n\nPython " + PYTHON_VERSION + ": see runtime/LICENSE.txt (PSF and included component notices).\n\n" "pywin32 " + PYWIN32_VERSION + ": see runtime/Lib/site-packages/pywin32-" + PYWIN32_VERSION + ".dist-info/ for upstream license and metadata.\n\n" "Mentor/Siemens vendor programs are not included. They are located on the target machine.\n", encoding="utf-8") write_json(destination / "runtime-dependencies.json", dependencies) files = {p.relative_to(destination).as_posix(): {"sha256": sha256(p), "bytes": p.stat().st_size} for p in sorted(destination.rglob("*")) if p.is_file()} write_json(destination / "package-manifest.json", {"schema": 1, "files": files}) archive = destination.parent / (destination.name + ".zip") with zipfile.ZipFile(archive, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=6) as package: for path in sorted(destination.rglob("*")): if path.is_file(): package.write(path, arcname=(Path("MentorExport") / path.relative_to(destination)).as_posix()) with zipfile.ZipFile(archive) as package: assert package.testzip() is None print(json.dumps({"folder": str(destination), "zip": str(archive), "bytes": archive.stat().st_size, "files": len(files)}, ensure_ascii=False, indent=2)) if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--output", type=Path) parser.add_argument("--runtime-only", action="store_true") args = parser.parse_args() if args.runtime_only: print(json.dumps(prepare_runtime()[1], ensure_ascii=False, indent=2)) elif args.output: build(args.output) else: parser.error("Specify --output or --runtime-only")