135 lines
7.2 KiB
Python
135 lines
7.2 KiB
Python
"""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())
|