224 lines
13 KiB
Python
224 lines
13 KiB
Python
"""Build and assemble the formal Windows portable release from this checkout."""
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import ast
|
|
import hashlib
|
|
from importlib import metadata
|
|
import json
|
|
from pathlib import Path, PurePosixPath
|
|
import re
|
|
import shutil
|
|
import struct
|
|
import subprocess
|
|
import sys
|
|
import tomllib
|
|
import zipfile
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
|
|
|
|
def project_version() -> str:
|
|
version = tomllib.loads((ROOT / "pyproject.toml").read_text(encoding="utf8"))["project"]["version"]
|
|
if not re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+", version):
|
|
raise ValueError("Formal releases require a stable major.minor.patch version")
|
|
return version
|
|
|
|
|
|
def sha256(path: Path) -> str:
|
|
with path.open("rb") as stream:
|
|
return hashlib.file_digest(stream, "sha256").hexdigest()
|
|
|
|
|
|
def validate_bundle(bundle: Path, *, runtime_files=None, license_files=None) -> None:
|
|
if not (bundle / "MentorPDFExporter.exe").is_file():
|
|
raise ValueError("Missing application executable")
|
|
if not (bundle / "_internal/mentor_pdf_export/assets/app.ico").is_file():
|
|
raise ValueError("Missing packaged window icon")
|
|
forbidden = {".prj", ".lmc", ".pdf", ".ttf", ".ttc", ".otf", ".woff", ".woff2", ".doc", ".docx", ".lic", ".dat", ".log"}
|
|
top_level = {"MentorPDFExporter.exe", "README.md", "CHANGELOG.md", "使用说明.txt", "发布说明.txt", "ThirdPartyNotices.txt", "SHA256SUMS.txt", "manifest.json"}
|
|
forbidden_dirs = {".git", "database", "projectbackup", "pcb", "sch", "runs", "logs", "output", "artifacts", "pdf参考"}
|
|
runtime_suffixes = {".dll", ".pyd", ".qm", ".zip", ".ico", ".svg", ".png", ".txt", ".md", ".apache", ".bsd", ""}
|
|
for file in bundle.rglob("*"):
|
|
relative = file.relative_to(bundle)
|
|
parts = relative.parts
|
|
if file.is_symlink() or file.is_junction():
|
|
raise ValueError(f"Linked bundle entry: {file.name}")
|
|
if any(part.casefold() in forbidden_dirs for part in parts):
|
|
raise ValueError(f"Private source/runtime directory: {relative}")
|
|
if len(parts) == 1 and parts[0] not in top_level | {"_internal", "licenses"}:
|
|
raise ValueError(f"Unapproved top-level bundle entry: {relative}")
|
|
if not file.is_file():
|
|
continue
|
|
if file.suffix.lower() in forbidden or file.name.lower() == "sch2pdf.exe":
|
|
raise ValueError(f"Private engineering data, font or Mentor binary: {file.name}")
|
|
if file.name.lower() in {"icuuc.dll", "icuin.dll"}:
|
|
raise ValueError(f"Foreign ICU library: {file.name}")
|
|
key = relative.as_posix()
|
|
if parts[0] == "_internal":
|
|
if file.suffix.lower() not in runtime_suffixes:
|
|
raise ValueError(f"Unapproved runtime file type: {relative}")
|
|
if runtime_files is not None and (key not in runtime_files or sha256(file) != runtime_files[key]):
|
|
raise ValueError(f"Runtime file differs from the build allowlist: {relative}")
|
|
if parts[0] == "licenses" and license_files is not None:
|
|
if key not in license_files or sha256(file) != license_files[key]:
|
|
raise ValueError(f"License file has no approved distribution source: {relative}")
|
|
if key == "MentorPDFExporter.exe" and runtime_files is not None:
|
|
if key not in runtime_files or sha256(file) != runtime_files[key]:
|
|
raise ValueError("Application executable differs from the build allowlist")
|
|
if runtime_files is not None:
|
|
for relative, expected in runtime_files.items():
|
|
file = (bundle / relative).resolve()
|
|
if not file.is_relative_to(bundle.resolve()) or not file.is_file() or sha256(file) != expected:
|
|
raise ValueError("A required build runtime file is missing or modified")
|
|
|
|
|
|
def validate_archive(archive: Path, bundle: Path) -> None:
|
|
"""Independently compare every ZIP member with the verified directory."""
|
|
expected = {bundle.name + "/" + p.relative_to(bundle).as_posix(): p for p in bundle.rglob("*") if p.is_file()}
|
|
with zipfile.ZipFile(archive) as zipped:
|
|
entries = zipped.infolist()
|
|
names = [entry.filename for entry in entries]
|
|
if len(set(names)) != len(names):
|
|
raise ValueError("Duplicate release ZIP member")
|
|
for entry in entries:
|
|
name = entry.filename
|
|
path = PurePosixPath(name)
|
|
if entry.is_dir() or name != path.as_posix() or "\\" in name or ":" in name or path.is_absolute() or ".." in path.parts:
|
|
raise ValueError("Unsafe release ZIP member path")
|
|
if set(names) != set(expected):
|
|
raise ValueError("Release ZIP members do not match the verified file set")
|
|
for name, source in expected.items():
|
|
with zipped.open(name) as stream:
|
|
digest = hashlib.file_digest(stream, "sha256").hexdigest()
|
|
if digest != sha256(source):
|
|
raise ValueError(f"Release ZIP member differs from the verified file: {name}")
|
|
|
|
|
|
def record_runtime_allowlist(bundle: Path, version: str) -> None:
|
|
"""Use PyInstaller's collected file list, never a wildcard of the bundle."""
|
|
work = ROOT / "build" / f"pyinstaller-{version}"
|
|
toc = ast.literal_eval((work / "MentorPDFExporter/COLLECT-00.toc").read_text(encoding="utf8"))
|
|
files = {}
|
|
for destination, source, kind in toc[0]:
|
|
relative = Path(destination) if kind == "EXECUTABLE" else Path("_internal") / destination
|
|
file = (bundle / relative).resolve()
|
|
if not file.is_relative_to(bundle.resolve()) or not file.is_file():
|
|
raise ValueError("Collected runtime file missing from bundle")
|
|
files[relative.as_posix()] = sha256(file)
|
|
(work / "runtime-files.json").write_text(json.dumps({"version": version, "files": files}, indent=2), encoding="utf8")
|
|
|
|
|
|
def collect_licenses(bundle: Path) -> tuple[dict[str, str], dict[str, str]]:
|
|
licenses = bundle / "licenses"
|
|
licenses.mkdir(exist_ok=True)
|
|
python_license = Path(sys.base_prefix) / "LICENSE.txt"
|
|
if not python_license.is_file():
|
|
raise FileNotFoundError("Python runtime license not found")
|
|
shutil.copyfile(python_license, licenses / "Python-LICENSE.txt")
|
|
versions = {}
|
|
approved = {"licenses/Python-LICENSE.txt": sha256(licenses / "Python-LICENSE.txt")}
|
|
names = ("pyside6", "pyside6_addons", "pyside6_essentials", "shiboken6", "pypdf", "pywin32", "cryptography", "cffi", "fonttools")
|
|
for name in names:
|
|
distribution = metadata.distribution(name)
|
|
versions[name] = distribution.version
|
|
copied = 0
|
|
for relative in distribution.files or ():
|
|
parts = relative.parts
|
|
if len(parts) < 3 or not parts[0].endswith(".dist-info") or parts[1] != "licenses":
|
|
continue
|
|
source = Path(distribution.locate_file(relative))
|
|
if source.is_file():
|
|
destination = licenses / Path(*parts)
|
|
destination.parent.mkdir(parents=True, exist_ok=True)
|
|
shutil.copyfile(source, destination)
|
|
approved[destination.relative_to(bundle).as_posix()] = sha256(source)
|
|
copied += 1
|
|
if not copied:
|
|
raise FileNotFoundError(f"No distributed license texts found for {name}")
|
|
metrics = Path(metadata.distribution("pypdf").locate_file("pypdf/_codecs/core_font_metrics.py"))
|
|
destination = licenses / "pypdf/Adobe-Core14-metrics-and-notices.py"
|
|
destination.parent.mkdir(exist_ok=True)
|
|
shutil.copyfile(metrics, destination)
|
|
shutil.copyfile(ROOT / "packaging/ICON-NOTICE.md", licenses / "Application-Icon.txt")
|
|
approved[destination.relative_to(bundle).as_posix()] = sha256(metrics)
|
|
approved["licenses/Application-Icon.txt"] = sha256(ROOT / "packaging/ICON-NOTICE.md")
|
|
return versions, approved
|
|
|
|
|
|
def assemble_release(bundle: Path, version: str) -> Path:
|
|
trusted = json.loads((ROOT / "build" / f"pyinstaller-{version}" / "runtime-files.json").read_text(encoding="utf8"))
|
|
if trusted["version"] != version:
|
|
raise ValueError("Runtime allowlist version mismatch")
|
|
runtime_files = trusted["files"]
|
|
validate_bundle(bundle, runtime_files=runtime_files)
|
|
versions, license_files = collect_licenses(bundle)
|
|
shutil.copyfile(ROOT / "README.md", bundle / "README.md")
|
|
shutil.copyfile(ROOT / "CHANGELOG.md", bundle / "CHANGELOG.md")
|
|
shutil.copyfile(ROOT / "docs/releases" / f"{version}.md", bundle / "发布说明.txt")
|
|
(bundle / "使用说明.txt").write_text(
|
|
f"Mentor PDF 批量导出 v{version} 正式版\n\n"
|
|
"双击 MentorPDFExporter.exe;请保留整个文件夹及 _internal。\n"
|
|
"本机需要 Mentor、有效许可证以及可访问的原工程依赖库。\n"
|
|
"选择工程目录 → 扫描工程 → 选择输出目录 → 勾选工程 → 开始批量导出。\n"
|
|
"PDF 使用原工程名,同名版本通过自然子目录区分。\n"
|
|
"默认参考配色、Arial 中文回退与 GBK 修复;普通 WinAnsi 工程请关闭 GBK 修复。\n"
|
|
"直接导出,不创建工程副本,不备份旧 PDF。原生引擎可能更新数据库或升级旧工程。\n"
|
|
"更多说明与边界见 README.md 和发布说明.txt。\n",
|
|
encoding="utf-8-sig",
|
|
)
|
|
(bundle / "ThirdPartyNotices.txt").write_text(
|
|
"This bundle includes Python, PySide6/Qt, shiboken6, pypdf, pywin32, cryptography, CFFI and FontTools. "
|
|
"Their license texts as distributed by the installed packages are retained in licenses/. "
|
|
"These notices do not replace the original terms.\n\n"
|
|
"Adobe Core14 AFM-derived metrics and all embedded permission/copyright notices from pypdf "
|
|
"are retained in licenses/pypdf/Adobe-Core14-metrics-and-notices.py.\n\n"
|
|
"The application icon is original project artwork, not a Mentor/Siemens/Adobe logo.\n\n"
|
|
"Mentor binaries/licenses, CAD projects, central libraries, PDFs and Windows font files are not shipped. "
|
|
"Fonts are read from the user system; restricted embedding/subsetting is rejected.\n",
|
|
encoding="utf8",
|
|
)
|
|
validate_bundle(bundle, runtime_files=runtime_files, license_files=license_files)
|
|
files = sorted((p for p in bundle.rglob("*") if p.is_file()), key=lambda p: p.relative_to(bundle).as_posix())
|
|
manifest = {
|
|
"product": "MentorPDFExporter", "version": version, "channel": "stable",
|
|
"platform": "windows-x64", "python": sys.version.split()[0],
|
|
"runtime_components": versions, "runtime_files": runtime_files, "license_files": license_files, "exe_sha256": sha256(bundle / "MentorPDFExporter.exe"),
|
|
"icon_sha256": sha256(bundle / "_internal/mentor_pdf_export/assets/app.ico"),
|
|
}
|
|
(bundle / "manifest.json").write_text(json.dumps(manifest, indent=2), encoding="utf8")
|
|
files = [p for p in files if p.name != "SHA256SUMS.txt" and p.name != "manifest.json"] + [bundle / "manifest.json"]
|
|
(bundle / "SHA256SUMS.txt").write_text("".join(f"{sha256(p)} {p.relative_to(bundle).as_posix()}\n" for p in files), encoding="utf8")
|
|
archive = bundle.parent / f"MentorPDFExporter-{version}-win64.zip"
|
|
with zipfile.ZipFile(archive, "w", zipfile.ZIP_DEFLATED, compresslevel=6) as output:
|
|
for file in sorted(p for p in bundle.rglob("*") if p.is_file()):
|
|
output.write(file, file.relative_to(bundle.parent).as_posix())
|
|
validate_archive(archive, bundle)
|
|
archive.with_suffix(".zip.sha256").write_text(f"{sha256(archive)} {archive.name}\n", encoding="ascii")
|
|
print(json.dumps({"archive": str(archive), "bytes": archive.stat().st_size, "sha256": sha256(archive), **manifest}, indent=2))
|
|
return archive
|
|
|
|
|
|
def main(argv=None) -> int:
|
|
parser = argparse.ArgumentParser(description="Build the formal Windows portable release")
|
|
parser.add_argument("--skip-build", action="store_true", help="Reassemble an already built, verified bundle")
|
|
args = parser.parse_args(argv)
|
|
if sys.platform != "win32" or struct.calcsize("P") != 8:
|
|
parser.error("Build on Windows using 64-bit Python")
|
|
version = project_version()
|
|
bundle = ROOT / "release" / f"MentorPDFExporter-{version}"
|
|
if not args.skip_build:
|
|
subprocess.run([sys.executable, str(ROOT / "packaging/generate_icon.py")], cwd=ROOT, check=True)
|
|
subprocess.run([
|
|
sys.executable, "-m", "PyInstaller", "--noconfirm", "--clean",
|
|
"--distpath", str(ROOT / "release"), "--workpath", str(ROOT / "build" / f"pyinstaller-{version}"),
|
|
str(ROOT / "packaging/MentorPDFExporter.spec"),
|
|
], cwd=ROOT, check=True)
|
|
record_runtime_allowlist(bundle, version)
|
|
assemble_release(bundle, version)
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|