Branchwell

Voxley / app · voxley.si / Scripts / package-mac-dmg.py

Raw 6.2 KB on 65820bdbf93f3277c3f8b2c09a8acbcf3783d60a
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
10
11from dmgbuild import build_dmg
12from ds_store import DSStore
13from mac_alias import Alias
14
15ROOT = Path(__file__).resolve().parent.parent
16BACKGROUND = Path("Contents/Resources/VoxleyInstallerBackground.tiff")
17
18
19def bundle_inventory(app: Path) -> dict:
20 inventory = {}
21 for path in app.rglob("*"):
22 name = str(path.relative_to(app))
23 if path.is_symlink():
24 inventory[name] = ("symlink", os.readlink(path))
25 elif path.is_file():
26 inventory[name] = ("file", path.stat().st_mode & 0o777,
27 hashlib.sha256(path.read_bytes()).hexdigest())
28 elif path.is_dir():
29 inventory[name] = ("directory", path.stat().st_mode & 0o777)
30 return inventory
31
32
33def install_background_reference(mount: Path) -> None:
34 """Point Finder at signed bundle artwork without creating a root-level file."""
35 with DSStore.open(str(mount / ".DS_Store"), "r+") as store:
36 icons = store["."]["icvp"]
37 icons["backgroundType"] = 2
38 icons["backgroundImageAlias"] = Alias.for_file(str(mount / "Voxley.app" / BACKGROUND)).to_bytes()
39 store["."]["icvp"] = icons
40
41
42def verify(image: Path, source_app: Path) -> dict:
43 attachment = subprocess.check_output([
44 "hdiutil", "attach", "-readonly", "-nobrowse", "-noautoopen", "-plist", str(image)
45 ])
46 volume = next(entry for entry in plistlib.loads(attachment)["system-entities"] if "mount-point" in entry)
47 mount = Path(volume["mount-point"])
48 try:
49 assert (mount / "Voxley.app").is_dir(), "App missing from installer"
50 assert os.readlink(mount / "Applications") == "/Applications"
51 visible = {path.name for path in mount.iterdir() if not path.name.startswith(".")}
52 assert visible == {"Voxley.app", "Applications"}, visible
53 # Check Finder metadata in the final compressed image, not staging only.
54 with DSStore.open(str(mount / ".DS_Store"), "r") as store:
55 window = store["."]["bwsp"]
56 icons = store["."]["icvp"]
57 locations = {name: tuple(store[name]["Iloc"])
58 for name in ("Voxley.app", "Applications")}
59 assert store["."]["icvl"] == (b"type", b"icnv")
60 assert window["WindowBounds"] == "{{160, 160}, {720, 520}}", window
61 for key in ("ShowToolbar", "ShowSidebar", "ShowStatusBar", "ShowPathbar", "ShowTabView"):
62 assert not window[key], (key, window)
63 assert icons["arrangeBy"] == "none"
64 assert icons["iconSize"] == 104
65 assert icons["backgroundType"] == 2
66 assert locations == {"Voxley.app": (195, 230), "Applications": (525, 230)}
67 assert not any(path.name.startswith(".background") for path in mount.iterdir())
68 background = mount / "Voxley.app" / BACKGROUND
69 assert background.is_file(), "Retina background missing"
70 assert background.read_bytes() == (ROOT / "Packaging/macOS/background.tiff").read_bytes()
71 alias = Alias.from_bytes(icons["backgroundImageAlias"])
72 assert alias.target.filename == background.name, alias.target.filename
73 assert alias.target.posix_path.lstrip("/") == str(Path("Voxley.app") / BACKGROUND)
74 # Compare links without following Sparkle framework directory aliases.
75 assert bundle_inventory(source_app) == bundle_inventory(mount / "Voxley.app")
76 subprocess.run(["codesign", "--verify", "--deep", "--strict", str(mount / "Voxley.app")], check=True)
77 info = plistlib.loads((mount / "Voxley.app/Contents/Info.plist").read_bytes())
78 assert info["CFBundleIdentifier"] == "com.protomota.voxley"
79 sparkle = plistlib.loads((ROOT / "Scripts/Sparkle.plist").read_bytes())
80 assert all(info[key] == value for key, value in sparkle.items())
81 assert (mount / "Voxley.app/Contents/Frameworks/Sparkle.framework/Sparkle").is_file()
82 return {"window_size": [720, 520], "icon_locations": locations,
83 "icon_size": 104, "background": str(Path("Voxley.app") / BACKGROUND),
84 "app_version": info.get("CFBundleShortVersionString"),
85 "app_build": info.get("CFBundleVersion"),
86 "app_bytes_match": True, "applications_target": "/Applications"}
87 finally:
88 subprocess.run(["hdiutil", "detach", str(mount)], check=True, stdout=subprocess.DEVNULL)
89
90
91def main() -> None:
92 if not __debug__:
93 raise RuntimeError("Run without Python -O so installer verification is enabled")
94 parser = argparse.ArgumentParser(description=__doc__)
95 parser.add_argument("--app", required=True, type=Path)
96 parser.add_argument("--output", required=True, type=Path)
97 parser.add_argument("--verify-only", action="store_true")
98 args = parser.parse_args()
99 app, image = args.app.resolve(), args.output.resolve()
100 if app.name != "Voxley.app" or not (app / "Contents/Info.plist").is_file():
101 parser.error("--app must be an existing Voxley.app bundle")
102 if not (app / BACKGROUND).is_file():
103 parser.error("Embed Packaging/macOS/background.tiff in the app's Resources before signing")
104 subprocess.run(["codesign", "--verify", "--deep", "--strict", str(app)], check=True)
105 if not args.verify_only:
106 if image.exists():
107 parser.error("--output already exists; choose a fresh output path")
108 image.parent.mkdir(parents=True, exist_ok=True)
109 mounted = {}
110
111 def remember_mount(mount_point, options):
112 mounted["path"] = Path(mount_point)
113
114 def finish_layout(event):
115 if event.get("type") == "operation::finished" and event.get("operation") == "dsstore::create":
116 install_background_reference(mounted["path"])
117
118 build_dmg(str(image), "Voxley", settings_file=str(ROOT / "Packaging/macOS/settings.py"),
119 defines={"app": str(app)},
120 settings={"create_hook": remember_mount}, callback=finish_layout)
121 report = verify(image, app)
122 image.with_suffix(".layout.json").write_text(json.dumps(report, indent=2) + "\n")
123 print("Installer layout verified:", json.dumps(report))
124
125
126if __name__ == "__main__":
127 main()