Debian Codegraph @

src/briefcase/platforms/macOS/__init__.py

raw
1 from __future__ import annotations
2
3 import concurrent.futures
4 import os
5 import plistlib
6 import re
7 import subprocess
8 import time
9 from collections.abc import Collection
10 from contextlib import suppress
11 from pathlib import Path
12 from signal import SIGTERM
13
14 from packaging.version import Version
15
16 from briefcase.config import AppConfig
17 from briefcase.exceptions import BriefcaseCommandError, NotarizationInterrupted
18 from briefcase.integrations.subprocess import (
19 get_process_id_by_command,
20 is_process_dead,
21 json_parser,
22 )
23 from briefcase.integrations.xcode import XcodeCliTools, get_identities
24 from briefcase.platforms.macOS.filters import macOS_log_clean_filter
25 from briefcase.platforms.macOS.utils import AppPackagesMergeMixin, is_mach_o_binary
26
27 try:
28 import dmgbuild
29 except ImportError: # pragma: no-cover-if-is-macos
30 # On non-macOS platforms, dmgbuild won't be installed.
31 # Allow the plugin to be loaded; raise an error when tools are verified.
32 dmgbuild = None
33
34
35 DEFAULT_OUTPUT_FORMAT = "app"
36
37 ADHOC_IDENTITY_NAME = (
38 "Ad-hoc identity. The resulting package will run but cannot be re-distributed."
39 )
40
41
42 class SigningIdentity:
43 def __init__(self, id="-", name=None):
44 """A wrapper around the various forms of an Apple signing identity."""
45 self.id = id
46 if self.id == "-":
47 self.team_id = None
48 self.name = ADHOC_IDENTITY_NAME
49 self.profile = None
50 else:
51 self.name = name
52 self.team_id = self.team_id_from_name(name)
53 self.profile = f"briefcase-macOS-{self.team_id}"
54
55 @classmethod
56 def team_id_from_name(cls, name):
57 try:
58 return re.match(r".*\(([\dA-Z]*)\)", name)[1]
59 except TypeError:
60 raise BriefcaseCommandError(
61 f"Couldn't extract Team ID from signing identity {name!r}"
62 ) from None
63
64 @property
65 def is_adhoc(self):
66 """Is this the adhoc identity?"""
67 return self.id == "-"
68
69 def __repr__(self):
70 if self.is_adhoc:
71 return "<AdhocSigningIdentity>"
72 else:
73 return f"<SigningIdentity id={self.id}>"
74
75 def __eq__(self, other):
76 return isinstance(other, SigningIdentity) and self.id == other.id
77
78
79 class macOSMixin:
80 platform = "macOS"
81 supported_host_os: Collection[str] = {"Darwin"}
82 supported_host_os_reason = "macOS applications can only be built on macOS."
83 # 0.3.20 introduced a framework-based support package.
84 platform_target_version: str | None = "0.3.20"
85
86 def bundle_package_path(self, app) -> Path:
87 return self.binary_path(app)
88
89 def is_icloud_synced(self, path: Path) -> bool:
90 """Determine if a path is on an iCloud drive.
91
92 This is done by looking for the "com.apple.fileprovider.fpfs#P" resource fork.
93 This fork only appears on *some* directories - most notably, `.app` folders.
94
95 :param path: The location to check.
96 :returns: True if the location has iCloud resource markers.
97 """
98 # Check if the path is on an iCloud mounted drive.
99 try:
100 # Check for the iCloud resource fork. "Good" operation produces an error,
101 # so use quiet mode.
102 self.tools.subprocess.check_output(
103 [
104 "xattr",
105 "-p",
106 "com.apple.fileprovider.fpfs#P",
107 path,
108 ],
109 quiet=1,
110 )
111 # The resource fork was found.
112 return True
113 except subprocess.CalledProcessError:
114 # The resource fork was not found.
115 # This includes the file not existing.
116 return False
117
118 def verify_not_on_icloud(self, app: AppConfig, cleanup=False):
119 """Confirm that the app is *not* on an iCloud synchronized drive.
120
121 When a `.app` folder is on an iCloud-synchronized drive, iCloud adds filesystem
122 metadata to the folder. This metadata can't be removed (iCloud will just put it
123 back again), but it also conflicts with app signing. So - if we detect this
124 metadata, the project has been generated somewhere that ultimately won't work.
125
126 Optionally, this method will clean up the bundle if the verification fails.
127
128 :param app: The app to check.
129 :param cleanup: Should the app bundle be deleted if verification fails?
130 """
131 if self.is_icloud_synced(self.binary_path(app)):
132 msg = [
133 """\
134 Your project is in a folder that is synchronized with iCloud. This interferes
135 with the operation of macOS code signing."""
136 ]
137 if cleanup:
138 self.tools.shutil.rmtree(self.bundle_path(app))
139 msg.append(f"""
140 Move your project to a location that is not synchronized with iCloud,
141 and re-run `briefcase {self.command}`.""")
142 else:
143 bundle_path = self.bundle_path(app).relative_to(self.base_path)
144 msg.append(f"""
145 Delete the {bundle_path} folder, move your project to location
146 that is not synchronized with iCloud, and re-run `briefcase {self.command}`.""")
147 raise BriefcaseCommandError("\n".join(msg))
148
149
150 class macOSCreateMixin(AppPackagesMergeMixin):
151 hidden_app_properties: Collection[str] = {"permission", "entitlement"}
152
153 def generate_app_template(self, app: AppConfig):
154 """Create an application bundle.
155
156 :param app: The config object for the app
157 """
158 # Before we generate the app template, make sure the package path and formal
159 # name match. This will always be the case for internal apps; they might not be
160 # aligned for external apps. We can't do this in verify, because app
161 # verification occurs after the template is generated.
162 if self.package_path(app).name != f"{app.formal_name}.app":
163 raise BriefcaseCommandError(
164 "The app bundle referenced by external_package_path "
165 f"({self.package_path(app).name})\n"
166 f"does not match the formal name of the app ({app.formal_name!r}).\n"
167 )
168
169 super().generate_app_template(app=app)
170 # If we discover we're on iCloud during app creation, we can clean up the app
171 # folder. This *may* return a false negative (i.e., not accurately detect that
172 # we *are* on iCloud, because it takes a moment for the iCloud daemon to detect
173 # that a new folder has been created; however, if this occurs, it will be
174 # picked up on the next run of any Briefcase command).
175 self.verify_not_on_icloud(app, cleanup=True)
176
177 def _install_app_requirements(
178 self,
179 app: AppConfig,
180 requires: list[str],
181 app_packages_path: Path,
182 **kwargs,
183 ):
184 try:
185 # Determine the min macOS version from the framework metadata
186 # of the macos-arm64_x86_64 slice of the XCframework
187 plist_file = (
188 self.support_path(app)
189 / "Python.xcframework/macos-arm64_x86_64"
190 / "Python.framework/Resources/Info.plist"
191 )
192 with plist_file.open("rb") as f:
193 info_plist = plistlib.load(f)
194
195 support_min_version = info_plist.get("MinimumOSVersion", "11.0")
196 except FileNotFoundError:
197 # If a plist file couldn't be found, it's an old-style support package;
198 # Determine min. macOS version from the VERSIONS file in the support package
199 versions = dict(
200 [part.strip() for part in line.split(": ", 1)]
201 for line in (
202 (self.support_path(app) / "VERSIONS")
203 .read_text(encoding="UTF-8")
204 .split("\n")
205 )
206 if ": " in line
207 )
208 support_min_version = versions.get("Min macOS version", "11.0")
209
210 # Check that the app's definition is compatible with the support package
211 # If the app doesn't specify a minimum version, use the support package
212 # minimum version as a default.
213 macOS_min_version = getattr(app, "min_os_version", support_min_version)
214
215 if Version(macOS_min_version) < Version(support_min_version):
216 raise BriefcaseCommandError(
217 "Your macOS app specifies a minimum macOS version of "
218 f"{macOS_min_version}, but the support package only supports "
219 f"{support_min_version}"
220 )
221
222 macOS_min_tag = macOS_min_version.replace(".", "_")
223
224 if getattr(app, "universal_build", True):
225 # Perform the initial install targeting the current platform
226 host_app_packages_path = (
227 self.bundle_path(app) / f"app_packages.{self.tools.host_arch}"
228 )
229 # A standard install, except we explicitly reject installs from source
230 # tarballs with `--only-binary :all:`. This is for two reasons:
231 #
232 # 1. Consistency. We need to use `--only-binary :all:` when we do the second
233 # "other arch" wheel install because of use of the `--platform` argument;
234 # if we only reject source tarballs from one of the installs, then a
235 # package that only provides binary wheels for one architecture would
236 # cause inconsistent results depending on which platform was the host;
237 # and
238 #
239 # 2. Security. Installs from source tarball involve executing arbitrary code
240 # at time of installation; and it makes the entire development
241 # environment building the app a vector for introducing vulnerabilities
242 # into an app. Forcing the use of binary wheels ensures that we can know
243 # with certainty the provenance of any binary content in the app.
244 #
245 # Since Briefcase is a tool designed to produce redistributable binaries,
246 # we've made the judgement call that the (minor, with known workarounds)
247 # inconvenience of not being able to use source tarballs is outweighed by
248 # the need to produce reliable, repeatable binary artefacts.
249 super()._install_app_requirements(
250 app,
251 requires=requires,
252 app_packages_path=host_app_packages_path,
253 pip_args=[
254 "--only-binary",
255 ":all:",
256 "--platform",
257 f"macosx_{macOS_min_tag}_{self.tools.host_arch}",
258 ],
259 install_hint=f"""
260
261 This may be because an {self.tools.host_arch} wheel that is compatible with a minimum
262 macOS version of {macOS_min_version} is not available.
263 """,
264 )
265
266 # Install dependencies for the architecture that isn't the host architecture
267 other_arch = {
268 "arm64": "x86_64",
269 "x86_64": "arm64",
270 }[self.tools.host_arch]
271
272 # Create a temporary folder targeting the other platform
273 other_app_packages_path = (
274 self.bundle_path(app) / f"app_packages.{other_arch}"
275 )
276 if other_app_packages_path.is_dir():
277 self.tools.shutil.rmtree(other_app_packages_path)
278 self.tools.os.mkdir(other_app_packages_path)
279
280 # Find all the packages with binary components.
281 # We can ignore any -universal2 packages; they're already fat.
282 binary_packages = self.find_binary_packages(
283 host_app_packages_path,
284 universal_suffix="_universal2",
285 other_suffix=f"_{other_arch}",
286 )
287 if binary_packages:
288 with self.console.wait_bar(
289 f"Installing binary app requirements for {other_arch}..."
290 ):
291 self._pip_install(
292 app,
293 app_packages_path=other_app_packages_path,
294 pip_args=[
295 "--no-deps",
296 "--platform",
297 f"macosx_{macOS_min_tag}_{other_arch}",
298 "--only-binary",
299 ":all:",
300 ]
301 + [
302 f"{package}=={version}"
303 for package, version in binary_packages
304 ],
305 install_hint=f"""
306
307 This may be because an {other_arch} wheel that is compatible with a minimum
308 macOS version of {macOS_min_version} is not available.
309
310 You may need to build a non-universal app by setting:
311
312 universal_build = False
313
314 in the macOS configuration section of your pyproject.toml.
315 """,
316 )
317 else:
318 self.console.info("All packages are pure Python, or universal.")
319
320 # If given the option of a single architecture binary or a universal2
321 # binary, pip will install the single platform binary. However, a common
322 # situation on macOS is for there to be an x86_64 binary and a universal2
323 # binary. This means you only get a universal2 binary in the "other" install
324 # pass. This then causes problems with merging, because the "other" binary
325 # contains a copy of the architecture that the "host" platform provides.
326 #
327 # To avoid this - ensure that the libraries in the app packages for the
328 # "other" arch are all thin.
329 #
330 # This doesn't matter if it happens the other way around - if the "host"
331 # arch installs a universal binary, then the "other" arch won't be asked to
332 # install a binary at all.
333 self.thin_app_packages(other_app_packages_path, arch=other_arch)
334
335 # Merge the binaries
336 self.merge_app_packages(
337 target_app_packages=app_packages_path,
338 sources=[host_app_packages_path, other_app_packages_path],
339 )
340 else:
341 # If we're not building a universal binary, we can do a single install pass
342 # directly into the app_packages folder.
343 super()._install_app_requirements(
344 app,
345 requires=requires,
346 app_packages_path=app_packages_path,
347 pip_args=[
348 "--only-binary",
349 ":all:",
350 "--platform",
351 f"macosx_{macOS_min_tag}_{self.tools.host_arch}",
352 ],
353 )
354
355 # Since we're only targeting 1 architecture, we can strip any universal
356 # libraries down to just the host architecture.
357 self.thin_app_packages(app_packages_path, arch=self.tools.host_arch)
358
359 def permissions_context(self, app: AppConfig, cross_platform: dict[str, str]):
360 """Additional template context for permissions.
361
362 :param app: The config object for the app
363 :param cross_platform: The dictionary of known cross-platform permission
364 definitions.
365 :returns: The template context describing permissions for the app.
366 """
367 # The info.plist entries for the app
368 info = {}
369
370 # Default entitlements for all macOS apps
371 entitlements = {
372 "com.apple.security.cs.allow-unsigned-executable-memory": True,
373 "com.apple.security.cs.disable-library-validation": True,
374 }
375
376 if cross_platform["bluetooth"]:
377 entitlements["com.apple.security.device.bluetooth"] = True
378 info["NSBluetoothAlwaysUsageDescription"] = cross_platform["bluetooth"]
379 if cross_platform["camera"]:
380 entitlements["com.apple.security.device.camera"] = True
381 info["NSCameraUsageDescription"] = cross_platform["camera"]
382 if cross_platform["microphone"]:
383 entitlements["com.apple.security.device.microphone"] = True
384 info["NSMicrophoneUsageDescription"] = cross_platform["microphone"]
385
386 if cross_platform["background_location"]:
387 info["NSLocationUsageDescription"] = cross_platform["background_location"]
388 entitlements["com.apple.security.personal-information.location"] = True
389 elif cross_platform["fine_location"]:
390 info["NSLocationUsageDescription"] = cross_platform["fine_location"]
391 entitlements["com.apple.security.personal-information.location"] = True
392 elif cross_platform["coarse_location"]:
393 info["NSLocationUsageDescription"] = cross_platform["coarse_location"]
394 entitlements["com.apple.security.personal-information.location"] = True
395
396 if cross_platform["photo_library"]:
397 info["NSPhotoLibraryUsageDescription"] = cross_platform["photo_library"]
398 entitlements["com.apple.security.personal-information.photo_library"] = True
399
400 # Override any info and entitlement definitions
401 # with the platform-specific definitions
402 info.update(getattr(app, "info", {}))
403 entitlements.update(getattr(app, "entitlement", {}))
404
405 return {
406 "info": info,
407 "entitlements": entitlements,
408 }
409
410
411 class macOSRunMixin:
412 def run_app(
413 self,
414 app: AppConfig,
415 passthrough: list[str],
416 **kwargs,
417 ):
418 """Start the application.
419
420 :param app: The config object for the app
421 :param passthrough: The list of arguments to pass to the app
422 """
423 # Console apps must operate in non-streaming mode so that console input can
424 # be handled correctly. However, if we're in test mode, we *must* stream so
425 # that we can see the test exit sentinel.
426 if app.console_app:
427 self.run_console_app(
428 app,
429 passthrough=passthrough,
430 **kwargs,
431 )
432 else:
433 self.run_gui_app(
434 app,
435 passthrough=passthrough,
436 **kwargs,
437 )
438
439 def run_console_app(
440 self,
441 app: AppConfig,
442 passthrough: list[str],
443 **kwargs,
444 ):
445 """Start the console application.
446
447 :param app: The config object for the app
448 :param passthrough: The list of arguments to pass to the app
449 """
450 sub_kwargs = self._prepare_app_kwargs(app=app)
451 cmdline = [self.binary_path(app) / f"Contents/MacOS/{app.formal_name}"]
452 cmdline.extend(passthrough)
453
454 if app.test_mode:
455 # Stream the app's output for testing.
456 # When a console app runs normally, its stdout should be connected
457 # directly to the terminal to properly display the app. When its test
458 # suite is running, though, Briefcase should stream the output to
459 # capture the testing outcome.
460 app_popen = self.tools.subprocess.Popen(
461 cmdline,
462 cwd=self.tools.home_path,
463 stdout=subprocess.PIPE,
464 stderr=subprocess.STDOUT,
465 bufsize=1,
466 **sub_kwargs,
467 )
468 self._stream_app_logs(app, popen=app_popen)
469
470 else:
471 try:
472 # Start the app directly
473 self.console.info("=" * 75)
474 self.tools.subprocess.run(
475 cmdline,
476 cwd=self.tools.home_path,
477 check=True,
478 stream_output=False,
479 **sub_kwargs,
480 )
481 except subprocess.CalledProcessError:
482 # The command line app *could* return an error code, which is legal.
483 # Ignore any subprocess error here.
484 pass
485
486 def run_gui_app(
487 self,
488 app: AppConfig,
489 passthrough: list[str],
490 **kwargs,
491 ):
492 """Start the GUI application.
493
494 :param app: The config object for the app
495 :param passthrough: The list of arguments to pass to the app
496 """
497 # Start log stream for the app.
498 # Streaming the system log is... a mess. The system log contains a
499 # *lot* of noise from other processes; even if you filter by
500 # process, there's a lot of macOS-generated noise. It's very
501 # difficult to extract just the "user generated" stdout/err log
502 # messages.
503 #
504 # The following sets up a log stream filter that looks for:
505 # 1. a log sender that matches that app binary; or,
506 # 2. a log sender of libffi, and a process that matches the app binary.
507 # Case (1) works for pre-Python 3.9 static linked binaries.
508 # Case (2) works for Python 3.9+ dynamic linked binaries.
509 # It's not enough to filter on *just* the processImagePath,
510 # as the process will generate lots of system-level messages.
511 # We can't filter on *just* the senderImagePath, because other
512 # apps will generate log messages that would be caught by the filter.
513 sender = os.fsdecode(self.binary_path(app) / "Contents/MacOS" / app.formal_name)
514 log_popen = self.tools.subprocess.Popen(
515 [
516 "log",
517 "stream",
518 "--style",
519 "compact",
520 "--predicate",
521 (
522 f'senderImagePath=="{sender}"'
523 f' OR (processImagePath=="{sender}"'
524 ' AND senderImagePath=="/usr/lib/libffi.dylib")'
525 ),
526 ],
527 stdout=subprocess.PIPE,
528 stderr=subprocess.STDOUT,
529 bufsize=1,
530 )
531
532 # Wait for the log stream start up
533 time.sleep(0.25)
534
535 app_pid = None
536 try:
537 # Set up the log stream
538 sub_kwargs = self._prepare_app_kwargs(app=app)
539
540 # Start the app in a way that lets us stream the logs
541 self.tools.subprocess.run(
542 # Force a new app to be launched
543 ["open", "-n", self.binary_path(app)]
544 + (["--args", *passthrough] if passthrough else []),
545 cwd=self.tools.home_path,
546 check=True,
547 **sub_kwargs,
548 )
549
550 # Find the App process ID so log streaming can exit when the app exits
551 app_pid = get_process_id_by_command(
552 command=str(self.binary_path(app)),
553 console=self.console,
554 )
555
556 if app_pid is None:
557 raise BriefcaseCommandError(
558 f"Unable to find process for app {app.app_name} "
559 "to start log streaming."
560 )
561
562 # Stream the app logs.
563 self._stream_app_logs(
564 app,
565 popen=log_popen,
566 clean_filter=macOS_log_clean_filter,
567 clean_output=True,
568 stop_func=lambda: is_process_dead(app_pid),
569 log_stream=True,
570 )
571 except subprocess.CalledProcessError as e:
572 raise BriefcaseCommandError(f"Unable to start app {app.app_name}.") from e
573 finally:
574 # Ensure the App also terminates when exiting. The ordering here is a little
575 # odd; the if could/should be outside the context manager, but coverage has
576 # issues with that arrangement on some Python versions (3.10, 3.14)
577 with suppress(ProcessLookupError):
578 if app_pid:
579 self.tools.os.kill(app_pid, SIGTERM)
580
581
582 class macOSSigningMixin:
583 def __init__(self, *args, **kwargs):
584 super().__init__(*args, **kwargs)
585
586 # External service APIs.
587 # These are abstracted to enable testing without patching.
588 self.get_identities = get_identities
589
590 def entitlements_path(self, app: AppConfig): # pragma: no-cover-if-is-windows
591 return self.bundle_path(app) / self.path_index(app, "entitlements_path")
592
593 def select_identity(
594 self,
595 identity: str | None = None,
596 app_identity: SigningIdentity | None = None,
597 allow_adhoc: bool = True,
598 ) -> SigningIdentity:
599 """Get the codesigning identity to use.
600
601 This can be either an application codesigning identity, or an installer
602 identity. An installer identity must be from the same Team ID as the application
603 identity.
604
605 :param identity: A pre-specified identity (either the 40-digit hex checksum, or
606 the string name of the identity). If provided, it will be validated against
607 the list of available identities to confirm that it is a valid codesigning
608 identity.
609 :param app_identity: The application signing identity to match when producing an
610 installer identity. Only non-app signing identities that match the team ID
611 for the ``app_identity`` will be presented as options. Omit this value to
612 select an app signing identity.
613 :param allow_adhoc: Should the adhoc identities be allowed?
614 :returns: The final identity to use
615 """
616 # If the adhoc identity is allowed, add it first so it appears first in the list
617 # of options.
618 identities = {}
619 if allow_adhoc:
620 identities["-"] = ADHOC_IDENTITY_NAME
621
622 # Obtain the valid codesigning identities. These are the identities that could
623 # be used for app signing.
624 identities.update(self.get_identities(self.tools, "codesigning"))
625
626 if app_identity:
627 ident_type = "installer"
628 ident_option = "--installer-identity"
629 # There's no way to explicitly request a list of installer identities. As a
630 # workaround, get the full, unfiltered list of all signing identities; then
631 # remove any identity that:
632 # 1. From a different team to the provided app identity; or
633 # 2. Appears on the list of app signing identities.
634 app_identities = identities
635 identities = {
636 key: name
637 for key, name in self.get_identities(self.tools).items()
638 if SigningIdentity.team_id_from_name(name) == app_identity.team_id
639 and key not in app_identities
640 }
641
642 if not identities:
643 raise BriefcaseCommandError(
644 "No installer signing identities for team "
645 f"{app_identity.team_id} could be found."
646 )
647 else:
648 ident_type = "application"
649 ident_option = "--identity"
650
651 if identity:
652 try:
653 # Try to look up the identity as a hex checksum
654 identity_name = identities[identity]
655 return SigningIdentity(id=identity, name=identity_name)
656 except KeyError as e:
657 # Try to look up the identity as readable name
658 try:
659 reverse_lookup = {name: ident for ident, name in identities.items()}
660 identity_id = reverse_lookup[identity]
661 return SigningIdentity(id=identity_id, name=identity)
662 except KeyError:
663 # Not found as an ID or name
664 raise BriefcaseCommandError(
665 f"Invalid {ident_type} signing identity {identity}"
666 ) from e
667
668 identity = self.console.selection_question(
669 intro=f"Select {ident_type} signing identity to use:",
670 description=f"{ident_type.title()} Signing Identity",
671 options=identities,
672 )
673 identity_name = identities[identity]
674 if identity == "-":
675 self.console.info(f"""
676 In future, you could specify this signing identity by using:
677
678 $ briefcase {self.command} macOS {self.output_format} --adhoc-sign ...
679
680 """)
681 else:
682 self.console.info(f"""
683 In future, you could specify this signing identity by using:
684
685 $ briefcase {self.command} macOS {self.output_format} {ident_option} {identity} ...
686
687 or
688
689 $ briefcase {self.command} macOS {self.output_format} {ident_option} "{identity_name}" ...
690
691 """) # noqa: E501
692
693 return SigningIdentity(id=identity, name=identity_name)
694
695 def sign_file(
696 self,
697 path: Path,
698 identity: SigningIdentity,
699 entitlements: Path | None = None,
700 ):
701 """Code sign a file.
702
703 :param path: The path to the file to sign.
704 :param identity: The code signing identity to use.
705 :param entitlements: The path to the entitlements file to use.
706 """
707 options = "runtime" if not identity.is_adhoc else None
708 process_command = ["codesign", path, "--sign", identity.id, "--force"]
709
710 if entitlements:
711 process_command.append("--entitlements")
712 process_command.append(entitlements)
713 if options:
714 process_command.append("--options")
715 process_command.append(options)
716
717 self.console.verbose(f"Signing {Path(path).relative_to(self.base_path)}")
718
719 try:
720 self.tools.subprocess.run(
721 process_command,
722 stderr=subprocess.PIPE,
723 check=True,
724 )
725 except subprocess.CalledProcessError as e:
726 errors = e.stderr
727 if any(
728 msg in errors
729 for msg in [
730 # File has a signature matching the Mach-O magic,
731 # but isn't actually a Mach-O binary
732 "unsupported format for signature",
733 # A folder named ``.framework`, but not actually a macOS Framework`
734 "bundle format unrecognized, invalid, or unsuitable",
735 ]
736 ):
737 # We should not be signing this in the first place
738 self.console.verbose(
739 f"... {Path(path).relative_to(self.base_path)} "
740 "does not require a signature"
741 )
742 return
743 else:
744 self.tools.subprocess.output_error(e)
745 raise BriefcaseCommandError(f"Unable to code sign {path}.") from e
746
747 def sign_app(
748 self,
749 app: AppConfig,
750 identity: SigningIdentity,
751 ): # pragma: no-cover-if-is-windows
752 """Sign an entire app with a specific identity.
753
754 :param app: The app to sign
755 :param identity: The signing identity to use
756 """
757 bundle_path = self.package_path(app)
758 resources_path = bundle_path / "Contents/Resources"
759 frameworks_path = bundle_path / "Contents/Frameworks"
760
761 sign_targets = []
762
763 for folder in (resources_path, frameworks_path):
764 # Sign all Mach-O executable objects
765 sign_targets.extend(
766 path
767 for path in folder.rglob("*")
768 if not path.is_dir()
769 and not path.is_symlink()
770 and is_mach_o_binary(path)
771 )
772
773 # Sign all embedded frameworks
774 sign_targets.extend(folder.rglob("*.framework"))
775
776 # Sign all embedded app objects
777 sign_targets.extend(folder.rglob("*.app"))
778
779 # Sign the bundle path itself
780 sign_targets.append(bundle_path)
781
782 # Run signing through a ThreadPoolExecutor so that they run in parallel. We need
783 # to ensure that objects are signed from the inside out (i.e., a folder must be
784 # signed *after* all it's contents has been signed; files in a folder must be
785 # signed *after* all subfolders in that same folder); and an app that uses a
786 # library must be signed *after* all the libraries it uses. See
787 # https://developer.apple.com/documentation/xcode/creating-distribution-signed-code-for-the-mac#Determine-the-signing-order
788 # for details.
789 #
790 # To do this, we utilize grouping on a sorted list, and rely on the fact that a
791 # new group is created whenever the grouping key changes. The sorting process
792 # guarantees depth-first ordering; the grouping is applied over the sorted
793 # content, ensuring that that folders are signed before files.
794 #
795 # This approach isn't perfect. It will fail if there's an embedded app that uses
796 # a library in a different framework, and the app is lexically sorted before the
797 # library (e.g. if app_packages/foobar/Alpha.framework/Helpers/My App.app
798 # depends on app_packages/footbar/Beta.framework/libbeta). However, if you're
799 # embedding apps in frameworks in Python libraries that are installed by pip,
800 # you're already making poor life choices; this approach is enough to satisfy
801 # the one use of app-in-framework embedding that we're aware of (PySide).
802 progress_bar = self.console.progress_bar()
803 task_id = progress_bar.add_task("Signing App", total=len(sign_targets))
804 with progress_bar:
805 for group in self.tools.file.sorted_depth_first_groups(sign_targets):
806 with concurrent.futures.ThreadPoolExecutor(
807 max_workers=1 if self.console.is_deep_debug else None
808 ) as executor:
809 futures = []
810 for path in group:
811 future = executor.submit(
812 self.sign_file,
813 path,
814 entitlements=self.entitlements_path(app),
815 identity=identity,
816 )
817 futures.append(future)
818 for future in concurrent.futures.as_completed(futures):
819 progress_bar.update(task_id, advance=1)
820 if future.exception():
821 raise future.exception()
822
823
824 class macOSPackageMixin(macOSSigningMixin):
825 ADHOC_SIGN_HELP = (
826 "Perform ad-hoc signing on the app. "
827 "The app will only run on this machine; it cannot be redistributed to others"
828 )
829 IDENTITY_HELP = (
830 "The code signing identity to use; either the 40-digit hex "
831 "checksum, or the full name of the identity"
832 )
833
834 @property
835 def packaging_formats(self):
836 return ["zip", "dmg", "pkg"]
837
838 @property
839 def default_packaging_format(self):
840 # The default changes depending on whether the app is a console app or a GUI app
841 return None
842
843 def notarization_path(self, app: AppConfig) -> Path:
844 """The file that is submitted for notarization."""
845 if app.packaging_format == "zip":
846 # Notarization for bare .app's is applied to the binary, not the
847 # distribution artefact, with the distribution artefact being
848 # created after notarization has completed.
849 return self.package_path(app)
850 else:
851 return self.distribution_path(app)
852
853 def distribution_path(self, app: AppConfig) -> Path:
854 """The path to the final distribution artefact."""
855 if app.packaging_format == "zip":
856 return self.dist_path / f"{app.formal_name}-{app.version}.app.zip"
857 elif app.packaging_format == "pkg":
858 return self.dist_path / f"{app.formal_name}-{app.version}.pkg"
859 else:
860 return self.dist_path / f"{app.formal_name}-{app.version}.dmg"
861
862 def add_options(self, parser):
863 super().add_options(parser)
864
865 # --no-sign-installer and --installer-identity are mutually exclusive
866 installer_signing_group = parser.add_mutually_exclusive_group()
867 installer_signing_group.add_argument(
868 "--no-sign-installer",
869 dest="sign_installer",
870 help="Do not sign the installer. Ignored unless using PKG format",
871 action="store_false",
872 )
873 installer_signing_group.add_argument(
874 "--installer-identity",
875 dest="installer_identity",
876 help=(
877 "The code signing identity to use for signing the installer. "
878 "Ignored unless using PKG format"
879 ),
880 required=False,
881 )
882
883 # We use store_const:False rather than store_false so that the
884 # "unspecified" value is None, rather than True, allowing for
885 # a "default behavior" interpretation when `--adhoc-sign` is specified
886 parser.add_argument(
887 "--no-notarize",
888 dest="notarize_app",
889 action="store_const",
890 const=False,
891 help="Disable notarization for the app",
892 )
893 parser.add_argument(
894 "--resume",
895 dest="submission_id",
896 help="The notarization submission ID to resume",
897 required=False,
898 )
899
900 def verify_tools(self):
901 # Require the Xcode command line tools.
902 XcodeCliTools.verify(tools=self.tools)
903
904 # Verify superclass tools *after* xcode. This ensures we get the
905 # git check *after* the xcode check.
906 super().verify_tools()
907
908 def __init__(self, *args, **kwargs):
909 super().__init__(*args, **kwargs)
910
911 # External service APIs.
912 # These are abstracted to enable testing without patching.
913 self.dmgbuild = dmgbuild
914
915 def verify_app(self, app):
916 super().verify_app(app)
917
918 if app.console_app:
919 if app.packaging_format is None:
920 app.packaging_format = "pkg"
921 elif app.packaging_format != "pkg":
922 raise BriefcaseCommandError(
923 "macOS console apps must be distributed in PKG format."
924 )
925 elif app.packaging_format is None:
926 app.packaging_format = "dmg"
927
928 def clean_dist_folder(self, app, **options):
929 """Clean up any existing artefacts in the dist folder.
930
931 If we are resuming a notarization session verify that the artefact exists, but
932 *do not* delete it.
933
934 :param app: The app being packaged.
935 :param submission_id: The notarization submission being resumed.
936 :param options: Any additional arguments passed to the package command.
937 """
938 if options.get("submission_id"):
939 if not self.notarization_path(app).exists():
940 raise BriefcaseCommandError(
941 "Notarization cannot be resumed, as the notarization artefact "
942 "associated with this app "
943 f"({self.notarization_path(app).relative_to(self.base_path)}) "
944 "does not exist."
945 )
946
947 # If the packaging format is zip, the distribution artefact is created
948 # *after* completion of notarization. If there's an existing distribution
949 # artefact, it must be from a previous notarization/stapling attempt.
950 if app.packaging_format == "zip":
951 super().clean_dist_folder(app, **options)
952 else:
953 super().clean_dist_folder(app, **options)
954
955 def ditto_archive(
956 self,
957 app_filename: Path,
958 archive_filename: Path,
959 ): # pragma: no-cover-if-not-macos
960 """Create an archive of an app using ditto.
961
962 Although the archive format is ".zip", we can't use standard Zip tools, as they
963 don't preserve UTF-8 encoding on all resources. Instead, we need to use `ditto`,
964 which is provided as part of macOS developer tooling. See
965 https://forums.developer.apple.com/forums/thread/116831 and
966 https://developer.apple.com/library/archive/technotes/tn2206/_index.html for
967 more details.
968
969 :param app_filename: The filename of the app to archive
970 :param archive_filename: The filename of the archive to produce
971 """
972 try:
973 self.tools.subprocess.run(
974 [
975 "/usr/bin/ditto",
976 "-c",
977 "-k",
978 "--sequesterRsrc",
979 "--keepParent",
980 app_filename,
981 archive_filename,
982 ],
983 check=True,
984 )
985 except subprocess.CalledProcessError as e:
986 raise BriefcaseCommandError(f"Unable to archive {app_filename.name}") from e
987
988 def notarize(
989 self,
990 app: AppConfig,
991 identity: SigningIdentity,
992 installer_identity: SigningIdentity | None = None,
993 ):
994 """Submit a file for notarization, and wait for that notarization to be
995 completed.
996
997 :param app: The app to notarize.
998 :param identity: The code signing used to notarize the app.
999 :param installer_identity: The signing identity to use when signing the
1000 installer. Optional unless the packaging format is ``pkg``.
1001 """
1002 # Determine the arguments that would be needed to reproduce this notarization
1003 if installer_identity:
1004 identity_args = (
1005 f"--identity {identity.id} --installer-identity {installer_identity.id}"
1006 )
1007 notarization_identity = installer_identity
1008 else:
1009 identity_args = f"--identity {identity.id}"
1010 notarization_identity = identity
1011
1012 format_args = f"-p {app.packaging_format}"
1013
1014 # Submit the app for notarization
1015 submission_id = self.submit_notarization(app, identity=notarization_identity)
1016
1017 self.console.warning(f"""
1018 Briefcase will now wait for Apple to approve the notarization request.
1019 This can take some time - in some cases, hours.
1020
1021 If notarization is interrupted, you can resume by running:
1022
1023 briefcase package macOS {self.output_format} {format_args} {identity_args} --resume {submission_id}
1024
1025 """) # noqa: E501
1026
1027 self.finalize_notarization(
1028 app,
1029 identity=notarization_identity,
1030 submission_id=submission_id,
1031 )
1032
1033 def submit_notarization(self, app, identity: SigningIdentity) -> str:
1034 """Submit a file for notarization, returning the ID of the notarizatzion task.
1035
1036 If the file is a .app, it will be archived as a .zip for submission purposes.
1037
1038 :param app: The app to notarize.
1039 :param identity: The code signing identity to use.
1040 :returns: The ID of the notarization task.
1041 """
1042 filename = self.notarization_path(app)
1043 try:
1044 if app.packaging_format == "zip":
1045 self.console.info()
1046 with self.console.wait_bar(
1047 f"Archiving {filename.name} for notarization..."
1048 ):
1049 archive_filename = filename.parent / (filename.name + ".zip")
1050 self.ditto_archive(filename, archive_filename)
1051 else:
1052 archive_filename = filename
1053
1054 submission_id = None
1055 store_credentials = False
1056 while not submission_id:
1057 if store_credentials:
1058 if not self.console.input_enabled:
1059 raise BriefcaseCommandError(f"""
1060 The keychain does not contain credentials for the profile {identity.profile}.
1061 You can store these credentials by invoking:
1062
1063 $ xcrun notarytool store-credentials --team-id {identity.team_id} {identity.profile}
1064
1065 """)
1066
1067 self.console.warning("""
1068 The notarization process uses credentials stored on your system Keychain.
1069 You need to do this once for each signing certificate you use.
1070
1071 The credentials are authenticated and stored using your Apple ID, using
1072 an app-specific Apple ID password. To generate an app-specific Apple ID
1073 password:
1074
1075 1. Sign into https://appleid.apple.com;
1076 2. In the 'Sign-in and Security' section, click 'App-Specific Passwords';
1077 3. Click on the '+' icon. You will need to provide an identifying name
1078 for the password. You can pick any name that makes sense to you - the
1079 name is only there so you can identify passwords. 'Briefcase' would be
1080 one possible name.
1081 4. Record the password somewhere safe.
1082 """)
1083 try:
1084 self.tools.subprocess.run(
1085 [
1086 "xcrun",
1087 "notarytool",
1088 "store-credentials",
1089 "--team-id",
1090 identity.team_id,
1091 identity.profile,
1092 ],
1093 check=True,
1094 stream_output=False, # Command reads from stdin.
1095 )
1096 except subprocess.CalledProcessError as e:
1097 raise BriefcaseCommandError(
1098 "Unable to store credentials for team ID "
1099 f"{identity.team_id}."
1100 ) from e
1101
1102 # Attempt the notarization
1103 try:
1104 self.console.info()
1105 with self.console.wait_bar("Submitting app for notarization..."):
1106 submission = self.tools.subprocess.parse_output(
1107 json_parser,
1108 [
1109 "xcrun",
1110 "notarytool",
1111 "submit",
1112 archive_filename,
1113 "--keychain-profile",
1114 identity.profile,
1115 "--output-format",
1116 "json",
1117 ],
1118 quiet=1,
1119 )
1120 submission_id = submission["id"]
1121 except subprocess.CalledProcessError as e:
1122 # Error when submitting for notarization.
1123 # A return code of 69 (nice) indicates an issue with the
1124 # keychain profile. If store_credentials is already True,
1125 # then we've already tried to store them, so call the attempt
1126 # a fail
1127 if e.returncode == 69 and not store_credentials:
1128 store_credentials = True
1129 else:
1130 self.tools.subprocess.output_error(e)
1131 raise BriefcaseCommandError(
1132 f"Unable to submit {filename.relative_to(self.base_path)} "
1133 "for notarization."
1134 ) from e
1135 finally:
1136 # If we're using .zip packaging, the archive is temporary and isn't used for
1137 # distribution, so we can clean up.
1138 if archive_filename != filename:
1139 self.tools.os.unlink(archive_filename)
1140
1141 return submission_id
1142
1143 def validate_submission_id(
1144 self,
1145 app: AppConfig,
1146 identity: SigningIdentity,
1147 submission_id: str,
1148 ):
1149 with self.console.wait_bar("Determining validity of submission ID..."):
1150 try:
1151 response = self.tools.subprocess.parse_output(
1152 json_parser,
1153 [
1154 "xcrun",
1155 "notarytool",
1156 "history",
1157 "--keychain-profile",
1158 identity.profile,
1159 "--output-format",
1160 "json",
1161 ],
1162 )
1163
1164 id_matches = [
1165 submission
1166 for submission in response["history"]
1167 if submission["id"] == submission_id
1168 ]
1169
1170 expected_filename = id_matches[0]["name"]
1171 # .app files are zipped for notarization, but the app itself is
1172 # notarized; strip the .zip suffix for filename matching purposes.
1173 expected_filename = expected_filename.removesuffix(".zip")
1174
1175 if expected_filename != self.notarization_path(app).name:
1176 raise BriefcaseCommandError(
1177 f"{submission_id} is not a submission ID for this project. "
1178 f"It notarizes a file named {expected_filename}"
1179 )
1180 except IndexError:
1181 raise BriefcaseCommandError(
1182 f"{submission_id} is not a known submission ID for this identity."
1183 ) from None
1184 except subprocess.CalledProcessError as e:
1185 raise BriefcaseCommandError(
1186 "Unable to invoke notarytool to determine validity of "
1187 "submission ID.\n"
1188 "Are you sure this is the identity that was used to notarize "
1189 "the app?"
1190 ) from e
1191
1192 def finalize_notarization(
1193 self,
1194 app: AppConfig,
1195 identity: SigningIdentity,
1196 submission_id: str,
1197 ):
1198 """Finalize a notarization task.
1199
1200 Polls to check the current notarization status; once notarization approval is
1201 received, the notarization is stapled onto the distribution artefact.
1202
1203 :param app: The app to notarize.
1204 :param identity: The code signing identity to use.
1205 :param submission_id: The submission ID of the notarization task to finalize.
1206 """
1207 try:
1208 with self.console.wait_bar("Waiting for notarization acceptance..."):
1209 accepted = False
1210 while not accepted:
1211 try:
1212 response = self.tools.subprocess.parse_output(
1213 json_parser,
1214 [
1215 "xcrun",
1216 "notarytool",
1217 "log",
1218 "--keychain-profile",
1219 identity.profile,
1220 submission_id,
1221 ],
1222 quiet=1,
1223 )
1224
1225 if response["status"] == "Accepted":
1226 accepted = True
1227 elif response["status"] == "Invalid":
1228 summary = response.get(
1229 "statusSummary", "No details provided"
1230 )
1231 raise BriefcaseCommandError(
1232 f"Notarization was rejected: {summary}\n"
1233 + "\n".join(
1234 f"""
1235 * ({issue.get("severity", "?")}) {issue.get("path")} [{issue.get("architecture", "unknown architecture")}]
1236 {issue.get("message")}
1237 {issue.get("docUrl", "(No additional help available)")}""" # noqa: E501
1238 for issue in response.get("issues", [])
1239 )
1240 )
1241 else:
1242 raise BriefcaseCommandError(
1243 f"Unexpected notarization status: {response['status']}"
1244 )
1245 except subprocess.CalledProcessError as e:
1246 if e.returncode == 69:
1247 # Error code 69 (nice) indicates the server can't give a log
1248 # response for the provided submission ID. We've already
1249 # validated that it's a valid submission ID, so that means
1250 # notarization isn't complete yet. Try again in 10 seconds.
1251 time.sleep(10)
1252 else:
1253 self.tools.subprocess.output_error(e)
1254 raise BriefcaseCommandError(
1255 "Unknown problem retrieving notarization status."
1256 ) from e
1257
1258 except KeyboardInterrupt:
1259 raise NotarizationInterrupted("Notarization interrupted by user.") from None
1260 else:
1261 filename = self.notarization_path(app)
1262 try:
1263 self.console.info()
1264 self.console.info(
1265 "Stapling notarization onto "
1266 f"{filename.relative_to(self.base_path)}..."
1267 )
1268 self.tools.subprocess.run(
1269 ["xcrun", "stapler", "staple", filename],
1270 check=True,
1271 )
1272 except subprocess.CalledProcessError as e:
1273 raise BriefcaseCommandError(
1274 "Unable to staple notarization onto "
1275 f"{filename.relative_to(self.base_path)}"
1276 ) from e
1277
1278 # Notarization on a zip package is performed on the bare app, so we can't
1279 # complete packaging until notarization has completed.
1280 if app.packaging_format == "zip":
1281 self.finalize_package_zip(app)
1282
1283 def package_app(
1284 self,
1285 app: AppConfig,
1286 notarize_app=None,
1287 identity=None,
1288 adhoc_sign=False,
1289 sign_installer=True,
1290 installer_identity=None,
1291 submission_id=None,
1292 **kwargs,
1293 ):
1294 """Package an app bundle.
1295
1296 :param app: The application to package
1297 :param notarize_app: Should the app be notarized? Default: ``True`` if the app
1298 has been signed with a real identity; ``False`` if the app is unsigned, or
1299 an ad-hoc signing identity has been used.
1300 :param identity: The signing identity to use to sign the app. This can be either
1301 the 40-digit hex checksum, or the string name of the identity. If
1302 unspecified, the user will be prompted for an app signing identity. Ignored
1303 if ``adhoc_sign`` is ``True``.
1304 :param adhoc_sign: If ``True``, code will be signed with ad-hoc identity of "-",
1305 and the resulting app will not be re-distributable.
1306 :param sign_installer: Should the installer be signed? Ignored unless the
1307 packaging format is ``pkg``.
1308 :param installer_identity: The signing identity to use when signing the
1309 installer. Ignored unless the packaging format is ``pkg``.
1310 :param submission_id: The submission ID of the notarization task to resume.
1311 """
1312 # Confirm the project isn't currently on an iCloud synced drive.
1313 self.verify_not_on_icloud(app)
1314
1315 if submission_id:
1316 # If we're resuming notarization, we *can't* use an adhoc identity,
1317 # so don't allow it to be selected.
1318 identity = self.select_identity(identity=identity, allow_adhoc=False)
1319
1320 if app.packaging_format == "pkg":
1321 notarization_identity = self.select_identity(
1322 identity=installer_identity,
1323 app_identity=identity,
1324 )
1325 else:
1326 notarization_identity = identity
1327
1328 self.console.info(
1329 f"Resuming notarization for submission {submission_id}",
1330 prefix=app.app_name,
1331 )
1332
1333 self.console.info()
1334 self.validate_submission_id(
1335 app,
1336 identity=notarization_identity,
1337 submission_id=submission_id,
1338 )
1339
1340 self.console.info()
1341 self.finalize_notarization(
1342 app,
1343 identity=notarization_identity,
1344 submission_id=submission_id,
1345 )
1346 return
1347
1348 # It's a normal packaging pass.
1349 self.console.info("Signing app...", prefix=app.app_name)
1350 if adhoc_sign:
1351 identity = SigningIdentity()
1352 else:
1353 identity = self.select_identity(identity=identity)
1354
1355 if identity.is_adhoc:
1356 if notarize_app:
1357 raise BriefcaseCommandError(
1358 "Can't notarize an app with an ad-hoc signing identity"
1359 )
1360 self.console.warning("""
1361 *************************************************************************
1362 ** WARNING: Signing with an ad-hoc identity **
1363 *************************************************************************
1364
1365 This app is being signed with an ad-hoc identity. The resulting
1366 app will run on this computer, but will not run on anyone else's
1367 computer.
1368
1369 To generate an app that can be distributed to others, you must
1370 obtain an application distribution certificate from Apple, and
1371 select the developer identity associated with that certificate
1372 when running 'briefcase package'.
1373
1374 *************************************************************************
1375
1376 """)
1377 self.console.info("Signing app with ad-hoc identity...")
1378 else:
1379 # If we're signing, and notarization isn't explicitly disabled,
1380 # notarize by default.
1381 if notarize_app is None:
1382 notarize_app = True
1383
1384 self.console.info(f"Signing app with identity {identity.name}...")
1385
1386 self.sign_app(app=app, identity=identity)
1387
1388 if app.packaging_format == "zip":
1389 self.package_zip(
1390 app,
1391 notarize_app=notarize_app,
1392 identity=identity,
1393 )
1394
1395 elif app.packaging_format == "pkg":
1396 # If the user has indicated they want to sign the installer (the default),
1397 # and the signing identity for the app *isn't* the adhoc identity, select an
1398 # identity for signing the installer.
1399 if sign_installer and not identity.is_adhoc:
1400 installer_identity = self.select_identity(
1401 identity=installer_identity,
1402 app_identity=identity,
1403 )
1404 else:
1405 installer_identity = None
1406
1407 self.package_pkg(
1408 app,
1409 notarize_app=notarize_app,
1410 identity=identity,
1411 installer_identity=installer_identity,
1412 )
1413
1414 else: # Default packaging format is DMG
1415 self.package_dmg(
1416 app,
1417 notarize_app=notarize_app,
1418 identity=identity,
1419 )
1420
1421 def package_zip(
1422 self,
1423 app: AppConfig,
1424 notarize_app: bool,
1425 identity: SigningIdentity,
1426 ):
1427 """Package an .app bundle in a zip file.
1428
1429 If we're notarizing, this doesn't actually create the distribution artefact.
1430 Notarization on a zip package is performed on the bare app, so we can't complete
1431 packaging until notarization has completed. We call ``finalize_package_zip()``
1432 as part of completing zip notarization.
1433 """
1434 if notarize_app:
1435 self.console.info(
1436 f"Notarizing app using team ID {identity.team_id}...",
1437 prefix=app.app_name,
1438 )
1439 self.notarize(app, identity=identity)
1440 else:
1441 self.finalize_package_zip(app)
1442
1443 def finalize_package_zip(self, app: AppConfig):
1444 """Finalize the zip packaging process."""
1445 # Build the final archive for distribution
1446 with self.console.wait_bar(
1447 f"Building final distribution archive for {self.package_path(app).name}..."
1448 ):
1449 self.ditto_archive(self.package_path(app), self.distribution_path(app))
1450
1451 def package_pkg(
1452 self,
1453 app: AppConfig,
1454 notarize_app: bool,
1455 identity: SigningIdentity,
1456 installer_identity: SigningIdentity | None,
1457 ):
1458 """Package the app as an installer."""
1459 dist_path: Path = self.distribution_path(app)
1460
1461 self.console.info("Building PKG...", prefix=app.app_name)
1462
1463 installer_path = self.bundle_path(app) / "installer"
1464
1465 with self.console.wait_bar("Installing license..."):
1466 license_file = self.base_path / "LICENSE"
1467 if license_file.is_file():
1468 (installer_path / "resources").mkdir(exist_ok=True)
1469 self.tools.shutil.copy(
1470 license_file,
1471 installer_path / "resources/LICENSE",
1472 )
1473 else:
1474 raise BriefcaseCommandError("""\
1475 Your project does not contain a LICENSE file.
1476
1477 Create a file named `LICENSE` in the same directory as your `pyproject.toml`
1478 with your app's licensing terms.
1479 """)
1480
1481 # pkgbuild's default behavior is to make "relocatable" installs, which means
1482 # that if you've ever run the app, the installer will default to updating *that*
1483 # version, rather than putting it in the location that the installer specifies.
1484 # This means if you've ever used `briefcase run`, that will be the install
1485 # location of the "installed" app. To work around this, you have to provide a
1486 # plist file - but that requires providing a "root" folder that *only* contains
1487 # the products you want to install. So - we need to copy the built app to a
1488 # "clean" packaging location.
1489 with self.console.wait_bar("Copying app into products folder..."):
1490 installed_app_path = installer_path / "root" / self.package_path(app).name
1491 if installed_app_path.exists():
1492 self.tools.shutil.rmtree(installed_app_path)
1493 self.tools.shutil.copytree(
1494 self.package_path(app),
1495 installed_app_path,
1496 # Ensure that symlinks are preserved in the duplication.
1497 symlinks=True,
1498 )
1499
1500 components_plist_path = self.bundle_path(app) / "installer/components.plist"
1501
1502 with (
1503 self.console.wait_bar("Writing component manifest..."),
1504 components_plist_path.open("wb") as components_plist,
1505 ):
1506 plistlib.dump(
1507 [
1508 {
1509 "BundleHasStrictIdentifier": True,
1510 "BundleIsRelocatable": False,
1511 "BundleIsVersionChecked": True,
1512 "BundleOverwriteAction": "upgrade",
1513 "RootRelativeBundlePath": self.package_path(app).name,
1514 }
1515 ],
1516 components_plist,
1517 )
1518
1519 # Console apps are installed in /Library/Formal Name, and include the
1520 # post-install scripts. Normal apps are installed in /Applications, and don't
1521 # include the scripts.
1522 if app.console_app:
1523 install_args = [
1524 "--install-location",
1525 f"/Library/{app.formal_name}",
1526 "--scripts",
1527 installer_path / "scripts",
1528 ]
1529 else:
1530 install_args = ["--install-location", "/Applications"]
1531
1532 with self.console.wait_bar("Building app package..."):
1533 installer_packages_path = installer_path / "packages"
1534 if installer_packages_path.exists():
1535 self.tools.shutil.rmtree(installer_packages_path)
1536 installer_packages_path.mkdir()
1537
1538 self.tools.subprocess.run(
1539 [
1540 "pkgbuild",
1541 "--root",
1542 installer_path / "root",
1543 "--component-plist",
1544 components_plist_path,
1545 *install_args,
1546 installer_packages_path / f"{app.app_name}.pkg",
1547 ],
1548 check=True,
1549 )
1550
1551 # Build package
1552 with self.console.wait_bar(f"Building {dist_path.name}..."):
1553 if installer_identity:
1554 signing_options = ["--sign", installer_identity.id]
1555 else:
1556 signing_options = []
1557
1558 self.tools.subprocess.run(
1559 [
1560 "productbuild",
1561 "--distribution",
1562 installer_path / "Distribution.xml",
1563 "--package-path",
1564 installer_path / "packages",
1565 "--resources",
1566 installer_path / "resources",
1567 *signing_options,
1568 dist_path,
1569 ],
1570 check=True,
1571 )
1572
1573 if notarize_app:
1574 self.console.info(
1575 f"Notarizing PKG with team ID {installer_identity.team_id}...",
1576 prefix=app.app_name,
1577 )
1578 self.notarize(
1579 app,
1580 identity=identity,
1581 installer_identity=installer_identity,
1582 )
1583
1584 def package_dmg(
1585 self,
1586 app: AppConfig,
1587 notarize_app: bool,
1588 identity: SigningIdentity,
1589 ):
1590 """Package an app as a DMG installer."""
1591 dist_path: Path = self.distribution_path(app)
1592 self.console.info("Building DMG...", prefix=app.app_name)
1593
1594 with self.console.wait_bar(f"Building {dist_path.name}..."):
1595 dmg_settings = {
1596 "files": [os.fsdecode(self.package_path(app))],
1597 "symlinks": {"Applications": "/Applications"},
1598 "icon_locations": {
1599 self.package_path(app).name: (75, 75),
1600 "Applications": (225, 75),
1601 },
1602 "window_rect": ((600, 600), (350, 150)),
1603 "icon_size": 64,
1604 "text_size": 12,
1605 }
1606
1607 try:
1608 icon_filename = self.base_path / f"{app.installer_icon}.icns"
1609 if not icon_filename.exists():
1610 self.console.warning(
1611 f"Can't find {app.installer_icon}.icns "
1612 "to use as DMG installer icon"
1613 )
1614 raise AttributeError()
1615 except AttributeError:
1616 # No installer icon specified. Fall back to the app icon
1617 if app.icon:
1618 icon_filename = self.base_path / f"{app.icon}.icns"
1619 if not icon_filename.exists():
1620 self.console.warning(
1621 f"Can't find {app.icon}.icns "
1622 "to use as fallback DMG installer icon"
1623 )
1624 icon_filename = None
1625 else:
1626 # No app icon specified either
1627 icon_filename = None
1628
1629 if icon_filename:
1630 dmg_settings["icon"] = os.fsdecode(icon_filename)
1631
1632 try:
1633 image_filename = self.base_path / f"{app.installer_background}.png"
1634 if image_filename.exists():
1635 dmg_settings["background"] = os.fsdecode(image_filename)
1636 else:
1637 self.console.warning(
1638 f"Can't find {app.installer_background}.png "
1639 "to use as DMG background"
1640 )
1641 except AttributeError:
1642 # No installer background image provided
1643 pass
1644
1645 self.dmgbuild.build_dmg(
1646 filename=os.fsdecode(dist_path),
1647 volume_name=f"{app.formal_name} {app.version}",
1648 settings=dmg_settings,
1649 )
1650
1651 self.sign_file(dist_path, identity=identity)
1652
1653 if notarize_app:
1654 self.console.info(
1655 f"Notarizing DMG with team ID {identity.team_id}...",
1656 prefix=app.app_name,
1657 )
1658 self.notarize(app, identity=identity)