release: ship validated Mentor PDF exporter v1.0.0

This commit is contained in:
阿白叔 committed 2026-10-10 16:28:18 +08:00
1 parent d4928af5b6
commit 0334f2b85b
50 files changed
+3998 -219

No files matched your search

+7
View File
@@ -0,0 +1,7 @@
# Application icon
The blue document / red PDF / export arrow artwork is original to this project.
No Mentor, Siemens, Adobe, or third-party application logo is used.
The editable SVG and multi-resolution ICO are stored in the application assets package.
Regenerate with `python packaging/generate_icon.py` using the release PySide6 environment.
Copyright © 2026 simgreek.
+22 -3
View File
@@ -1,14 +1,33 @@
# Portable onedir bundle: no Mentor binaries, licenses or private projects.
from pathlib import Path
import sys
import tomllib
from PyInstaller.utils.win32.versioninfo import VSVersionInfo, FixedFileInfo, StringFileInfo, StringTable, StringStruct, VarFileInfo, VarStruct
sys.path.insert(0, SPECPATH)
from bundle_policy import filter_binaries
root = Path(SPECPATH).parent
version = tomllib.loads((root / "pyproject.toml").read_text(encoding="utf-8"))["project"]["version"]
assets = root / "src/mentor_pdf_export/assets"
version_tuple = tuple(int(part) for part in version.split(".")) + (0,)
version_info = VSVersionInfo(
ffi=FixedFileInfo(filevers=version_tuple, prodvers=version_tuple, mask=0x3f,
flags=0, OS=0x40004, fileType=1, subtype=0, date=(0, 0)),
kids=[StringFileInfo([StringTable("040904B0", [
StringStruct("CompanyName", "simgreek"),
StringStruct("FileDescription", "Mentor PDF Batch Exporter"),
StringStruct("FileVersion", version),
StringStruct("InternalName", "MentorPDFExporter"),
StringStruct("OriginalFilename", "MentorPDFExporter.exe"),
StringStruct("ProductName", "Mentor PDF Batch Exporter"),
StringStruct("ProductVersion", version),
StringStruct("LegalCopyright", "Copyright (c) 2026 simgreek"),
])]), VarFileInfo([VarStruct("Translation", [1033, 1200])])],
)
analysis = Analysis(
[str(root / "packaging" / "entrypoint.py")],
pathex=[str(root / "src")],
binaries=[],
datas=[],
datas=[(str(assets), "mentor_pdf_export/assets")],
hiddenimports=["win32job", "win32api", "win32con"],
hookspath=[],
hooksconfig={},
@@ -20,7 +39,7 @@ analysis = Analysis(
analysis.binaries = filter_binaries(analysis.binaries)
pyz = PYZ(analysis.pure)
exe = EXE(pyz, analysis.scripts, [], exclude_binaries=True,
name="MentorPDFExporter", debug=False, bootloader_ignore_signals=False,
name="MentorPDFExporter", icon=str(assets / "app.ico"), version=version_info, debug=False, bootloader_ignore_signals=False,
strip=False, upx=False, console=False, disable_windowed_traceback=False)
coll = COLLECT(exe, analysis.binaries, analysis.datas, strip=False, upx=False,
name="MentorPDFExporter")
name=f"MentorPDFExporter-{version}")
+223
View File
@@ -0,0 +1,223 @@
"""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())
+46
View File
@@ -0,0 +1,46 @@
"""Render the project's original SVG into a multi-resolution Windows ICO."""
from pathlib import Path
import struct
from PySide6.QtCore import QByteArray, QBuffer, QIODevice, QRectF
from PySide6.QtGui import QGuiApplication, QImage, QPainter
from PySide6.QtSvg import QSvgRenderer
ROOT = Path(__file__).resolve().parents[1]
def main():
app = QGuiApplication.instance() or QGuiApplication([])
assets = ROOT / "src/mentor_pdf_export/assets"
renderer = QSvgRenderer(str(assets / "app.svg"))
if not renderer.isValid():
raise ValueError("Invalid application icon SVG")
sizes = (16, 24, 32, 48, 64, 128, 256)
entries = []
payloads = []
offset = 6 + 16 * len(sizes)
for size in sizes:
image = QImage(size, size, QImage.Format.Format_ARGB32)
image.fill(0)
painter = QPainter(image)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
renderer.render(painter, QRectF(0, 0, size, size))
painter.end()
data = QByteArray()
buffer = QBuffer(data)
buffer.open(QIODevice.OpenModeFlag.WriteOnly)
if not image.save(buffer, "PNG"):
raise RuntimeError("Cannot encode application icon")
buffer.close()
png = bytes(data)
entries.append(struct.pack("<BBBBHHII", size % 256, size % 256, 0, 0, 1, 32, len(png), offset))
payloads.append(png)
offset += len(png)
if size == 256:
image.save(str(assets / "app.png"))
(assets / "app.ico").write_bytes(struct.pack("<HHH", 0, 1, len(sizes)) + b"".join(entries) + b"".join(payloads))
print("Generated original application icon: 16/24/32/48/64/128/256 px")
if __name__ == "__main__":
main()
+214
View File
@@ -0,0 +1,214 @@
"""Publish a verified stable release to the user's simgreek Gitea organization.
Credentials are read from Git Credential Manager into memory only. No secret is
accepted on the command line, written to a report, or embedded in remote URLs.
"""
from __future__ import annotations
import argparse
import base64
import hashlib
import json
import os
from pathlib import Path
import re
import subprocess
import sys
import time
import tomllib
import urllib.error
import urllib.parse
import urllib.request
import uuid
import xml.etree.ElementTree as ET
ROOT = Path(__file__).resolve().parents[1]
SERVER = "https://git.simgreek.com"
HOST = "git.simgreek.com"
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
# Never forward authentication to an attachment redirect or another host.
return None
def validate_name(value: str) -> str:
if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]*", value):
raise ValueError("Invalid organization or repository name")
return value
def multipart_attachment(file: Path, boundary: str) -> tuple[bytes, str]:
name = file.name
if not re.fullmatch(r"[A-Za-z0-9_.-]+", name):
raise ValueError("Unsafe release attachment filename")
header = (f'--{boundary}\r\nContent-Disposition: form-data; name="attachment"; filename="{name}"\r\n'
'Content-Type: application/octet-stream\r\n\r\n').encode("ascii")
return header + file.read_bytes() + f"\r\n--{boundary}--\r\n".encode("ascii"), f"multipart/form-data; boundary={boundary}"
def git(*args: str) -> str:
env = dict(os.environ, GIT_TERMINAL_PROMPT="0", GCM_INTERACTIVE="Never")
result = subprocess.run(["git", *args], cwd=ROOT, env=env, capture_output=True, text=True, check=True, timeout=240)
return result.stdout.strip()
def credentials() -> str:
env = dict(os.environ, GIT_TERMINAL_PROMPT="0", GCM_INTERACTIVE="Never")
result = subprocess.run(["git", "credential", "fill"], cwd=ROOT, env=env,
input=f"protocol=https\nhost={HOST}\n\n", capture_output=True, text=True, timeout=30)
fields = dict(line.split("=", 1) for line in result.stdout.splitlines() if "=" in line)
if result.returncode or not fields.get("username") or not fields.get("password"):
raise RuntimeError("No stored Git credential for git.simgreek.com; sign in using your normal Git client first")
return "Basic " + base64.b64encode((fields["username"] + ":" + fields["password"]).encode("utf8")).decode("ascii")
class Client:
def __init__(self, authorization: str):
self.authorization = authorization
# The existing Git configuration explicitly disables a proxy for this host.
self.opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect())
def request(self, path: str, method="GET", data=None, attachment=None, missing_ok=False):
headers = {"Authorization": self.authorization, "Accept": "application/json", "User-Agent": "MentorPDFExporter-release"}
body = None
if attachment:
body, headers["Content-Type"] = multipart_attachment(attachment, "mentor-release-" + uuid.uuid4().hex)
elif data is not None:
body = json.dumps(data).encode("utf8")
headers["Content-Type"] = "application/json"
url = SERVER + "/api/v1" + path
for attempt in range(3):
try:
request = urllib.request.Request(url, data=body, headers=headers, method=method)
with self.opener.open(request, timeout=180 if attachment else 30) as response:
content = response.read()
return json.loads(content) if content else None
except urllib.error.HTTPError as error:
if error.code == 404 and missing_ok:
return None
if method == "GET" and error.code in (502, 503, 504) and attempt < 2:
time.sleep(2 * (attempt + 1))
continue
raise RuntimeError(f"git.simgreek.com returned HTTP {error.code} for {path}; nothing is claimed uploaded") from None
raise RuntimeError("Server unavailable")
def attachment_hash(self, url: str) -> str:
parsed = urllib.parse.urlsplit(url)
if parsed.scheme != "https" or parsed.hostname != HOST or parsed.username or parsed.password or parsed.port not in (None, 443):
raise ValueError("Attachment download URL does not belong to the trusted Git host")
request = urllib.request.Request(url, headers={"Authorization": self.authorization, "User-Agent": "MentorPDFExporter-release"})
digest = hashlib.sha256()
with self.opener.open(request, timeout=180) as response:
while data := response.read(1024 * 1024):
digest.update(data)
return digest.hexdigest()
def file_hash(file: Path) -> str:
with file.open("rb") as source:
return hashlib.file_digest(source, "sha256").hexdigest()
def verified_artifacts(version: str) -> tuple[Path, Path]:
report = ROOT / "artifacts" / f"release-{version}" / "verification.json"
data = json.loads(report.read_text(encoding="utf8"))
archive = ROOT / "release" / f"MentorPDFExporter-{version}-win64.zip"
checksum = archive.with_suffix(".zip.sha256")
if not data.get("passed") or data.get("version") != version or data.get("zip_sha256") != file_hash(archive):
raise ValueError("Release archive does not match its passed verification report")
if checksum.read_text(encoding="ascii").split()[0] != file_hash(archive):
raise ValueError("Release ZIP checksum differs")
tree = ET.parse(ROOT / "artifacts" / "pytest-v100-final.xml")
suites = tree.getroot().iter("testsuite")
counts = [(int(s.get("tests", "0")), int(s.get("failures", "0")), int(s.get("errors", "0"))) for s in suites]
if not counts or sum(x[0] for x in counts) < 236 or any(x[1] or x[2] for x in counts):
raise ValueError("A passing complete release regression run is required")
# Re-check current application code rather than trusting stale build metadata.
sys.path.insert(0, str(ROOT / "packaging"))
from verify_release import verify_source
verify_source(ROOT / "release" / f"MentorPDFExporter-{version}" / "MentorPDFExporter.exe")
return archive, checksum
def publish(client: Client, org: str, repo: str, version: str) -> dict:
archive, checksum = verified_artifacts(version)
if git("status", "--porcelain"):
raise ValueError("Commit release source before publishing; the working tree must be clean")
commit = git("rev-parse", "HEAD")
tag = "v" + version
if git("rev-parse", tag + "^{commit}") != commit:
raise ValueError("Release tag must identify the current source commit")
remote_url = f"{SERVER}/{org}/{repo}.git"
remotes = git("remote").splitlines()
original_remote = git("remote", "get-url", "origin") if "origin" in remotes else None
if original_remote is not None and original_remote != remote_url:
raise ValueError("Existing origin differs from requested organization repository")
existing = client.request(f"/repos/{org}/{repo}", missing_ok=True)
if existing is not None and not existing.get("empty", False) and original_remote is None:
raise ValueError("Repository already contains unrelated history; refusing to overwrite it")
if existing is None:
existing = client.request(f"/orgs/{org}/repos", method="POST", data={
"name": repo, "description": "Mentor / DxDesigner PDF batch exporter for Windows",
"private": True, "auto_init": False, "default_branch": "main",
})
if original_remote is None:
git("remote", "add", "origin", remote_url)
# No force push; branch and tag are published together or not at all.
git("push", "--atomic", "-u", "origin", "HEAD:refs/heads/main", "refs/tags/" + tag)
refs = git("ls-remote", "origin", "refs/heads/main", "refs/tags/" + tag + "^{}")
refmap = dict(line.split()[::-1] for line in refs.splitlines())
if refmap.get("refs/heads/main") != commit or refmap.get("refs/tags/" + tag + "^{}") != commit:
raise ValueError("Remote branch/tag does not match the release source commit")
release = client.request(f"/repos/{org}/{repo}/releases/tags/{tag}", missing_ok=True)
if release is None:
release = client.request(f"/repos/{org}/{repo}/releases", method="POST", data={
"tag_name": tag, "target_commitish": commit, "name": f"Mentor PDF 批量导出 {tag}",
"body": (ROOT / "docs/releases" / f"{version}.md").read_text(encoding="utf8"),
"draft": False, "prerelease": False,
})
if release.get("draft") or release.get("prerelease"):
raise ValueError("Existing release is not a formal stable release; refusing implicit changes")
release_id = release["id"]
assets = {asset["name"]: asset for asset in release.get("assets", [])}
uploaded = []
for file in (archive, checksum):
asset = assets.get(file.name)
if asset is None:
asset = client.request(f"/repos/{org}/{repo}/releases/{release_id}/assets?name={urllib.parse.quote(file.name)}", method="POST", attachment=file)
if client.attachment_hash(asset["browser_download_url"]) != file_hash(file):
raise ValueError("Remote attachment hash mismatch; existing attachments are never silently replaced")
uploaded.append({"name": file.name, "sha256": file_hash(file), "url": asset["browser_download_url"]})
return {"published": True, "repository": existing["html_url"], "release": release["html_url"],
"version": version, "commit": commit, "tag": tag, "assets": uploaded}
def main(argv=None) -> int:
parser = argparse.ArgumentParser(description="Publish a verified stable release to simgreek Gitea")
parser.add_argument("--org", default="simgreek")
parser.add_argument("--repo", default="mentor-pdf-exporter")
parser.add_argument("--publish", action="store_true", help="Create the private repository if needed, push source/tag and upload the verified release")
args = parser.parse_args(argv)
org, repo = validate_name(args.org), validate_name(args.repo)
version = tomllib.loads((ROOT / "pyproject.toml").read_text(encoding="utf8"))["project"]["version"]
try:
client = Client(credentials())
server = client.request("/version")
user = client.request("/user")
organization = client.request(f"/orgs/{org}")
print(json.dumps({"server": server, "authenticated_user": user.get("login"), "organization": organization.get("username", org)}, ensure_ascii=True))
if args.publish:
result = publish(client, org, repo, version)
evidence = ROOT / "artifacts" / f"release-{version}"
evidence.mkdir(parents=True, exist_ok=True)
(evidence / "published.json").write_text(json.dumps(result, indent=2), encoding="utf8")
print(json.dumps(result, ensure_ascii=True, indent=2))
return 0
except (RuntimeError, ValueError, OSError, subprocess.CalledProcessError, urllib.error.URLError) as error:
print(f"Release not completed: {type(error).__name__}: {error}", file=sys.stderr)
return 1
if __name__ == "__main__":
raise SystemExit(main())
+4 -1
View File
@@ -1,5 +1,8 @@
# Exact runtime/build versions used for the 2026-10-09 Windows release.
# Exact runtime/build versions used for the 2026-10-10 Windows release.
PySide6==6.11.2
pypdf==6.20.0
pywin32==312
PyInstaller==6.22.3
fonttools==4.66.1
cryptography==45.0.7
cffi==2.1.1
+134
View File
@@ -0,0 +1,134 @@
"""Verify the delivered EXE, icons, source match, clean-PATH UI and ZIP."""
from __future__ import annotations
import hashlib
import json
import os
from pathlib import Path
import subprocess
import sys
import types
import zipfile
from build_release import ROOT, project_version, sha256, validate_bundle, validate_archive
def verify_source(exe: Path) -> int:
from PyInstaller.archive.readers import CArchiveReader
archive = CArchiveReader(str(exe)).open_embedded_archive("PYZ.pyz")
def normalized(code):
return code.replace(co_filename="", co_consts=tuple(normalized(c) if isinstance(c, types.CodeType) else c for c in code.co_consts))
package = ROOT / "src/mentor_pdf_export"
expected = {"mentor_pdf_export" if p.name == "__init__.py" else "mentor_pdf_export." + p.stem for p in package.glob("*.py") if p.name != "__main__.py"}
found = {n for n in archive.toc if n == "mentor_pdf_export" or n.startswith("mentor_pdf_export.")}
if found != expected:
raise ValueError("Frozen application module list differs from source")
for name in sorted(found):
source = package / ("__init__.py" if name == "mentor_pdf_export" else name.rsplit(".", 1)[1] + ".py")
code = compile(source.read_bytes(), str(source), "exec", dont_inherit=True, optimize=0)
if normalized(code) != normalized(archive.extract(name)):
raise ValueError(f"Frozen application module differs from current source: {name}")
return len(found)
def verify_shell_icon(exe: Path, output: Path) -> None:
import win32api
import win32con
import win32gui
import win32ui
from PySide6.QtGui import QImage
count = win32gui.ExtractIconEx(str(exe), -1)
if count < 1:
raise ValueError("Executable has no Windows shell icon resource")
large, small = win32gui.ExtractIconEx(str(exe), 0)
if not large or not small:
raise ValueError("Executable shell icons cannot be extracted")
desktop = win32gui.GetDC(0)
dc = win32ui.CreateDCFromHandle(desktop)
memory = dc.CreateCompatibleDC()
bitmap = win32ui.CreateBitmap()
bitmap.CreateCompatibleBitmap(dc, 64, 64)
previous = memory.SelectObject(bitmap)
try:
memory.FillSolidRect((0, 0, 64, 64), win32api.RGB(255, 255, 255))
win32gui.DrawIconEx(memory.GetSafeHdc(), 0, 0, large[0], 64, 64, 0, None, win32con.DI_NORMAL)
image = QImage(bitmap.GetBitmapBits(True), 64, 64, QImage.Format.Format_RGB32).copy()
if not image.save(str(output)):
raise ValueError("Cannot save shell icon evidence")
finally:
memory.SelectObject(previous)
win32gui.DeleteObject(bitmap.GetHandle())
memory.DeleteDC()
dc.DeleteDC()
win32gui.ReleaseDC(0, desktop)
for handle in large + small:
win32gui.DestroyIcon(handle)
def main() -> int:
import win32api
version = project_version()
bundle = ROOT / "release" / f"MentorPDFExporter-{version}"
exe = bundle / "MentorPDFExporter.exe"
archive = bundle.parent / f"MentorPDFExporter-{version}-win64.zip"
evidence = ROOT / "artifacts" / f"release-{version}"
evidence.mkdir(parents=True, exist_ok=True)
validate_bundle(bundle)
frozen_modules = verify_source(exe)
metadata = {}
for key in ("CompanyName", "FileDescription", "FileVersion", "ProductName", "ProductVersion", "OriginalFilename"):
metadata[key] = win32api.GetFileVersionInfo(str(exe), "\\StringFileInfo\\040904B0\\" + key)
assert metadata["FileVersion"] == metadata["ProductVersion"] == version
assert metadata["CompanyName"] == "simgreek"
verify_shell_icon(exe, evidence / "exe-icon.png")
packaged_icon = bundle / "_internal/mentor_pdf_export/assets/app.ico"
assert packaged_icon.read_bytes() == (ROOT / "src/mentor_pdf_export/assets/app.ico").read_bytes()
manifest = json.loads((bundle / "manifest.json").read_text(encoding="utf8"))
assert manifest["version"] == version and manifest["channel"] == "stable"
validate_bundle(bundle, runtime_files=manifest["runtime_files"], license_files=manifest["license_files"])
assert manifest["exe_sha256"] == sha256(exe) and manifest["icon_sha256"] == sha256(packaged_icon)
for line in (bundle / "SHA256SUMS.txt").read_text(encoding="utf8").splitlines():
expected, relative = line.split(" ", 1)
file = (bundle / relative).resolve()
assert file.is_relative_to(bundle.resolve()) and sha256(file) == expected
assert archive.with_suffix(".zip.sha256").read_text(encoding="ascii").split()[0] == sha256(archive)
validate_archive(archive, bundle)
with zipfile.ZipFile(archive) as zipped:
assert zipped.testzip() is None
assert hashlib.sha256(zipped.read(bundle.name + "/MentorPDFExporter.exe")).hexdigest() == sha256(exe)
assert zipped.read(bundle.name + "/_internal/mentor_pdf_export/assets/app.ico") == packaged_icon.read_bytes()
assert zipped.read(bundle.name + "/发布说明.txt") == (ROOT / "docs/releases" / f"{version}.md").read_bytes()
source = evidence / "smoke-projects"
for name in ("Example-A", "Example-B", "Example-C"):
directory = source / name
directory.mkdir(parents=True, exist_ok=True)
(directory / (name + ".prj")).write_text('SECTION DesignInfo\nKEY FrontEndSnapshot "DxD"\nENDSECTION\nSECTION iCDB\nKEY iCDBDir ".\\database"\nENDSECTION\n', encoding="utf8")
env = dict(os.environ)
for key in ("PYTHONPATH", "PYTHONHOME", "QT_PLUGIN_PATH", "QT_QPA_PLATFORM_PLUGIN_PATH", "QT_QPA_PLATFORM"):
env.pop(key, None)
env["PATH"] = str(Path(os.environ.get("WINDIR", "C:/Windows")) / "System32")
check = evidence / "self-check.json"
subprocess.run([str(exe), "--self-check", "--report", str(check)], cwd=bundle, env=env, timeout=60, check=True, creationflags=subprocess.CREATE_NO_WINDOW)
self_check = json.loads(check.read_text(encoding="utf8"))
assert self_check["version"] == version and self_check["frozen"] and self_check["ui_import_ok"]
report = evidence / "ui.json"
shot = evidence / "ui.png"
subprocess.run([str(exe), "--project-root", str(source), "--output", str(evidence / "output"), "--ui-smoke", str(shot), "--report", str(report)], cwd=bundle, env=env, timeout=90, check=True, creationflags=subprocess.CREATE_NO_WINDOW)
ui = json.loads(report.read_text(encoding="utf8"))
assert ui["version"] == version and ui["projects"] == 3 and ui["screenshot_saved"]
assert ui["application_icon"] and ui["window_icon"] and ui["app_id_set"]
assert ui["app_id"] == "simgreek.MentorPDFExporter" and not ui["ui_export_requested"]
result = {
"passed": True, "version": version, "channel": "stable", "frozen_source_modules_match": frozen_modules,
"exe_sha256": sha256(exe), "zip_sha256": sha256(archive), "zip_bytes": archive.stat().st_size,
"windows_metadata": metadata, "exe_shell_icon": True, "packaged_window_icon_matches": True,
"stable_taskbar_app_id": ui["app_id"], "clean_path_default_ui": True, "scanned_projects": ui["projects"],
"zip_crc_ok": True, "private_projects_or_fonts_shipped": False,
}
(evidence / "verification.json").write_text(json.dumps(result, indent=2), encoding="utf8")
print(json.dumps(result, indent=2))
return 0
if __name__ == "__main__":
raise SystemExit(main())