Debian Codegraph @

src/briefcase/commands/base.py

raw
1 from __future__ import annotations
2
3 import argparse
4 import importlib
5 import importlib.metadata
6 import inspect
7 import os
8 import platform
9 import re
10 import subprocess
11 import sys
12 from abc import ABC, abstractmethod
13 from argparse import RawDescriptionHelpFormatter
14 from collections.abc import Collection, Iterable
15 from datetime import datetime
16 from pathlib import Path
17 from typing import Any
18
19 from cookiecutter import exceptions as cookiecutter_exceptions
20 from cookiecutter.repository import is_repo_url
21 from packaging.specifiers import InvalidSpecifier, SpecifierSet
22 from packaging.version import Version
23 from platformdirs import PlatformDirs
24
25 from briefcase.debuggers import get_debugger, get_debuggers
26
27 if sys.version_info >= (3, 11): # pragma: no-cover-if-lt-py311
28 import tomllib
29 else: # pragma: no-cover-if-gte-py311
30 import tomli as tomllib
31
32 import briefcase
33 from briefcase import __version__
34 from briefcase.config import AppConfig, GlobalConfig, parse_config
35 from briefcase.console import MAX_TEXT_WIDTH, Console
36 from briefcase.exceptions import (
37 BriefcaseCommandError,
38 BriefcaseConfigError,
39 InvalidTemplateBranch,
40 InvalidTemplateRepository,
41 MissingAppMetadata,
42 NetworkFailure,
43 UnsupportedHostError,
44 UnsupportedPythonVersion,
45 )
46 from briefcase.integrations.base import ToolCache
47 from briefcase.integrations.file import File
48 from briefcase.integrations.subprocess import Subprocess
49 from briefcase.integrations.virtual_environment import VirtualEnvironment
50 from briefcase.platforms import get_output_formats, get_platforms
51
52
53 def create_config(klass, config, msg):
54 try:
55 return klass(**config)
56 except TypeError as e:
57 # Inspect the GlobalConfig constructor to find which
58 # parameters are required and don't have a default value.
59 required_args = {
60 name
61 for name, param in inspect.signature(klass.__init__).parameters.items()
62 if param.default == inspect._empty and name not in {"self", "kwargs"}
63 }
64 missing_args = required_args - config.keys()
65 missing = ", ".join(f"'{arg}'" for arg in sorted(missing_args))
66 raise BriefcaseConfigError(f"{msg} is incomplete (missing {missing})") from e
67
68
69 def full_options(state, options):
70 """Merge command state with keyword arguments.
71
72 Command state takes precedence over any keyword argument.
73
74 :param state: The current command state. Can be ``None``.
75 :param options: The base options.
76 :returns: A dictionary containing all of ``options``, with any values
77 provided in ``state`` overriding the base ``options`` values.
78 """
79 if state is not None:
80 full = options.copy()
81 full.update(state)
82 else:
83 full = options
84
85 return full
86
87
88 def split_passthrough(args: list[str]) -> tuple[list[str], list[str]]:
89 try:
90 pos = args.index("--")
91 except ValueError:
92 return args, []
93 else:
94 return args[:pos], args[pos + 1 :]
95
96
97 def parse_config_overrides(config_overrides: list[str] | None) -> dict[str, Any]:
98 """Parse command line -C/--config option overrides.
99
100 :param config_overrides: The values passed in as configuration overrides. Each value
101 *should* be a "key=<valid TOML>" string.
102 :returns: A dictionary of app configuration keys to override and their new values.
103 :raises BriefcaseCommandError: if any of the values can't be parsed as valid TOML.
104 """
105 overrides = {}
106 if config_overrides:
107 for override in config_overrides:
108 try:
109 # Do initial checks of the key being overridden.
110 # These catch cases that would be valid TOML, but would result
111 # in invalid app configurations.
112 key, _ = override.split("=", 1)
113 if "." in key:
114 raise BriefcaseConfigError(
115 "Can't override multi-level configuration keys."
116 )
117 elif key == "app_name":
118 raise BriefcaseConfigError("The app name cannot be overridden.")
119
120 # Now actually parse the value
121 overrides.update(tomllib.loads(override))
122 except ValueError as e:
123 raise BriefcaseConfigError(
124 f"Unable to parse configuration override {override}"
125 ) from e
126 return overrides
127
128
129 class BaseCommand(ABC):
130 cmd_line = "briefcase {command} {platform} {output_format}"
131 supported_host_os: Collection[str] = {"Darwin", "Linux", "Windows"}
132 supported_host_os_reason = f"This command is not supported on {platform.system()}."
133
134 # defined by platform-specific subclasses
135 command: str
136 description: str
137 platform: str
138 output_format: str
139 # supports passing extra command line arguments to subprocess
140 allows_passthrough = False
141 # supports remote debugging
142 supports_debugger = False
143 # if specified for a platform, then any template for that platform must declare
144 # compatibility with that version epoch. An epoch begins when a breaking change is
145 # introduced for a platform such that older versions of a template are incompatible
146 platform_target_version: str | None = None
147
148 def __init__(
149 self,
150 console: Console,
151 tools: ToolCache = None,
152 apps: dict[str, AppConfig] | None = None,
153 base_path: Path | None = None,
154 data_path: Path | None = None,
155 is_clone: bool = False,
156 ):
157 """Base for all Commands.
158
159 :param console: Facilitates console interaction and input solicitation.
160 :param tools: Cache of tools populated by Commands as they are required.
161 :param apps: Dictionary of project's Apps keyed by app name.
162 :param base_path: Base directory for Briefcase project.
163 :param data_path: Base directory for Briefcase tools, support packages, etc.
164 :param is_clone: Flag that Command was triggered by the user's requested
165 Command; for instance, RunCommand can invoke UpdateCommand and/or
166 BuildCommand.
167 """
168 if base_path is None:
169 self.base_path = Path.cwd()
170 else:
171 self.base_path = base_path
172 self.data_path = self.validate_data_path(data_path)
173 self.apps = {} if apps is None else apps
174 self.is_clone = is_clone
175
176 self.tools = tools or ToolCache(
177 console=console,
178 base_path=self.data_path / "tools",
179 )
180 self.validate_python_version()
181
182 # Immediately add tools that must be always available
183 Subprocess.verify(tools=self.tools)
184 VirtualEnvironment.verify(tools=self.tools)
185 File.verify(tools=self.tools)
186
187 if not is_clone:
188 self.validate_locale()
189
190 self.global_config = None
191 self._briefcase_toml: dict[AppConfig, dict[str, ...]] = {}
192
193 @property
194 def console(self):
195 return self.tools.console
196
197 def validate_data_path(self, data_path):
198 """Validate provided data path or determine OS-specific path.
199
200 If a data path is provided during construction, use it. This usually indicates
201 we're under test conditions. If there's no data path provided, look for a
202 BRIEFCASE_HOME environment variable. If that isn't defined, use a platform-
203 specific default data path.
204 """
205 if data_path is None:
206 try:
207 briefcase_home = os.environ["BRIEFCASE_HOME"]
208 data_path = Path(briefcase_home).resolve()
209 # Path("") converts to ".", so check for that edge case.
210 if briefcase_home == "" or not data_path.is_dir():
211 raise BriefcaseCommandError(
212 "The path specified by BRIEFCASE_HOME does not exist."
213 )
214 except KeyError:
215 if platform.system() == "Darwin": # pragma: no-cover-if-not-macos
216 # macOS uses a bundle name, rather than just the app name
217 app_name = "org.beeware.briefcase"
218 else: # pragma: no-cover-if-is-macos
219 app_name = "briefcase"
220
221 data_path = PlatformDirs(
222 appname=app_name,
223 appauthor="BeeWare",
224 ).user_cache_path
225
226 data_path = os.fsdecode(data_path)
227
228 if " " in data_path:
229 raise BriefcaseCommandError(
230 f"""
231 The location Briefcase will use to store tools and support files:
232
233 {data_path}
234
235 contains spaces. This will cause problems with some tools, preventing
236 you from building and packaging applications.
237
238 You can set the environment variable BRIEFCASE_HOME to specify
239 a custom location for Briefcase's tools.
240
241 """
242 )
243
244 if not os.path.exists(data_path):
245 try:
246 # The Windows Store version of Python can redirect filesystem
247 # interactions within %LOCALAPPDATA% to a sandboxed location.
248 # To bypass this, the Briefcase cache directory creation is
249 # performed via ``cmd.exe`` in a different process. Once this
250 # directory exists in the "real" %LOCALAPPDATA%, Windows will
251 # allow normal interactions without attempting to sandbox them.
252 if platform.system() == "Windows": # pragma: no-cover-if-not-windows
253 subprocess.run(
254 ["mkdir", data_path],
255 shell=True,
256 check=True,
257 stdout=subprocess.DEVNULL,
258 stderr=subprocess.DEVNULL,
259 )
260 else: # pragma: no-cover-if-is-windows
261 os.makedirs(data_path, exist_ok=True)
262 except (subprocess.CalledProcessError, OSError) as e:
263 raise BriefcaseCommandError(
264 f"""
265 Failed to create the Briefcase directory to store tools and support files:
266
267 {data_path}
268
269 You can set the environment variable BRIEFCASE_HOME to specify
270 a custom location for Briefcase's tools.
271
272 """
273 ) from e
274
275 return Path(data_path)
276
277 def validate_locale(self):
278 """Validate the system's locale is compatible."""
279 if self.tools.host_os == "Linux" and self.tools.system_encoding != "UTF-8":
280 self.console.warning(
281 f"""
282 *************************************************************************
283 ** WARNING: Default system encoding is not supported **
284 *************************************************************************
285
286 Briefcase and the third-party tools it uses only support UTF-8.
287
288 The detected default system encoding is {self.tools.system_encoding}.
289
290 Briefcase will proceed but some console output could be corrupted and
291 created files or artefacts may contain corrupted text.
292
293 Update your system's encoding to UTF-8 to avoid issues.
294
295 *************************************************************************
296 """
297 )
298
299 def validate_python_version(self) -> bool:
300 """Validate the system's Python version is within its end-of-life date.
301
302 :return: True if the Python version is within its end-of-life date.
303 """
304 # Python EOL dates are provided on: https://devguide.python.org/versions/
305 # EOL for Python 3.8 was October 2024. Assuming Python releases occur on the
306 # same yearly cadence, the EOL for Python 3.x is October of 2024 + (x - 8)
307 EOL_year = 2024 + (sys.version_info.minor - 8)
308 if datetime.today() > datetime(EOL_year, 10, 1):
309 self.console.warning(
310 f"""
311 *************************************************************************
312 ** WARNING: Your Python version is unsupported! **
313 *************************************************************************
314
315 The version of Python you are using ({platform.python_version()}) is past its
316 end of life. As a result, it is highly likely your Briefcase
317 version is also out of date.
318
319 See https://devguide.python.org/versions/ for details on currently
320 supported Python versions.
321
322 *************************************************************************
323 """
324 )
325 return False
326
327 return True
328
329 def _command_factory(self, command_name: str):
330 """Command factory for the current platform and format.
331
332 :param command_name: name of Command (e.g. 'create', 'build', 'run', etc.)
333 :return: instantiated Command
334 """
335 format_module = importlib.import_module(self.__module__)
336 command = getattr(format_module, command_name)(
337 base_path=self.base_path,
338 apps=self.apps,
339 console=self.console,
340 tools=self.tools,
341 is_clone=True,
342 )
343 command.clone_options(self)
344 return command
345
346 @property
347 def create_command(self):
348 """Create Command factory for the same platform and format."""
349 return self._command_factory("create")
350
351 @property
352 def update_command(self):
353 """Update Command factory for the same platform and format."""
354 return self._command_factory("update")
355
356 @property
357 def build_command(self):
358 """Build Command factory for the same platform and format."""
359 return self._command_factory("build")
360
361 @property
362 def run_command(self):
363 """Run Command factory for the same platform and format."""
364 return self._command_factory("run")
365
366 @property
367 def package_command(self):
368 """Package Command factory for the same platform and format."""
369 return self._command_factory("package")
370
371 @property
372 def publish_command(self):
373 """Publish Command factory for the same platform and format."""
374 return self._command_factory("publish")
375
376 def template_cache_path(self, template) -> Path:
377 """The path where Briefcase keeps template checkouts.
378
379 :param template: The URL for the template that will be cached locally.
380 """
381 template = template.rstrip("/")
382 tail = template.split("/")[-1]
383 cache_name = tail.rsplit(".git")[0]
384 return self.data_path / "templates" / cache_name
385
386 def build_path(self, app) -> Path:
387 """The path in which all platform artefacts for the app will be built.
388
389 :param app: The app config
390 """
391 return self.base_path / "build" / app.app_name / self.platform.lower()
392
393 @property
394 def dist_path(self) -> Path:
395 """The path for all applications for this command's platform."""
396 return self.base_path / "dist"
397
398 def bundle_path(self, app) -> Path:
399 """The path to the bundle for the app in the output format.
400
401 The bundle is the template-generated source form of the app. The path will
402 usually be a directory, the existence of which is indicative that the template
403 has been rolled out for an app. The leaf of this path is the base of the content
404 generated from template.
405
406 :param app: The app config
407 """
408 return self.build_path(app) / self.output_format.lower()
409
410 @abstractmethod
411 def binary_path(self, app) -> Path:
412 """The path to the executable artefact for the app in the output format.
413
414 This may be a binary file produced by compilation; however, if the output format
415 doesn't require compilation, it may be the same as the bundle path (assuming the
416 bundle path is inherently "executable"), or a path that reasonably represents
417 the thing that can be executed.
418
419 :param app: The app config
420 """
421
422 def binary_executable_path(self, app) -> Path:
423 """The path to the actual binary object for the app in the output format.
424
425 For most platforms, this will be the same as the binary path. However, for
426 platforms that use an "executable bundle" (e.g., macOS), this will be actual
427 binary that is embedded in the bundle.
428
429 :param app: The app config
430 """
431 return self.binary_path(app)
432
433 def unbuilt_executable_path(self, app) -> Path:
434 """The path to the unbuilt form of the binary object for the app.
435
436 The pre-built stub binary may need to undergo some manipulation before it can be
437 used; to mark that this manipulation is required, the "unbuilt" binary has a
438 "raw" name that doesn't involve any app details. The build step moves the binary
439 to the final name.
440
441 :param app: The app config
442 """
443
444 if sys.platform == "win32": # pragma: no-cover-if-not-windows
445 suffix = self.binary_executable_path(app).suffix
446 else: # pragma: no-cover-if-is-windows
447 suffix = ""
448
449 return self.binary_executable_path(app).parent / f"Stub{suffix}"
450
451 def bundle_package_path(self, app):
452 """The root path of the content in the bundle generated by Briefcase that will
453 be packaged for distribution.
454
455 This may be overridden if the user manually specifies external_package_path.
456
457 :param app: The app config
458 """
459 # We raise NotImplementedError(), rather than making the method an
460 # abstractmethod so that we don't have to define this method on platforms that
461 # don't support external packaging. If this method is ever invoked on a platform
462 # that doesn't support external packaging, we've got a problem.
463 raise NotImplementedError()
464
465 def package_path(self, app):
466 """The root path of the content that will be packaged for distribution.
467
468 :param app: The app config
469 """
470 if app.external_package_path:
471 return Path(app.external_package_path).absolute().resolve()
472 else:
473 return self.bundle_package_path(app)
474
475 def bundle_package_executable_path(self, app):
476 """The path, relative to the package path generated by Briefcase, of the binary
477 in the packaged app that is executed as the app.
478
479 This may be overridden if the user manually specifies a
480 external_package_executable_path.
481
482 :param app: The app config
483 """
484 # We raise NotImplementedError(), rather than making the method an
485 # abstractmethod so that we don't have to define this method on platforms that
486 # don't support external packaging. If this method is ever invoked on a platform
487 # that doesn't support external packaging, we've got a problem.
488 raise NotImplementedError()
489
490 def package_executable_path(self, app):
491 """The path, relative to the package path, of the binary that is executed as the
492 app.
493
494 :param app: The app config
495 """
496 if app.external_package_executable_path:
497 return app.external_package_executable_path
498 else:
499 return self.bundle_package_executable_path(app)
500
501 def briefcase_toml(self, app: AppConfig) -> dict[str, ...]:
502 """Load the ``briefcase.toml`` file provided by the app template.
503
504 :param app: The config object for the app
505 :return: The contents of ``briefcase.toml``
506 """
507 try:
508 return self._briefcase_toml[app]
509 except KeyError:
510 try:
511 with (self.bundle_path(app) / "briefcase.toml").open("rb") as f:
512 self._briefcase_toml[app] = tomllib.load(f)
513 except OSError as e:
514 raise MissingAppMetadata(self.bundle_path(app)) from e
515 else:
516 return self._briefcase_toml[app]
517
518 def path_index(self, app: AppConfig, path_name: str) -> str | dict | list:
519 """Return a path from the path index provided by the app template.
520
521 Raises KeyError if ``path_name`` is not defined in the index.
522
523 :param app: The config object for the app
524 :param path_name: Name of the filepath to retrieve
525 :return: filepath for requested path
526 """
527 return self.briefcase_toml(app)["paths"][path_name]
528
529 def template_target_version(self, app: AppConfig) -> str | None:
530 """The target version of Briefcase for the app from ``briefcase.toml``.
531
532 This value represents a version epoch specific to the platform. An epoch begins
533 when a breaking change is introduced. Therefore, this value would remain the
534 version of Briefcase that introduced a breaking change for a template until
535 another such change requires a new epoch.
536
537 :param app: The config object for the app
538 :return: target version or None if one isn't specified
539 """
540 try:
541 return self.briefcase_toml(app)["briefcase"]["target_version"]
542 except KeyError:
543 return None
544
545 def stub_binary_revision(self, app: AppConfig) -> str:
546 """Obtain the stub binary revision that the template requires.
547
548 :param app: The config object for the app
549 :return: The stub binary revision required by the template.
550 """
551 return self.path_index(app, "stub_binary_revision")
552
553 def support_path(self, app: AppConfig) -> Path:
554 """Obtain the path into which the support package should be unpacked.
555
556 :param app: The config object for the app
557 :return: The full path where the support package should be unpacked.
558 """
559 return self.bundle_path(app) / self.path_index(app, "support_path")
560
561 def support_revision(self, app: AppConfig) -> str:
562 """Obtain the support package revision that the template requires.
563
564 :param app: The config object for the app
565 :return: The support revision required by the template.
566 """
567 return self.path_index(app, "support_revision")
568
569 def cleanup_paths(self, app: AppConfig) -> list[str]:
570 """Obtain the paths generated by the app template that should be cleaned up
571 prior to release.
572
573 :param app: The config object for the app
574 :return: The list of path globs inside the app template that should be cleaned
575 up.
576 """
577 return self.path_index(app, "cleanup_paths")
578
579 def app_requirements_path(self, app: AppConfig) -> Path:
580 """Obtain the path into which a requirements.txt file should be written.
581
582 :param app: The config object for the app
583 :return: The full path where the requirements.txt file should be written
584 """
585 return self.bundle_path(app) / self.path_index(app, "app_requirements_path")
586
587 def app_requirement_installer_args_path(self, app: AppConfig) -> Path:
588 """Obtain the path into which a newline delimited requirement installer args
589 file should be written.
590
591 :param app: The config object for the app
592 :return: The full path where the file should be written
593 """
594 return self.bundle_path(app) / self.path_index(
595 app, "app_requirement_installer_args_path"
596 )
597
598 def app_packages_path(self, app: AppConfig) -> Path:
599 """Obtain the path into which requirements should be installed.
600
601 :param app: The config object for the app
602 :return: The full path where application requirements should be installed.
603 """
604 return self.bundle_path(app) / self.path_index(app, "app_packages_path")
605
606 def app_path(self, app: AppConfig) -> Path:
607 """Obtain the path into which the application should be installed.
608
609 :param app: The config object for the app
610 :return: The full path where application code should be installed.
611 """
612 return self.bundle_path(app) / self.path_index(app, "app_path")
613
614 def app_module_path(self, app: AppConfig) -> Path:
615 """Find the path for the application module for an app.
616
617 :param app: The config object for the app
618 :returns: The Path to the dist-info folder.
619 """
620 app_home = [
621 path.split("/")
622 for path in app.sources
623 if path.rsplit("/", 1)[-1] == app.module_name
624 ]
625
626 if len(app_home) == 0:
627 raise BriefcaseCommandError(
628 f"Unable to find code for application {app.app_name!r}"
629 )
630 elif len(app_home) == 1:
631 path = Path(str(self.base_path), *app_home[0])
632 else:
633 raise BriefcaseCommandError(
634 f"Multiple paths in sources found for application {app.app_name!r}"
635 )
636
637 return path
638
639 @property
640 def briefcase_required_python_version(self):
641 """The major.minor of the minimum Python version required by Briefcase itself.
642
643 This is extracted from packaging metadata.
644 """
645 # Native format is ">=3.8"
646 return tuple(
647 int(v)
648 for v in importlib.metadata.metadata("briefcase")["Requires-Python"]
649 .split("=")[1]
650 .strip()
651 .split(".")
652 )
653
654 @property
655 def python_version_tag(self):
656 """The major.minor of the Python version in use, as a string.
657
658 This is used as a repository label/tag to identify the appropriate templates,
659 etc. to use.
660 """
661 major, minor, *_ = self.tools.sys.version_info
662 return f"{major}.{minor}"
663
664 def verify_host(self):
665 """Verify the host OS is supported by the Command."""
666 if self.tools.host_os not in self.supported_host_os:
667 raise UnsupportedHostError(self.supported_host_os_reason)
668
669 def verify_tools(self):
670 """Verify that the tools needed to run this Command exist.
671
672 Raises MissingToolException if a required system tool is missing.
673 """
674 return
675
676 def finalize_app_config(self, app: AppConfig):
677 """Finalize the application config.
678
679 Some app configurations (notably, Linux system packages like .deb) have
680 configurations that are deeper than other platforms, because they need to
681 include components that are dependent on command-line arguments. They may also
682 require the existence of system tools to complete configuration.
683
684 The final app configuration merges those "deep" properties into the app
685 configuration, and performs any other app-specific platform configuration and
686 verification that is required as a result of command-line arguments.
687
688 :param app: The app configuration to finalize.
689 """
690 return
691
692 def resolve_apps(
693 self,
694 app: AppConfig | None = None,
695 app_name: str | None = None,
696 ) -> dict[str, AppConfig]:
697 """Resolve which apps to operate on.
698
699 :param app: An explicit app config to use.
700 :param app_name: The name of the app to look up in the project.
701 :returns: A dict of app name to AppConfig for the selected apps.
702 """
703 if app_name:
704 if not (app_obj := self.apps.get(app_name)):
705 raise BriefcaseCommandError(
706 f"App '{app_name}' does not exist in this project."
707 )
708 return {app_name: app_obj}
709 elif app:
710 return {app.app_name: app}
711 else:
712 return self.apps
713
714 def finalize(
715 self,
716 apps: Iterable[AppConfig],
717 test_mode: bool = False,
718 debugger: str | None = None,
719 debugger_host: str | None = None,
720 debugger_port: int | None = None,
721 ):
722 """Finalize Briefcase configuration.
723
724 This will:
725
726 1. Ensure that the host has been verified
727 2. Ensure that the platform tools have been verified
728 3. Ensure that app configurations have been finalized.
729 4. Ensure that the debugger is configured.
730
731 App finalization will only occur once per invocation.
732
733 :param apps: The app configuration(s) to finalize.
734 :param test_mode: Specify if the app is running in test mode
735 :param debugger: The debugger that should be used
736 :param debugger_host: The host to use for the debugger
737 :param debugger_port: The port to use for the debugger
738 """
739 self.verify_host()
740 self.verify_tools()
741
742 for app in apps:
743 if hasattr(app, "__draft__"):
744 if debugger and debugger != "":
745 app.debugger = get_debugger(debugger)
746 app.debugger_host = debugger_host
747 app.debugger_port = debugger_port
748
749 app.test_mode = test_mode
750 self.finalize_app_config(app)
751 delattr(app, "__draft__")
752
753 if app.external_package_path:
754 # Package path is defined
755 if app.sources is not None:
756 # sources is not defined
757 raise BriefcaseConfigError(
758 f"{app.app_name!r} is declared as an external app, "
759 f"but also defines 'sources'. "
760 f"External apps (apps defining 'external_package_path') "
761 f"cannot define sources."
762 )
763 elif app.sources is None:
764 # Neither sources nor package_path is defined
765 raise BriefcaseConfigError(
766 f"{app.app_name!r} does not define either 'sources' or "
767 f"'external_package_path'."
768 )
769 else:
770 # sources is defined, package_path is not
771 if app.external_package_executable_path:
772 raise BriefcaseConfigError(
773 f"{app.app_name!r} defines "
774 f"'external_package_executable_path', "
775 f"but not 'external_package_path'."
776 )
777
778 def verify_app(self, app: AppConfig):
779 """Verify the app is compatible and the app tools are available.
780
781 This is the last step of verification for a Command before running the Command's
782 business logic. It runs _after_ pre-requisite Commands have been verified and
783 run.
784
785 :param app: app configuration
786 """
787 self.verify_app_template(app)
788 self.verify_app_tools(app)
789 self.verify_required_python(app)
790
791 def verify_app_tools(self, app: AppConfig):
792 """Verify that tools needed to run the command for this app exist."""
793 return
794
795 def verify_app_template(self, app: AppConfig):
796 """Verify the template targets the same Briefcase version as the Command.
797
798 :param app: app configuration
799 """
800
801 # Skip this check if the template isn't rolled out
802 # or if the command doesn't support templates
803 try:
804 template_target_version = self.template_target_version(app)
805 except (MissingAppMetadata, NotImplementedError):
806 return
807
808 if self.platform_target_version != template_target_version:
809 raise BriefcaseCommandError(
810 f"""\
811 The app template used to generate this app is not compatible with this version
812 of Briefcase.
813
814 If the app was generated with an earlier version of Briefcase using the default
815 Briefcase template, you can run:
816
817 $ briefcase create {self.platform} {self.output_format}
818
819 to re-generate your app with a compatible version of the template.
820
821 If you are using a custom template, you'll need to update the template to correct
822 any compatibility problems, and then add the compatibility declaration.
823 """
824 )
825
826 def verify_required_python(self, app: AppConfig):
827 """Verify that the running version of Python meets the project's
828 specifications."""
829
830 requires_python = getattr(self.global_config, "requires_python", None)
831 if not requires_python:
832 return
833
834 try:
835 spec = SpecifierSet(requires_python)
836 except InvalidSpecifier as e:
837 raise BriefcaseConfigError(
838 f"Invalid requires-python in pyproject.toml: {e}"
839 ) from e
840
841 running_version = platform.python_version()
842
843 if not spec.contains(running_version, prereleases=True):
844 raise UnsupportedPythonVersion(
845 version_specifier=requires_python, running_version=running_version
846 )
847
848 def parse_options(self, extra: list[str]) -> tuple[dict[str, Any], dict[str, Any]]:
849 """Parse the command line arguments for the Command.
850
851 After the initial ArgumentParser runs to choose the Command for the selected
852 platform and format, a new ArgumentParser is created here to parse the remaining
853 command line arguments specific to the Command. Additionally, the default
854 options for disabling input, log verbosity, and log saving are parsed out and
855 saved to the Command.
856
857 :param extra: the remaining command line arguments after the initial
858 ArgumentParser runs over the command line.
859 :return: dictionary of parsed arguments for Command, and a dictionary of parsed
860 configuration overrides.
861 """
862 default_format = getattr(
863 get_platforms().get(self.platform), "DEFAULT_OUTPUT_FORMAT", None
864 )
865 # only show supported formats for Commands that support formats
866 if default_format is not None and self.command not in {"new", "dev", "upgrade"}:
867 formats = list(get_output_formats(self.platform).keys())
868 formats[formats.index(default_format)] = f"{default_format} (default)"
869 supported_formats_helptext = (
870 f"Supported formats:\n {', '.join(sorted(formats, key=str.lower))}"
871 )
872 else:
873 supported_formats_helptext = ""
874
875 parser = argparse.ArgumentParser(
876 prog=self.cmd_line.format(
877 command=self.command,
878 platform=self.platform,
879 output_format=self.output_format,
880 ),
881 description=self.console.textwrap(
882 f"{self.description}\n\n{supported_formats_helptext}"
883 ),
884 formatter_class=(
885 lambda prog: RawDescriptionHelpFormatter(prog, width=MAX_TEXT_WIDTH)
886 ),
887 )
888
889 self.add_default_options(parser)
890 self.add_options(parser)
891
892 # If the command allows passthrough arguments, add an option for the help,
893 # then process the argument list to strip out the passthrough args.
894 if self.allows_passthrough:
895 parser.add_argument(
896 "--",
897 dest="passthrough",
898 metavar="ARGS ...",
899 required=False,
900 help="Arguments to pass to the app",
901 )
902 args, passthrough = split_passthrough(extra)
903 else:
904 args = extra
905
906 # Parse the full set of command line options from the content
907 # remaining after the basic command/platform/output format
908 # has been extracted.
909 options = vars(parser.parse_args(args))
910
911 if self.allows_passthrough:
912 options["passthrough"] = passthrough
913
914 # Extract the base default options onto the command
915 self.console.input_enabled = options.pop("input_enabled")
916 self.console.verbosity = options.pop("verbosity")
917 self.console.save_log = options.pop("save_log")
918
919 # Parse the configuration overrides
920 overrides = parse_config_overrides(options.pop("config_overrides"))
921
922 return options, overrides
923
924 def clone_options(self, command):
925 """Clone options from one command to this one.
926
927 :param command: The command whose options are to be cloned
928 """
929 return
930
931 def add_default_options(self, parser):
932 """Add the default options that exist on *all* commands.
933
934 :param parser: a stub argparse parser for the command.
935 """
936 parser.add_argument(
937 "-C",
938 "--config",
939 dest="config_overrides",
940 action="append",
941 metavar="KEY=VALUE",
942 help="Override the value of the app configuration item KEY with VALUE",
943 )
944 parser.add_argument(
945 "-v",
946 "--verbosity",
947 action="count",
948 default=0,
949 help=(
950 "Enable verbose logging. Use -vv and -vvv to increase logging verbosity"
951 ),
952 )
953 parser.add_argument("-V", "--version", action="version", version=__version__)
954 parser.add_argument(
955 "--no-input",
956 action="store_false",
957 default=True,
958 dest="input_enabled",
959 help=(
960 "Don't ask for user input. If any action would be destructive, "
961 "an error will be raised; otherwise, default answers will be "
962 "assumed"
963 ),
964 )
965 parser.add_argument(
966 "--log",
967 action="store_true",
968 dest="save_log",
969 help=(
970 "Save a detailed log to file. "
971 "By default, this log file is only created for critical errors"
972 ),
973 )
974
975 def _add_update_options(
976 self,
977 parser,
978 context_label="",
979 update=True,
980 ):
981 """Internal utility method for adding common update options.
982
983 :param parser: The parser to which options should be added.
984 :param context_label: Label text that will be added to the end of the help text
985 to describe when the update will be applied (e.g., "before building")
986 :param update: Should the --update and --no-update options be exposed?
987 """
988 if update:
989 parser.add_argument(
990 "-u",
991 "--update",
992 action="store_true",
993 help=f"Update the app{context_label}",
994 )
995
996 parser.add_argument(
997 "-r",
998 "--update-requirements",
999 action="store_true",
1000 help=f"Update requirements for the app{context_label}",
1001 )
1002
1003 parser.add_argument(
1004 "--update-support",
1005 action="store_true",
1006 help=f"Update support package for the app{context_label}",
1007 )
1008
1009 parser.add_argument(
1010 "--update-stub",
1011 action="store_true",
1012 help=f"Update stub binary for the app{context_label}",
1013 )
1014
1015 parser.add_argument(
1016 "--update-resources",
1017 action="store_true",
1018 help=f"Update app resources (icons, splash screens, etc){context_label}",
1019 )
1020
1021 if update:
1022 parser.add_argument(
1023 "--no-update",
1024 action="store_true",
1025 help=f"Prevent any automated update{context_label}",
1026 )
1027
1028 def _add_test_options(self, parser, context_label):
1029 """Internal utility method for adding common test-related options.
1030
1031 :param parser: The parser to which options should be added.
1032 :param context_label: Label text for commands; the capitalized action being
1033 performed (e.g., "Build", "Run",...)
1034 """
1035 parser.add_argument(
1036 "--test",
1037 dest="test_mode",
1038 action="store_true",
1039 help=f"{context_label} the app in test mode",
1040 )
1041
1042 def _add_debug_options(self, parser, context_label, run_cmd: bool = False):
1043 """Internal utility method for adding common debug-related options.
1044
1045 :param parser: The parser to which options should be added.
1046 :param context_label: Label text for commands; the capitalized action being
1047 performed (e.g., "Build", "Run",...)
1048 """
1049 debuggers = get_debuggers()
1050 debugger_names = list(reversed(debuggers.keys()))
1051
1052 parser.add_argument(
1053 "--debug",
1054 dest="debugger",
1055 nargs="?",
1056 default=None,
1057 const="pdb",
1058 choices=debugger_names,
1059 metavar="DEBUGGER",
1060 help=(
1061 f"{context_label} the app with the specified debugger. "
1062 f"One of %(choices)s (default: %(const)s)"
1063 ),
1064 )
1065
1066 if run_cmd:
1067 parser.add_argument(
1068 "--debugger-host",
1069 default="localhost",
1070 help="The host on which to run the debug server (default: %(default)s)",
1071 required=False,
1072 )
1073 parser.add_argument(
1074 "-dp",
1075 "--debugger-port",
1076 default=5678,
1077 type=int,
1078 help="The port on which to run the debug server (default: %(default)s)",
1079 required=False,
1080 )
1081
1082 def add_options(self, parser):
1083 """Add any options that this command needs to parse from the command line.
1084
1085 :param parser: a stub argparse parser for the command.
1086 """
1087 return
1088
1089 def parse_config(self, filename, overrides):
1090 try:
1091 with open(filename, "rb") as config_file:
1092 # Parse the content of the pyproject.toml file, extracting
1093 # any platform and output format configuration for each app,
1094 # creating a single set of configuration options.
1095 global_config, app_configs = parse_config(
1096 config_file,
1097 platform=self.platform,
1098 output_format=self.output_format,
1099 console=self.console,
1100 )
1101
1102 # Create the global config
1103 global_config.update(overrides)
1104 self.global_config = create_config(
1105 klass=GlobalConfig,
1106 config=global_config,
1107 msg="Global configuration",
1108 )
1109
1110 for app_name, app_config in app_configs.items():
1111 # Construct an AppConfig object with the final set of
1112 # configuration options for the app.
1113 app_config.update(overrides)
1114 self.apps[app_name] = create_config(
1115 klass=AppConfig,
1116 config=app_config,
1117 msg=f"Configuration for '{app_name}'",
1118 )
1119
1120 except OSError as e:
1121 raise BriefcaseConfigError(
1122 f"""\
1123 Configuration file not found.
1124
1125 Did you run Briefcase in a project directory that contains {filename.name!r}?"""
1126 ) from e
1127
1128 def update_cookiecutter_cache(self, template: str, branch="master"):
1129 """Ensure that we have a current checkout of a template path.
1130
1131 If the path is a local path, use the path as is.
1132
1133 If the path is a URL, look for a local cache; if one exists, update it,
1134 including checking out the required branch.
1135
1136 :param template: The template URL or path.
1137 :param branch: The template branch to use. Default: ``master``
1138 :return: The path to the cached template. This may be the originally
1139 provided path if the template was a file path.
1140 """
1141 if is_repo_url(template):
1142 # The app template is a repository URL.
1143 #
1144 # Look for a Briefcase cache of the template.
1145 cached_template = self.template_cache_path(template)
1146
1147 if cached_template.exists():
1148 # There is a pre-existing cache of the template. Attempt to update it;
1149 # if the fetch fails, use the existing state of the cache. Any other
1150 # failure is surfaced to the user.
1151 try:
1152 repo = self.tools.git.Repo(cached_template)
1153 except self.tools.git.exc.GitError:
1154 # Template repository is in a weird state. Delete it
1155 self.console.warning(
1156 "Template cache is in a weird state. Getting a clean clone."
1157 )
1158 self.tools.shutil.rmtree(cached_template)
1159
1160 if not cached_template.exists():
1161 # There's no pre-existing template. It's either the first time seeing
1162 # the template, or the template was in a weird state. Perform a blobless
1163 # clone.
1164 try:
1165 self.console.info(f"Cloning template {template!r}...")
1166 cached_template.mkdir(exist_ok=True, parents=True)
1167 repo = self.tools.git.Repo.clone_from(
1168 url=template,
1169 to_path=cached_template,
1170 filter=["blob:none"],
1171 no_checkout=True,
1172 )
1173 except KeyboardInterrupt:
1174 # The user has aborted the initial clone. Git is fairly resilient to
1175 # being interrupted, but if the *initial* clone fails, it's very
1176 # hard to recover. To avoid problems on the next run, remove the
1177 # partial repo clone.
1178 if cached_template.exists():
1179 self.tools.shutil.rmtree(cached_template)
1180 raise
1181 except self.tools.git.exc.GitError as e:
1182 # The clone failed; to make sure the repo is in a clean state,
1183 # clean up any partial remnants of this initial clone.
1184 # If we're getting a GitError, we know the directory must exist.
1185 self.tools.shutil.rmtree(cached_template)
1186 git_fatal_message = re.findall(
1187 r"(?<=fatal: ).*?$", e.stderr, flags=re.DOTALL
1188 )
1189 if git_fatal_message:
1190 # GitError captures stderr with single quotes. Because the regex
1191 # above takes everything after git's "fatal" message, we need to
1192 # strip that final single quote.
1193 hint = git_fatal_message[0].rstrip("'").strip()
1194
1195 # git is inconsistent with capitalization of the first word of
1196 # the message and about periods at the end of the message.
1197 hint = f"{hint[0].upper()}{hint[1:].removesuffix('.')}."
1198 else:
1199 hint = (
1200 "This may be because your computer is offline, or "
1201 "because the repository URL is incorrect."
1202 )
1203
1204 raise BriefcaseCommandError(
1205 f"Unable to clone repository {template!r}.\n\n{hint}"
1206 ) from e
1207
1208 try:
1209 # Raises ValueError if "origin" isn't a valid remote
1210 remote = repo.remote(name="origin")
1211 # Ensure the existing repo's origin URL points to the location
1212 # being requested. A difference can occur, for instance, if a
1213 # fork of the template is used.
1214 remote.set_url(new_url=template)
1215 try:
1216 # Attempt to update the repository
1217 remote.fetch()
1218 except self.tools.git.exc.GitCommandError as e:
1219 # We are offline, or otherwise unable to contact the origin git
1220 # repo. It's OK to continue; but capture the error in the log and
1221 # warn the user that the template may be stale.
1222 self.console.debug(str(e))
1223 self.console.warning(
1224 """
1225 *************************************************************************
1226 ** WARNING: Unable to update template **
1227 *************************************************************************
1228
1229 Briefcase is unable the update the application template. This
1230 may be because your computer is currently offline. Briefcase will
1231 use existing template without updating.
1232
1233 *************************************************************************
1234 """
1235 )
1236
1237 try:
1238 # Check out the branch for the required version tag.
1239 head = remote.refs[branch]
1240
1241 self.console.info(
1242 f"Using existing template (sha {head.commit.hexsha}, "
1243 f"updated {head.commit.committed_datetime.strftime('%c')})"
1244 )
1245 head.checkout()
1246 except IndexError as e:
1247 # No branch exists for the requested version.
1248 raise InvalidTemplateBranch(template, branch) from e
1249 except (ValueError, self.tools.git.exc.GitError) as e:
1250 raise BriefcaseCommandError(
1251 "Unable to check out template branch.\n"
1252 "\n"
1253 "This may be because your computer is offline, or because the "
1254 "template repository is in a weird state. "
1255 "If you have a stable network connection, try deleting:\n"
1256 "\n"
1257 f" {cached_template}\n"
1258 "\n"
1259 "and retrying your command."
1260 ) from e
1261 else:
1262 # If this isn't a repository URL, treat it as a local directory
1263 cached_template = template
1264
1265 return cached_template
1266
1267 def _generate_template(self, template, branch, output_path, extra_context):
1268 """Ensure the named template is up-to-date for the given branch, and roll out
1269 that template.
1270
1271 :param template: The template URL or path to generate
1272 :param branch: The branch of the template to use
1273 :param output_path: The filesystem path where the template will be generated.
1274 :param extra_context: Extra context to pass to the cookiecutter template
1275 """
1276 # Make sure we have an updated cookiecutter template,
1277 # checked out to the right branch
1278 cached_template = self.update_cookiecutter_cache(
1279 template=template,
1280 branch=branch,
1281 )
1282
1283 self.console.configure_stdlib_logging("cookiecutter")
1284 try:
1285 # Unroll the template.
1286 self.tools.cookiecutter(
1287 str(cached_template),
1288 no_input=True,
1289 output_dir=str(output_path),
1290 checkout=branch,
1291 # Use a copy to prevent changes propagating among tests
1292 # while the test suite is running
1293 extra_context=extra_context.copy(),
1294 # Store replay data in the Briefcase template cache
1295 # instead of ~/.cookiecutter_replay
1296 default_config={"replay_dir": str(self.template_cache_path(".replay"))},
1297 )
1298 except subprocess.CalledProcessError as e:
1299 # Computer is offline
1300 # status code == 128 - certificate validation error.
1301 raise NetworkFailure("clone template repository") from e
1302 except cookiecutter_exceptions.RepositoryNotFound as e:
1303 # Either the template path is invalid,
1304 # or it isn't a cookiecutter template (i.e., no cookiecutter.json)
1305 raise InvalidTemplateRepository(template) from e
1306 except cookiecutter_exceptions.RepositoryCloneFailed as e:
1307 # Branch does not exist.
1308 raise InvalidTemplateBranch(template, branch) from e
1309 except cookiecutter_exceptions.UndefinedVariableInTemplate as e:
1310 raise BriefcaseConfigError(f"{e.message}: {e.error}") from e
1311
1312 def generate_template(
1313 self,
1314 template: str | None,
1315 branch: str | None,
1316 output_path: str | Path,
1317 extra_context: dict[str, str],
1318 ) -> None:
1319 # If a branch wasn't supplied through the --template-branch argument,
1320 # use the branch derived from the Briefcase version
1321 briefcase_version = Version(briefcase.__version__)
1322 if branch is None:
1323 template_branch = f"v{briefcase_version.base_version}"
1324 else:
1325 template_branch = branch
1326
1327 extra_context = extra_context.copy()
1328 # Additional context that can be used for the Briefcase template pyproject.toml
1329 # header to include the version of Briefcase as well as the source of the
1330 # template.
1331 extra_context.update(
1332 {
1333 "template_source": template,
1334 "template_branch": template_branch,
1335 "briefcase_version": str(briefcase_version),
1336 }
1337 )
1338
1339 try:
1340 self.console.info(
1341 f"Using app template: {template}, branch {template_branch}"
1342 )
1343 # Unroll the new app template
1344 self._generate_template(
1345 template=template,
1346 branch=template_branch,
1347 output_path=output_path,
1348 extra_context=extra_context,
1349 )
1350 except InvalidTemplateBranch:
1351 # Only use the main template if we're on a development branch of briefcase
1352 # and the user didn't explicitly specify which branch to use.
1353 if briefcase_version.dev is None or branch is not None:
1354 raise
1355
1356 # Development branches can use the main template.
1357 self.console.info(
1358 f"Template branch {template_branch} not found; "
1359 f"falling back to development template"
1360 )
1361
1362 extra_context["template_branch"] = "main"
1363 self._generate_template(
1364 template=template,
1365 branch="main",
1366 output_path=output_path,
1367 extra_context=extra_context,
1368 )
1369
1370 def get_git_config_value(self, section: str, option: str) -> str | None:
1371 """Get the requested git config value, if available.
1372
1373 :param section: The configuration section.
1374 :param option: The configuration option.
1375 :returns: The configuration value, or None.
1376 """
1377 git_config_paths = [
1378 self.tools.git.config.get_config_path("system"),
1379 self.tools.git.config.get_config_path("global"),
1380 self.tools.git.config.get_config_path("user"),
1381 ".git/config",
1382 ]
1383
1384 with self.tools.git.config.GitConfigParser(git_config_paths) as git_config:
1385 if git_config.has_option(section, option):
1386 return git_config.get_value(section, option)
1387
1388 return None