Debian Codegraph @

src/briefcase/platforms/macOS/utils.py

raw
1 from __future__ import annotations
2
3 import concurrent
4 import email
5 import hashlib
6 import os
7 import pathlib
8 import plistlib
9 import subprocess
10 from pathlib import Path
11
12 from briefcase.exceptions import BriefcaseCommandError
13
14 CORETYPES_PATH = "/System/Library/CoreServices/CoreTypes.bundle/Contents/Info.plist"
15
16
17 def is_mach_o_binary(path: Path): # pragma: no-cover-if-is-windows
18 """Determine if the file at the given path is a Mach-O binary.
19
20 :param path: The path to check
21 :returns: True if the file at the given location is a Mach-O binary.
22 """
23 # A binary is any file that is executable, or has a suffix from a known list
24 if os.access(path, os.X_OK) or path.suffix.lower() in {".dylib", ".o", ".so", ""}:
25 # File is a binary; read the file magic to determine if it's Mach-O.
26 with path.open("rb") as f:
27 magic = f.read(4)
28 return magic in (
29 b"\xca\xfe\xba\xbe",
30 b"\xcf\xfa\xed\xfe",
31 b"\xce\xfa\xed\xfe",
32 b"\xbe\xba\xfe\xca",
33 b"\xfe\xed\xfa\xcf",
34 b"\xfe\xed\xfa\xce",
35 )
36 else:
37 # Not a binary
38 return False
39
40
41 def sha256_file_digest(path: Path) -> str:
42 """Compute a sha256 checksum digest of a file.
43
44 :param path: The file to digest.
45 :returns: A sha256 hex digest for the file.
46 """
47 with path.open("rb") as f:
48 file_hash = hashlib.sha256()
49 while chunk := f.read(8192):
50 file_hash.update(chunk)
51
52 return file_hash.hexdigest()
53
54
55 class AppPackagesMergeMixin:
56 # A mixin containing the utilities to merge independent platform-specific
57 # app_packages folders into a single "fat" app_packages folder.
58 # This is currently only used by macOS, but it *could* be required on iOS
59 # if they ever re-introduce multiple on-device architectures.
60
61 def find_binary_packages(
62 self,
63 install_path: Path,
64 universal_suffix: str | None = None,
65 other_suffix: str | None = None,
66 ) -> list[tuple[str, str]]:
67 """Find the packages that have been installed that have binary components.
68
69 :param install_path: The path into which packages have been installed.
70 :param universal_suffix: The tag suffix that indicates a universal wheel.
71 :param other_suffix: The tag suffix for the *other* architecture. Presence of
72 this architecture implies a universal wheel, even if it isn't tagged as
73 such.
74 :returns: A list of (package name, version) tuples, describing the packages that
75 are in the install path that are non-universal and non-pure.
76 """
77 binary_packages = []
78 for distinfo in install_path.glob("*.dist-info"):
79 # Read the WHEEL file in the dist-info folder.
80 # Use this to determine if the wheel is "pure", and the tag
81 # for the wheel.
82 with (distinfo / "WHEEL").open("r", encoding="utf-8") as f:
83 wheel_data = email.message_from_string(f.read())
84 is_purelib = wheel_data.get("Root-Is-Purelib", "false") == "true"
85 tags = wheel_data.get_all("Tag")
86
87 # If the wheel is pure, it's not a binary package
88 if is_purelib:
89 continue
90
91 # If the tag ends with the universal tag, the binary package can be used on
92 # all targets and doesn't need additional processing.
93 if universal_suffix and any(tag.endswith(universal_suffix) for tag in tags):
94 continue
95
96 # If the wheel is tagged with the *other* architecture, it's a universal
97 # wheel even though it isn't tagged as such
98 if other_suffix and any(tag.endswith(other_suffix) for tag in tags):
99 continue
100
101 # The wheel is a single platform binary wheel.
102 # Read the package metadata to determine what needs to be installed.
103 with (distinfo / "METADATA").open("r", encoding="utf-8") as f:
104 metadata = email.message_from_string(f.read())
105 binary_packages.append((metadata["Name"], metadata["Version"]))
106
107 return binary_packages
108
109 def ensure_thin_binary(self, path: Path, arch: str):
110 """Ensure that a binary is thin, targeting a given architecture.
111
112 If the library is already thin, it is left as-is.
113
114 :param path: The library file to process.
115 :param arch: The architecture that should be preserved.
116 """
117 try:
118 output = self.tools.subprocess.check_output(
119 ["lipo", "-info", path],
120 )
121 except subprocess.CalledProcessError as e:
122 raise BriefcaseCommandError(
123 f"Unable to inspect architectures in {path}"
124 ) from e
125 else:
126 if output.startswith("Non-fat file: "):
127 self.console.verbose(f"{path} is already thin.")
128 elif output.startswith("Architectures in the fat file: "):
129 architectures = set(output.strip().split(":")[-1].strip().split(" "))
130 if arch in architectures:
131 self.console.verbose(f"Thinning {path}")
132 try:
133 thin_lib_path = path.parent / f"{path.name}.{arch}"
134 self.tools.subprocess.run(
135 [
136 "lipo",
137 "-thin",
138 arch,
139 "-output",
140 thin_lib_path,
141 path,
142 ],
143 check=True,
144 )
145 except subprocess.CalledProcessError as e:
146 raise BriefcaseCommandError(
147 f"Unable to create thin binary from {path}"
148 ) from e
149 else:
150 # Having extracted the single architecture into a temporary
151 # file, replace the original with the thin version.
152 self.tools.shutil.move(thin_lib_path, path)
153 else:
154 raise BriefcaseCommandError(
155 f"{path} does not contain a {arch} slice."
156 )
157 else:
158 raise BriefcaseCommandError(
159 f"Unable to determine architectures in {path}"
160 )
161
162 def lipo_dylib(self, relative_path: Path, target_path: Path, sources: list[Path]):
163 """Create a fat library by invoking lipo on multiple source libraries.
164
165 :param relative_path: The path fragment for the dylib, relative to the root
166 :param target_path: The root location where the fat library will be written
167 :param sources: A list of root locations providing single platform libraries.
168 """
169 self.console.verbose(f"Creating fat library {relative_path}")
170
171 try:
172 # Ensure the directory where the library will be written exists.
173 (target_path / relative_path).parent.mkdir(exist_ok=True, parents=True)
174
175 # Add all the constructed source paths. If the original binary is universal,
176 # or the binary is only needed on *some* platforms (e.g., libjpeg isn't
177 # included in the x86_64 Pillow wheel), the source won't exist, so only
178 # merge sources that actually exist. lipo allows creating a "fat"
179 # single-platform binary; it's effectively a copy.
180 self.tools.subprocess.run(
181 [
182 "lipo",
183 "-create",
184 "-output",
185 target_path / relative_path,
186 ]
187 + [
188 source_path / relative_path
189 for source_path in sources
190 if (source_path / relative_path).is_file()
191 ],
192 check=True,
193 )
194 except subprocess.CalledProcessError as e:
195 raise BriefcaseCommandError(
196 f"Unable to create fat library for {relative_path}"
197 ) from e
198
199 def thin_app_packages(
200 self,
201 app_packages: Path,
202 arch: str,
203 ):
204 """Ensure that all the dylibs in a given app_packages folder are thin."""
205 dylibs = []
206 for source_path in app_packages.glob("**/*"):
207 if not source_path.is_dir() and is_mach_o_binary(source_path):
208 dylibs.append(source_path)
209
210 # Call lipo on each dylib that was found to ensure it is thin.
211 if dylibs:
212 # Do this in a threadpool to make it run faster.
213 progress_bar = self.console.progress_bar()
214 self.console.info(f"Thinning libraries in {app_packages.name}...")
215 task_id = progress_bar.add_task("Create fat libraries", total=len(dylibs))
216 with (
217 progress_bar,
218 concurrent.futures.ThreadPoolExecutor(
219 max_workers=1 if self.console.is_deep_debug else None
220 ) as executor,
221 ):
222 futures = []
223 for path in dylibs:
224 future = executor.submit(
225 self.ensure_thin_binary,
226 path=path,
227 arch=arch,
228 )
229 futures.append(future)
230 for future in concurrent.futures.as_completed(futures):
231 progress_bar.update(task_id, advance=1)
232 if future.exception():
233 raise future.exception()
234 else:
235 self.console.info("No libraries require thinning.")
236
237 def merge_app_packages(
238 self,
239 target_app_packages: Path,
240 sources: list[Path],
241 ):
242 """Merge the contents of multiple source app packages into a final location.
243
244 :param target_app_packages: The location of the final merged app packages
245 :param sources: A list of app packages folders to be merged.
246 """
247 # Clear any existing app packages folder.
248 if target_app_packages.is_dir():
249 self.tools.shutil.rmtree(target_app_packages)
250 self.tools.os.mkdir(target_app_packages)
251
252 # Copy all the non-library files from the source to the target. If a file exists
253 # in multiple sources, do a checksum, and warn if there is a discrepancy. If
254 # there is a discrepancy, the version from the first source is what will be
255 # used. Don't warn if the file is in a __pycache__ folder; these will always be
256 # different, but they'll be purged later anyway. Don't warn for anything in a
257 # .dist-info folder either; these are going to be different because of platform
258 # difference, but core package metadata should be consistent.
259 dylibs = set()
260 digests = {}
261 for source_app_packages in sources:
262 with self.console.wait_bar(f"Merging {source_app_packages.name}..."):
263 for source_path in source_app_packages.glob("**/*"):
264 relative_path = source_path.relative_to(source_app_packages)
265 target_path = target_app_packages / relative_path
266 if source_path.is_dir():
267 target_path.mkdir(exist_ok=True)
268 else:
269 if is_mach_o_binary(source_path):
270 # Dynamic libraries need to be merged in a second pass
271 dylibs.add(relative_path)
272 elif target_path.exists():
273 # The file already exists. Check for differences; if there
274 # are any differences outside `dist-info` or `__pycache__`
275 # folders, warn the user.
276 digest = sha256_file_digest(source_path)
277 if digests[relative_path] != digest and not (
278 relative_path.parent.name == "__pycache__"
279 or Path(relative_path.parts[0]).suffix == ".dist-info"
280 ):
281 self.console.warning(
282 f"{relative_path} has different content between"
283 " sources; ignoring"
284 f" {source_app_packages.suffix[1:]} version. This"
285 " is usually safe if the file content is not used"
286 " at runtime. See"
287 " https://briefcase.readthedocs.io/en/stable/reference/platforms/macOS/index.html#inconsistent-content-in-non-universal-wheels"
288 " for more details."
289 )
290 else:
291 # The file doesn't exist yet; copy it as is (including
292 # permissions), and store the digest for later comparison
293 self.tools.shutil.copy(source_path, target_path)
294 digests[relative_path] = sha256_file_digest(source_path)
295
296 # Call lipo on each dylib that was found to create the fat version.
297 if dylibs:
298 # Do this in a threadpool to make it run faster.
299 progress_bar = self.console.progress_bar()
300 self.console.info("Merging libraries...")
301 task_id = progress_bar.add_task("Create fat libraries", total=len(dylibs))
302 with (
303 progress_bar,
304 concurrent.futures.ThreadPoolExecutor(
305 max_workers=1 if self.console.is_deep_debug else None
306 ) as executor,
307 ):
308 futures = []
309 for relative_path in dylibs:
310 future = executor.submit(
311 self.lipo_dylib,
312 target_path=target_app_packages,
313 relative_path=relative_path,
314 sources=sources,
315 )
316 futures.append(future)
317 for future in concurrent.futures.as_completed(futures):
318 progress_bar.update(task_id, advance=1)
319 if future.exception():
320 raise future.exception()
321 else:
322 self.console.info("No libraries require merging.")
323
324
325 def is_uti_core_type(uti: str) -> bool: # pragma: no-cover-if-not-macos
326 """Check if a UTI is a built-in Core Type.
327
328 This function checks if a given UTI is a built-in Core Type by reading the
329 system's CoreTypes Info.plist file. If the file is not found, it assumes
330 that the system is not macOS or the file has been moved in recent macOS
331 versions, and returns False.
332
333 Args:
334 uti: The UTI to check.
335
336 Returns:
337 True if the UTI is a built-in Core Type, False otherwise.
338 """
339 try:
340 plist_data = pathlib.Path(CORETYPES_PATH).read_bytes()
341 except FileNotFoundError:
342 # If the file is not found, we assume that the system is not macOS
343 # or the file has been moved in recent macOS versions.
344 # In this case, we return False to indicate that the UTI is not built-in.
345 return False
346 plist = plistlib.loads(plist_data)
347 return uti in {
348 type_declaration["UTTypeIdentifier"]
349 for type_declaration in (
350 plist["UTExportedTypeDeclarations"] + plist["UTImportedTypeDeclarations"]
351 )
352 }
353
354
355 def mime_type_to_uti(mime_type: str) -> str | None: # pragma: no-cover-if-not-macos
356 """Convert a MIME type to a Uniform Type Identifier (UTI).
357
358 This function reads the system's CoreTypes Info.plist file to determine the
359 UTI for a given MIME type.
360
361 Args:
362 mime_type: The MIME type to convert.
363
364 Returns:
365 The UTI for the MIME type, or None if the UTI cannot be determined.
366 """
367 try:
368 plist_data = pathlib.Path(CORETYPES_PATH).read_bytes()
369 except FileNotFoundError:
370 # If the file is not found, we assume that the system is not macOS
371 # or the file has been moved in recent macOS versions.
372 # In this case, we return None to indicate that the UTI cannot be determined.
373 return None
374 plist = plistlib.loads(plist_data)
375 type_declarations = (
376 plist["UTExportedTypeDeclarations"] + plist["UTImportedTypeDeclarations"]
377 )
378 for type_declaration in type_declarations:
379 # We check both the system built-in types (exported) and the known
380 # third-party types (imported) to find the UTI for the given MIME type.
381 # Most type declarations will have a UTTypeTagSpecification dictionary
382 # with a "public.mime-type" key. That can be either a list of MIME types
383 # or a single MIME type. We check if the MIME type is in the list or
384 # matches the single MIME type. If we find a match, we return the UTI
385 # identifier. If we don't find a match, we return None.
386
387 mime_types = type_declaration.get("UTTypeTagSpecification", {}).get(
388 "public.mime-type", []
389 )
390 if isinstance(mime_types, list):
391 # Most MIME types are declared as a list even if they are a
392 # single type. Some types define multiple closely-related MIME
393 # types.
394 if mime_type in mime_types:
395 return type_declaration["UTTypeIdentifier"]
396 else:
397 # some MIME types are declared as a single type
398 if mime_types == mime_type:
399 return type_declaration["UTTypeIdentifier"]
400
401 # If no match is found in the entire list, return None
402 return None