Branchwell

PulseCanvas / app · pulsecanvas.ai / scripts / package-mac-dmg.py

Raw 8.7 KB on 87dd19288bbd69b69b6ac6e250fb5d18bfebb877
1#!/usr/bin/env python3
2"""Build a Finder-styled DMG, then inspect its real mounted resources/layout."""
3import argparse
4import hashlib
5import json
6import os
7from pathlib import Path
8import plistlib
9import subprocess
10import tempfile
11
12from dmgbuild import build_dmg
13from ds_store import DSStore
14from mac_alias import Alias
15
16ROOT = Path(__file__).resolve().parent.parent
17BACKGROUND = Path("Contents/Resources/PulseCanvasInstallerBackground.tiff")
18APP_NAME = "PulseCanvas Studio.app"
19DIRECT_CONFIG = json.loads((ROOT / "macOS/DirectRelease.json").read_text())
20
21
22def bundle_inventory(app: Path) -> dict:
23 inventory = {".": ("directory", app.stat().st_mode & 0o7777)}
24 for path in app.rglob("*"):
25 name = str(path.relative_to(app))
26 if path.is_symlink():
27 inventory[name] = ("symlink", path.lstat().st_mode & 0o7777, os.readlink(path))
28 elif path.is_file():
29 inventory[name] = ("file", path.stat().st_mode & 0o7777,
30 hashlib.sha256(path.read_bytes()).hexdigest())
31 elif path.is_dir():
32 inventory[name] = ("directory", path.stat().st_mode & 0o7777)
33 return inventory
34
35
36def install_background_reference(mount: Path) -> None:
37 """Point Finder at signed bundle artwork without creating a root-level file."""
38 with DSStore.open(str(mount / ".DS_Store"), "r+") as store:
39 icons = store["."]["icvp"]
40 icons["backgroundType"] = 2
41 icons["backgroundImageAlias"] = Alias.for_file(str(mount / "PulseCanvas Studio.app" / BACKGROUND)).to_bytes()
42 store["."]["icvp"] = icons
43
44
45def verify(image: Path, source_app: Path, release_checks: bool = False) -> dict:
46 if not __debug__:
47 raise RuntimeError("Run the verifier without Python -O; assertions are required")
48 with tempfile.TemporaryDirectory(prefix="pulsecanvas-dmg-inspection-") as temporary:
49 mount = Path(temporary) / "volume"
50 mount.mkdir()
51 subprocess.run(["hdiutil", "attach", "-readonly", "-nobrowse", "-noautoopen",
52 "-mountpoint", str(mount), str(image)], check=True,
53 stdout=subprocess.DEVNULL)
54 try:
55 assert (mount / "PulseCanvas Studio.app").is_dir(), "App missing from installer"
56 assert os.readlink(mount / "Applications") == "/Applications"
57 visible = {path.name for path in mount.iterdir() if not path.name.startswith(".")}
58 assert visible == {"PulseCanvas Studio.app", "Applications"}, visible
59 root_items = sorted(path.name for path in mount.iterdir())
60 allowed_metadata = {".DS_Store", ".Trashes", ".fseventsd", ".HFS+ Private Directory Data\r"}
61 assert set(root_items) <= visible | allowed_metadata, root_items
62 # Check Finder metadata in the final compressed image, not staging only.
63 with DSStore.open(str(mount / ".DS_Store"), "r") as store:
64 window = store["."]["bwsp"]
65 icons = store["."]["icvp"]
66 locations = {name: tuple(store[name]["Iloc"])
67 for name in ("PulseCanvas Studio.app", "Applications")}
68 assert store["."]["icvl"] == (b"type", b"icnv")
69 assert window["WindowBounds"] == "{{160, 160}, {720, 520}}", window
70 for key in ("ShowToolbar", "ShowSidebar", "ShowStatusBar", "ShowPathbar", "ShowTabView"):
71 assert not window[key], (key, window)
72 assert icons["arrangeBy"] == "none"
73 assert icons["iconSize"] == 104
74 assert icons["textSize"] == 15
75 assert icons["labelOnBottom"]
76 assert (icons["scrollPositionX"], icons["scrollPositionY"]) == (0, 0)
77 assert icons["backgroundType"] == 2
78 assert locations == {"PulseCanvas Studio.app": (195, 230), "Applications": (525, 230)}
79 assert not any(path.name.startswith(".background") for path in mount.iterdir())
80 background = mount / "PulseCanvas Studio.app" / BACKGROUND
81 assert background.is_file(), "Retina background missing"
82 assert background.read_bytes() == (ROOT / "packaging/macos/background.tiff").read_bytes()
83 alias = Alias.from_bytes(icons["backgroundImageAlias"])
84 assert alias.target.filename == background.name, alias.target.filename
85 assert alias.target.posix_path.lstrip("/") == str(Path(APP_NAME) / BACKGROUND), alias.target.posix_path
86 # Compare links without following Sparkle framework directory aliases.
87 assert bundle_inventory(source_app) == bundle_inventory(mount / "PulseCanvas Studio.app")
88 subprocess.run(["codesign", "--verify", "--deep", "--strict", str(mount / "PulseCanvas Studio.app")], check=True)
89 info = plistlib.loads((mount / "PulseCanvas Studio.app/Contents/Info.plist").read_bytes())
90 assert info["CFBundleIdentifier"] == DIRECT_CONFIG["bundleIdentifier"]
91 assert info["SUFeedURL"] == DIRECT_CONFIG["feedURL"]
92 assert info["SUPublicEDKey"] == DIRECT_CONFIG["sparklePublicKey"]
93 if release_checks:
94 signature = subprocess.run(["codesign", "--display", "--verbose=4", str(mount / APP_NAME)],
95 check=True, capture_output=True, text=True).stderr
96 assert "TeamIdentifier=22HV69L32T" in signature, "Wrong signing team"
97 assert "Authority=Developer ID Application: Protomota, LLC (22HV69L32T)" in signature, "Developer ID signature required"
98 subprocess.run(["codesign", "--verify", "--strict", str(image)], check=True)
99 subprocess.run(["xcrun", "stapler", "validate", str(image)], check=True)
100 subprocess.run(["spctl", "--assess", "--type", "execute", "--verbose=2",
101 str(mount / APP_NAME)], check=True)
102 return {"window_size": [720, 520], "icon_locations": locations,
103 "icon_size": 104, "text_size": 15, "scroll_position": [0, 0],
104 "background": str(Path("PulseCanvas Studio.app") / BACKGROUND),
105 "background_sha256": hashlib.sha256(background.read_bytes()).hexdigest(),
106 "root_items": root_items, "direct_updater_configuration_matches": True,
107 "release_checks_passed": release_checks,
108 "app_version": info.get("CFBundleShortVersionString"),
109 "app_build": info.get("CFBundleVersion"),
110 "app_bytes_match": True, "applications_target": "/Applications"}
111 finally:
112 subprocess.run(["hdiutil", "detach", str(mount)], check=True,
113 stdout=subprocess.DEVNULL)
114
115
116def main() -> None:
117 parser = argparse.ArgumentParser(description=__doc__)
118 parser.add_argument("--app", required=True, type=Path)
119 parser.add_argument("--output", required=True, type=Path)
120 parser.add_argument("--verify-only", action="store_true")
121 parser.add_argument("--release-checks", action="store_true",
122 help="Also require DMG signature/staple and mounted app Gatekeeper acceptance")
123 args = parser.parse_args()
124 app, image = args.app.resolve(), args.output.resolve()
125 if app.name != "PulseCanvas Studio.app" or not (app / "Contents/Info.plist").is_file():
126 parser.error("--app must be an existing PulseCanvas Studio.app bundle")
127 if not (app / BACKGROUND).is_file():
128 parser.error("Embed packaging/macos/background.tiff in the app's Resources before signing")
129 if (app / BACKGROUND).read_bytes() != (ROOT / "packaging/macos/background.tiff").read_bytes():
130 parser.error("App background must match the committed installer artwork")
131 subprocess.run(["codesign", "--verify", "--deep", "--strict", str(app)], check=True)
132 if not args.verify_only:
133 if image.exists():
134 parser.error("--output already exists; choose a fresh output path")
135 image.parent.mkdir(parents=True, exist_ok=True)
136 mounted = {}
137 def remember_mount(mount_point: str, options: dict) -> None:
138 mounted["path"] = Path(mount_point)
139 def finish_layout(event: dict) -> None:
140 if event.get("type") == "operation::finished" and event.get("operation") == "dsstore::create":
141 install_background_reference(mounted["path"])
142 build_dmg(str(image), "PulseCanvas Studio", settings_file=str(ROOT / "packaging/macos/settings.py"),
143 defines={"app": str(app)},
144 settings={"create_hook": remember_mount}, callback=finish_layout)
145 report = verify(image, app, args.release_checks)
146 image.with_suffix(".layout.json").write_text(json.dumps(report, indent=2) + "\n")
147 print("Installer layout verified:", json.dumps(report))
148
149
150if __name__ == "__main__":
151 main()