Debian Codegraph @

src/briefcase/integrations/xcode.py

raw
1 from __future__ import annotations
2
3 import enum
4 import re
5 import subprocess
6 from collections.abc import Collection
7 from pathlib import Path
8
9 from briefcase.exceptions import BriefcaseCommandError, CommandOutputParseError
10 from briefcase.integrations.base import Tool, ToolCache
11 from briefcase.integrations.subprocess import json_parser
12
13
14 class DeviceState(enum.Enum):
15 SHUTDOWN = 0
16 BOOTED = 1
17 SHUTTING_DOWN = 10
18 UNKNOWN = 99
19
20
21 class Xcode(Tool):
22 name = "xcode"
23 full_name = "Xcode"
24 supported_host_os: Collection[str] = {"Darwin"}
25
26 @classmethod
27 def verify_install(
28 cls,
29 tools: ToolCache,
30 min_version: tuple[int, int] | tuple[int, int, int] | None = None,
31 **kwargs,
32 ) -> Xcode:
33 """Verify that Xcode and the command line developer tools are installed and
34 ready for use.
35
36 We need Xcode, *and* the Xcode Command Line Tools. A completely clean
37 machine will have neither Xcode *nor* the Command Line Tools. However,
38 it's possible to install Xcode and *not* install the command line tools,
39 and vice versa.
40
41 We also need to ensure that an adequate version of Xcode is available.
42
43 Then, there is a license that needs to be accepted.
44
45 Lastly, we ensure that the iOS simulator is installed.
46
47 :param tools: ToolCache of available tools
48 :param min_version: The minimum allowed version of Xcode, specified as a
49 tuple of integers (e.g., (11, 2, 1)). Default: ``None``, meaning there
50 is no minimum version.
51 """
52 # short circuit since already verified and available
53 if hasattr(tools, "xcode"):
54 return tools.xcode
55
56 cls.ensure_xcode_is_installed(tools=tools, min_version=min_version)
57 XcodeCliTools.verify(tools=tools)
58
59 tools.xcode = Xcode(tools=tools)
60 return tools.xcode
61
62 @classmethod
63 def ensure_xcode_is_installed(
64 cls,
65 tools: ToolCache,
66 min_version: tuple[int, int] | tuple[int, int, int] | None = None,
67 xcode_location: str = "/Applications/Xcode.app",
68 ):
69 """Determine if Xcode is installed; and if so, that it meets minimum version
70 requirements.
71
72 Raises an exception if Xcode isn't installed, or if the version of Xcode
73 that is installed doesn't meet the minimum requirement.
74
75 :param tools: ToolCache of available tools
76 :param min_version: The minimum allowed version of Xcode, specified as a
77 tuple of integers (e.g., (11, 2, 1)). Default: ``None``, meaning there
78 is no minimum version.
79 :param xcode_location: The location where we expect to find an Xcode install.
80 Used for testing; defaults to ``/Applications/Xcode.app``.
81 """
82 # Check for *any* version of Xcode tools. xcode-select returns:
83 # * The path to the currently active Xcode install; or
84 # * error code 2 - No Xcode installation
85 try:
86 tools.subprocess.check_output(["xcode-select", "-p"])
87 except subprocess.CalledProcessError as e:
88 raise BriefcaseCommandError(
89 """\
90 Could not find an Xcode installation.
91
92 To select an existing Xcode installation, run:
93
94 $ sudo xcode-select --switch path/to/Xcode.app
95
96 or install Xcode from the macOS App Store. Once you have installed Xcode,
97 you can re-run Briefcase.
98 """
99 ) from e
100
101 try:
102 # xcodebuild -version returns the version of Xcode that is currently
103 # selected. If the current Xcode is a commandline tools install,
104 # returns an error:
105 # xcode-select: error: tool 'xcodebuild' requires Xcode, but active
106 # developer directory '/Library/Developer/CommandLineTools' is a
107 # command line tools instance
108 output = tools.subprocess.check_output(["xcodebuild", "-version"], quiet=1)
109
110 if min_version is not None:
111 # Look for a line in the output that reads "Xcode X.Y.Z"
112 version_lines = [
113 line for line in output.split("\n") if line.startswith("Xcode ")
114 ]
115 if version_lines:
116 # Split the content after the first space
117 # and split that content on the dots.
118 # At this point, version lines *must* have at least one element,
119 # and each line *must* have a string with at least one space,
120 # so if either array lookup fails, something weird is happening.
121 version_string = version_lines[0].split(" ")[1]
122
123 # Append 0's to fill any gaps caused by
124 # version numbers that don't have a minor version.
125 parsed_version = tuple(int(v) for v in version_string.split("."))
126 version = (*parsed_version, 0, 0)
127
128 if version < min_version:
129 min_version = ".".join(str(v) for v in min_version)
130 version = ".".join(str(v) for v in version)
131 raise BriefcaseCommandError(
132 f"Xcode {min_version} is required; {version} is installed. "
133 f"Please update Xcode."
134 )
135 else:
136 # Version number is acceptable
137 return
138
139 tools.console.warning(
140 """
141 *************************************************************************
142 ** WARNING: Unable to determine the version of Xcode that is installed **
143 *************************************************************************
144
145 Briefcase will proceed, assuming everything is OK. If you experience
146 problems, this is almost certainly the cause of those problems.
147
148 Please report this as a bug at:
149
150 https://github.com/beeware/briefcase/issues/new
151
152 In your report, please including the output from running:
153
154 $ xcodebuild -version
155
156 from the command prompt.
157
158 *************************************************************************
159 """
160 )
161
162 except subprocess.CalledProcessError as e:
163 if " is a command line tools instance" in e.output:
164 # Commandline tools are currently selected. Look for the existence
165 # of the default folder; if that folder doesn't exist, we can't
166 # conclude that Xcode *isn't* installed.
167 if Path(xcode_location).exists():
168 preamble = """\
169 Xcode appears to be installed, but the active developer directory is the Xcode
170 command line tools. To make Xcode the active developer directory, run:
171
172 $ sudo xcode-select --switch /Applications/Xcode.app
173 """
174 else:
175 preamble = """\
176 You have the Xcode command line tools installed; however, Briefcase requires
177 a full Xcode install. Xcode can be downloaded from the macOS App Store at
178 <https://apps.apple.com/au/app/xcode/id497799835?mt=12>.
179 """
180
181 raise BriefcaseCommandError(
182 preamble
183 + """
184 Or, to use a version of Xcode installed in a non-default location:
185
186 $ sudo xcode-select --switch /path/to/Xcode.app
187
188 and then re-run Briefcase.
189 """
190 ) from e
191
192 else:
193 tools.subprocess.output_error(e)
194 raise BriefcaseCommandError(
195 """\
196 An Xcode install appears to exist, but Briefcase was unable to
197 determine the current Xcode version. Running:
198
199 $ xcodebuild -version
200
201 should return the current Xcode version, but it raised an error.
202
203 You may need to re-install Xcode. Re-run Briefcase once that
204 installation is complete.
205 """
206 ) from e
207
208
209 class XcodeCliTools(Tool):
210 name = "xcode_cli"
211 full_name = "Xcode Command Line Tools"
212 supported_host_os: Collection[str] = {"Darwin"}
213
214 @classmethod
215 def verify_install(cls, tools: ToolCache, **kwargs) -> XcodeCliTools:
216 """Verify that command line developer tools are installed and ready for use.
217
218 A completely clean machine will have neither Xcode *nor* the Command Line Tools.
219 However, it's possible to install Xcode and *not* install the command line
220 tools, and vice versa.
221
222 Lastly, there is a license that needs to be accepted.
223
224 :param tools: ToolCache of available tools
225 """
226 # short circuit since already verified and available
227 if hasattr(tools, "xcode_cli"):
228 return tools.xcode_cli
229
230 cls.ensure_command_line_tools_are_installed(tools=tools)
231 cls.confirm_xcode_license_accepted(tools=tools)
232
233 tools.xcode_cli = XcodeCliTools(tools=tools)
234 return tools.xcode_cli
235
236 @classmethod
237 def ensure_command_line_tools_are_installed(cls, tools: ToolCache):
238 """Determine if the Xcode command line tools are installed.
239
240 If they are not installed, an exception is raised; in addition, an OS dialog
241 will be displayed prompting the user to install Xcode.
242
243 :param tools: ToolCache of available tools
244 """
245 # We determine if the command line tools are installed by running:
246 #
247 # xcode-select --install
248 #
249 # If that command exits with status 0, it means the tools are *not*
250 # installed; but a dialog will be displayed prompting an installation.
251 #
252 # If it returns a status code of 1, the tools are already installed
253 # and outputs the message "command line tools are already installed"
254 #
255 # Any other status code is a problem.
256 try:
257 tools.subprocess.check_output(["xcode-select", "--install"], quiet=1)
258 raise BriefcaseCommandError(
259 """\
260 The command line developer tools are not installed.
261
262 You should be shown a dialog prompting you to install them. Select "Install"
263 to continue, and re-run Briefcase once that installation is complete.
264 """
265 )
266 except subprocess.CalledProcessError as e:
267 if e.returncode != 1:
268 tools.console.warning(
269 """
270 *************************************************************************
271 ** WARNING: Unable to determine if Xcode is installed **
272 *************************************************************************
273
274 Briefcase will proceed, assuming everything is OK. If you experience
275 problems, this is almost certainly the cause of those problems.
276
277 Please report this as a bug at:
278
279 https://github.com/beeware/briefcase/issues/new
280
281 In your report, please including the output from running:
282
283 $ xcode-select --install
284
285 from the command prompt.
286
287 *************************************************************************
288 """
289 )
290
291 @classmethod
292 def confirm_xcode_license_accepted(cls, tools: ToolCache):
293 """Confirm if the Xcode license has been accepted.
294
295 :param tools: ToolCache of available tools
296 """
297 # Lastly, check if the Xcode license has been accepted. The command line
298 # tools return a status code of 69 (nice...) if the license has not been
299 # accepted. In this case, we can prompt the user to accept the license.
300 try:
301 tools.subprocess.check_output(["/usr/bin/clang", "--version"], quiet=1)
302 except subprocess.CalledProcessError as e:
303 if e.returncode == 69:
304 tools.console.info(
305 """
306 Use of Xcode and the iOS developer tools are covered by a license that must be
307 accepted before you can use those tools.
308
309 You can accept these licenses by starting Xcode and clicking "Accept"; or, you
310 can run this command and accept the license when prompted:
311
312 $ sudo xcodebuild -license
313
314 Briefcase will try to run this command now. You will need to enter your
315 password (Briefcase will not store this password anywhere).
316 """
317 )
318 try:
319 tools.subprocess.run(
320 ["sudo", "xcodebuild", "-license"],
321 check=True,
322 stream_output=False,
323 )
324 except subprocess.CalledProcessError as e:
325 # status code 1 - sudo fail
326 # status code 69 - license not accepted.
327 if e.returncode == 1:
328 raise BriefcaseCommandError(
329 """\
330 Briefcase was unable to run the Xcode licensing tool. This may be because you
331 did not enter your password correctly, or because your account does not have
332 administrator privileges on this computer.
333
334 You need to accept the Xcode license before Briefcase can package your app.
335 """
336 ) from e
337 elif e.returncode == 69:
338 raise BriefcaseCommandError(
339 """\
340 Xcode license has not been accepted. Briefcase cannot continue.
341
342 You need to accept the Xcode license before Briefcase can package your app.
343 """
344 ) from e
345 else:
346 tools.console.warning(
347 """
348 *************************************************************************
349 ** WARNING: Unable to determine if the Xcode license has been accepted **
350 *************************************************************************
351
352 Briefcase will proceed, assuming everything is OK. If you experience
353 problems, this is almost certainly the cause of those problems.
354
355 Please report this as a bug at:
356
357 https://github.com/beeware/briefcase/issues/new
358
359 In your report, please including the output from running:
360
361 $ sudo xcodebuild -license
362
363 from the command prompt.
364
365 *************************************************************************
366 """
367 )
368 else:
369 tools.subprocess.output_error(e)
370 tools.console.warning(
371 """
372 *************************************************************************
373 ** WARNING: Unable to determine if the Xcode license has been accepted **
374 *************************************************************************
375
376 Briefcase will proceed, assuming everything is OK. If you experience
377 problems, this is almost certainly the cause of those problems.
378
379 Please report this as a bug at:
380
381 https://github.com/beeware/briefcase/issues/new
382
383 In your report, please including the output from running:
384
385 $ /usr/bin/clang --version
386
387 from the command prompt.
388
389 *************************************************************************
390 """
391 )
392
393
394 def get_simulators(
395 tools: ToolCache,
396 os_name: str,
397 simulator_location: str = (
398 "/Library/Developer/PrivateFrameworks/CoreSimulator.framework/"
399 ),
400 ) -> dict[str, str]:
401 """Obtain the simulators available on this machine.
402
403 The return value is a 2 level dictionary. The outer dictionary is keyed by OS
404 version; the inner dictionary for each OS version contains the details of the
405 available simulators, keyed by UDID.
406
407 :param tools: ToolCache of available tools
408 :param os_name: The OS that we want to simulate. One of `"iOS"`, `"watchOS"`, or
409 `"tvOS"`.
410 :param simulator_location: The filesystem path where the simulator frameworks are
411 installed.
412 :returns: A dictionary of available simulators.
413 """
414 # If the simulator frameworks don't exist, they will be downloaded
415 # and installed. This should only occur on first execution.
416 if not Path(simulator_location).exists():
417 tools.console.prompt(
418 f"""
419 It looks like the {os_name} Simulator is not installed. The {os_name} Simulator
420 must be installed with administrator privileges.
421
422 xcodebuild will prompt you for your admin password so that it can download
423 and install the simulator.
424 """
425 )
426 tools.console("Press Return to continue: ")
427
428 try:
429 simctl_data = tools.subprocess.parse_output(
430 json_parser,
431 ["xcrun", "simctl", "list", "-j"],
432 )
433
434 os_versions = {
435 runtime["name"]: runtime["identifier"]
436 for runtime in simctl_data["runtimes"]
437 if runtime["name"].startswith(f"{os_name} ") and runtime["isAvailable"]
438 }
439
440 # For some reason, simctl varies the style of key that is used to
441 # identify device versions. The first format is OS identifier (e.g.,
442 # 'com.apple.CoreSimulator.SimRuntime.iOS-12-0'). The second is a
443 # "human readable" name ('iOS 12.0'). We presume (but can't verify)
444 # that any given OS version only exists with a single key.
445 # SO - Look for an identifier first; then look for the OS name. If
446 # neither exist, return an empty list.
447 simulators = {
448 version: {
449 device["udid"]: device["name"]
450 for device in simctl_data["devices"].get(
451 identifier, simctl_data["devices"].get(version, [])
452 )
453 if device["isAvailable"]
454 }
455 for version, identifier in os_versions.items()
456 }
457
458 # Purge any versions with no devices
459 versions_with_no_devices = [
460 version for version, devices in simulators.items() if len(devices) == 0
461 ]
462 for version in versions_with_no_devices:
463 simulators.pop(version)
464
465 return simulators
466
467 except CommandOutputParseError as e:
468 raise BriefcaseCommandError("Unable to parse output of xcrun simctl") from e
469 except subprocess.CalledProcessError as e:
470 raise BriefcaseCommandError("Unable to run xcrun simctl.") from e
471
472
473 def get_device_state(tools: ToolCache, udid: str) -> str:
474 """Determine the state of an iOS simulator device.
475
476 :param tools: ToolCache of available tools
477 :param udid: The UDID of the device to inspect
478 :returns: The status of the device, as a DeviceState enum.
479 """
480 try:
481 simctl_data = tools.subprocess.parse_output(
482 json_parser,
483 ["xcrun", "simctl", "list", "devices", "-j", udid],
484 )
485
486 for _, devices in simctl_data["devices"].items():
487 for device in devices:
488 if device["udid"] == udid:
489 return {
490 "Booted": DeviceState.BOOTED,
491 "Shutting Down": DeviceState.SHUTTING_DOWN,
492 "Shutdown": DeviceState.SHUTDOWN,
493 }.get(device["state"], DeviceState.UNKNOWN)
494
495 # If we fall out the bottom of the loop, the UDID didn't match
496 # so we raise an error.
497 raise BriefcaseCommandError(f"Unable to determine status of device {udid}.")
498 except CommandOutputParseError as e:
499 raise BriefcaseCommandError("Unable to parse output of xcrun simctl") from e
500 except subprocess.CalledProcessError as e:
501 raise BriefcaseCommandError("Unable to run xcrun simctl.") from e
502
503
504 # A regex pattern that matches the content returned by `security find-identity`
505 IDENTITY_RE = re.compile(r"\s*\d+\) ([0-9A-F]{40}) \"(.*)\"")
506
507
508 def get_identities(tools: ToolCache, policy: str | None = None) -> dict[str, str]:
509 """Obtain a set of valid identities for the given policy.
510
511 :param tools: ToolCache of available tools
512 :param policy: The identity policy to evaluate (e.g., ``codesigning``).
513 If None, no policy filtering is applied.
514 """
515 try:
516 output = tools.subprocess.check_output(
517 ["security", "find-identity", "-v"] + (["-p", policy] if policy else []),
518 )
519
520 return dict(
521 IDENTITY_RE.match(line).groups()
522 for line in output.split("\n")
523 if IDENTITY_RE.match(line)
524 )
525
526 except subprocess.CalledProcessError as e:
527 raise BriefcaseCommandError("Unable to run security find-identity.") from e