Branchwell

Inkspring / app / build / package-installer.py

1"""Package a signed Mac app in the PulseCanvas Finder installer layout."""
2
3import argparse
4import json
5import os
6from pathlib import Path
7import subprocess
8import tempfile
9
10from dmgbuild import build_dmg
11from ds_store import DSStore
12from mac_alias import Alias
13
14ARTWORK = Path("Contents/Resources/installer-background.tiff")
15
16
17def run(*command: str) -> None:
18 subprocess.run(command, check=True)
19
20
21def notarize(artifact: Path, staple_target: Path | None = None) -> None:
22 """Read the Apple notarization credential options."""
23 env = os.environ
24 if env.get("APPLE_ID") and env.get("APPLE_APP_SPECIFIC_PASSWORD"):
25 credentials = ["--apple-id", env["APPLE_ID"],
26 "--password", env["APPLE_APP_SPECIFIC_PASSWORD"],
27 "--team-id", env["APPLE_TEAM_ID"]]
28 elif env.get("APPLE_API_KEY"):
29 credentials = ["--key", env["APPLE_API_KEY"], "--key-id", env["APPLE_API_KEY_ID"],
30 "--issuer", env["APPLE_API_ISSUER"]]
31 else:
32 credentials = ["--keychain-profile", env["APPLE_KEYCHAIN_PROFILE"]]
33 if env.get("APPLE_KEYCHAIN"):
34 credentials += ["--keychain", env["APPLE_KEYCHAIN"]]
35 result = subprocess.run(
36 ["xcrun", "notarytool", "submit", str(artifact), *credentials, "--wait",
37 "--output-format", "json"], capture_output=True, text=True,
38 )
39 if result.returncode:
40 raise RuntimeError(f"Apple notarization command failed for {artifact.name}")
41 receipt = json.loads(result.stdout)
42 artifact.with_suffix(".notarization.json").write_text(json.dumps(receipt, indent=2) + "\n")
43 if receipt.get("status") != "Accepted":
44 raise RuntimeError(f"Apple did not accept {artifact.name}: {receipt.get('status')}")
45 target = str(staple_target or artifact)
46 run("xcrun", "stapler", "staple", target)
47 run("xcrun", "stapler", "validate", target)
48
49
50def package(app: Path, output: Path, title: str) -> None:
51 if not (app / ARTWORK).is_file() or output.exists():
52 raise ValueError("Use an app containing the installer artwork and a new output path")
53 run("codesign", "--verify", "--deep", "--strict", str(app))
54 mount: Path
55
56 def remember_mount(mount_point: str, _options: dict) -> None:
57 nonlocal mount
58 mount = Path(mount_point)
59
60 def write_background_alias(event: dict) -> None:
61 if event.get("type") != "operation::finished" or event.get("operation") != "dsstore::create":
62 return
63 with DSStore.open(str(mount / ".DS_Store"), "r+") as store:
64 icons = store["."]["icvp"]
65 icons["backgroundType"] = 2
66 icons["backgroundImageAlias"] = Alias.for_file(str(mount / app.name / ARTWORK)).to_bytes()
67 store["."]["icvp"] = icons
68
69 build_dmg(str(output), title, settings={
70 "format": "UDZO",
71 "filesystem": "HFS+",
72 "files": [str(app)],
73 "symlinks": {"Applications": "/Applications"},
74 "window_rect": ((160, 160), (720, 520)),
75 "default_view": "icon-view",
76 "show_toolbar": False,
77 "show_sidebar": False,
78 "show_status_bar": False,
79 "show_pathbar": False,
80 "show_tab_view": False,
81 "arrange_by": None,
82 "scroll_position": (0, 0),
83 "icon_size": 104,
84 "text_size": 15,
85 "label_pos": "bottom",
86 "icon_locations": {app.name: (195, 230), "Applications": (525, 230)},
87 "create_hook": remember_mount,
88 }, callback=write_background_alias)
89 identity = os.environ.get("CSC_NAME") or "Developer ID Application: Protomota, LLC (22HV69L32T)"
90 if not identity.startswith("Developer ID Application: "):
91 identity = f"Developer ID Application: {identity}"
92 keychain = os.environ.get("CSC_KEYCHAIN") or str(Path.home() / "Library/Keychains/login.keychain-db")
93 run("codesign", "--timestamp", "--sign", identity, "--keychain", keychain, str(output))
94 notarize(output)
95 run("codesign", "--verify", "--strict", str(output))
96 run("spctl", "--assess", "--type", "open", "--context", "context:primary-signature",
97 "--verbose=2", str(output))
98
99
100def main() -> None:
101 parser = argparse.ArgumentParser(description=__doc__)
102 parser.add_argument("app", type=Path)
103 parser.add_argument("output", type=Path)
104 parser.add_argument("title", nargs="?")
105 parser.add_argument("--notarize-app", action="store_true")
106 args = parser.parse_args()
107 if args.notarize_app:
108 with tempfile.TemporaryDirectory(prefix="notary-app-") as temporary:
109 archive = Path(temporary) / f"{args.app.stem}.zip"
110 run("ditto", "-c", "-k", "--sequesterRsrc", "--keepParent", str(args.app), str(archive))
111 notarize(archive, args.app)
112 package(args.app, args.output, args.title or args.app.stem)
113
114
115if __name__ == "__main__":
116 main()