Branchwell

Jotley / app · jotley.ai / scripts / package-mac-dmg.py

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