Debian Codegraph @

src/briefcase/commands/create.py

raw
1 from __future__ import annotations
2
3 import argparse
4 import hashlib
5 import os
6 import platform
7 import re
8 import shutil
9 import subprocess
10 import sys
11 from collections.abc import Collection
12 from datetime import date, datetime
13 from pathlib import Path
14
15 import briefcase
16 from briefcase.config import AppConfig
17 from briefcase.exceptions import (
18 BriefcaseCommandError,
19 InvalidStubBinary,
20 InvalidSupportPackage,
21 MissingAppSources,
22 MissingNetworkResourceError,
23 MissingStubBinary,
24 MissingSupportPackage,
25 RequirementsInstallError,
26 UnsupportedPlatform,
27 )
28 from briefcase.integrations.git import Git
29 from briefcase.integrations.subprocess import NativeAppContext
30
31 from .base import BaseCommand, full_options
32
33
34 def cookiecutter_cache_path(template):
35 """Determine the cookiecutter template cache directory given a template URL.
36
37 This will return a valid path, regardless of whether `template`
38
39 :param template: The template to use. This can be a filesystem path or
40 a URL.
41 :returns: The path that cookiecutter would use for the given template name.
42 """
43 template = template.rstrip("/")
44 tail = template.split("/")[-1]
45 cache_name = tail.rsplit(".git")[0]
46 return Path.home() / ".cookiecutters" / cache_name
47
48
49 def write_dist_info(app: AppConfig, dist_info_path: Path):
50 """Install the dist-info folder for the application.
51
52 :param app: The config object for the app
53 :param dist_info_path: The path into which the dist-info folder should be written.
54 """
55 # Create dist-info folder, and write a minimal metadata collection.
56 dist_info_path.mkdir(exist_ok=True)
57 with (dist_info_path / "INSTALLER").open("w", encoding="utf-8") as f:
58 f.write("briefcase\n")
59 with (dist_info_path / "WHEEL").open("w", encoding="utf-8") as f:
60 f.write("Wheel-Version: 1.0\n")
61 f.write("Root-Is-Purelib: true\n")
62 f.write(f"Generator: briefcase ({briefcase.__version__})\n")
63 f.write("Tag: py3-none-any\n")
64 with (dist_info_path / "METADATA").open("w", encoding="utf-8") as f:
65 f.write("Metadata-Version: 2.1\n")
66 f.write(f"Briefcase-Version: {briefcase.__version__}\n")
67 f.write(f"Name: {app.app_name}\n")
68 f.write(f"Formal-Name: {app.formal_name}\n")
69 f.write(f"App-ID: {app.bundle_identifier}\n")
70 f.write(f"Version: {app.version}\n")
71 if app.url:
72 f.write(f"Home-page: {app.url}\n")
73 f.write(f"Download-URL: {app.url}\n")
74 else:
75 f.write("Download-URL: \n")
76 if app.author:
77 f.write(f"Author: {app.author}\n")
78 if app.author_email:
79 f.write(f"Author-email: {app.author_email}\n")
80 f.write(f"Summary: {app.description}\n")
81 with (dist_info_path / "top_level.txt").open("w", encoding="utf-8") as f:
82 f.write(f"{app.module_name}\n")
83
84
85 class CreateCommand(BaseCommand):
86 command = "create"
87 description = "Create a new app for a target platform."
88
89 def add_options(self, parser):
90 super().add_options(parser)
91 parser.add_argument(
92 "-a",
93 "--app",
94 dest="app_name",
95 help="Name of the app to create (if multiple apps exist in the project)",
96 default=argparse.SUPPRESS,
97 )
98
99 # app properties that won't be exposed to the context
100 hidden_app_properties: Collection[str] = {"permission"}
101
102 @property
103 def app_template_url(self) -> str:
104 """The URL for a cookiecutter repository to use when creating apps."""
105 return f"https://github.com/beeware/briefcase-{self.platform}-{self.output_format}-template.git"
106
107 def support_package_filename(self, support_revision: str) -> str:
108 """The query arguments to use in a support package query request."""
109 return (
110 f"Python-{self.python_version_tag}-{self.platform}"
111 f"-support.b{support_revision}.tar.gz"
112 )
113
114 def support_package_url(self, support_revision: str) -> str:
115 """The URL of the support package to use for apps of this type."""
116 return (
117 "https://briefcase-support.s3.amazonaws.com/python/"
118 f"{self.python_version_tag}/"
119 f"{self.platform}/"
120 f"{self.support_package_filename(support_revision)}"
121 )
122
123 def stub_binary_filename(self, support_revision: str, is_console_app: bool) -> str:
124 """The filename for the stub binary."""
125 stub_type = "Console" if is_console_app else "GUI"
126 return f"{stub_type}-Stub-{self.python_version_tag}-b{support_revision}.zip"
127
128 def stub_binary_url(self, support_revision: str, is_console_app: bool) -> str:
129 """The URL of the stub binary to use for apps of this type."""
130 return (
131 "https://briefcase-support.s3.amazonaws.com/python/"
132 f"{self.python_version_tag}/"
133 f"{self.platform}/"
134 f"{self.stub_binary_filename(support_revision, is_console_app)}"
135 )
136
137 def icon_targets(self, app: AppConfig):
138 """Obtain the dictionary of icon targets that the template requires.
139
140 :param app: The config object for the app
141 :return: A dictionary of icons that the template supports. The keys of the
142 dictionary are the size of the icons.
143 """
144 # If the template specifies no icons, return an empty dictionary.
145 # If the template specifies a single icon without a size specification,
146 # return a dictionary with a single ``None`` key.
147 # Otherwise, return the full size-keyed dictionary.
148 try:
149 icon_targets = self.path_index(app, "icon")
150 # Convert string-specified icons into an "unknown size" icon form
151 if isinstance(icon_targets, str):
152 icon_targets = {None: icon_targets}
153 except KeyError:
154 icon_targets = {}
155
156 return icon_targets
157
158 def document_type_icon_targets(self, app: AppConfig):
159 """Obtain the dictionary of document type icon targets that the template
160 requires.
161
162 :param app: The config object for the app
163 :return: A dictionary of document types, with the values being dictionaries
164 describing the icon sizes that the template supports. The inner dictionary
165 describes the path fragments (relative to the bundle path) for the images
166 that are required; the keys are the size of the splash images.
167 """
168 # If the template specifies no document types, return an empty dictionary.
169 # Then, for each document type; If the template specifies a single icon
170 # without a size specification, return a dictionary with a single
171 # ``None`` key. Otherwise, return the full size-keyed dictionary.
172 try:
173 icon_targets = self.path_index(app, "document_type_icon")
174 return {
175 extension: {None: targets} if isinstance(targets, str) else targets
176 for extension, targets in icon_targets.items()
177 }
178
179 except KeyError:
180 return {}
181
182 def _x_permissions(self, app: AppConfig):
183 """Extract the known cross-platform permission definitions from the app's
184 permissions definitions.
185
186 After calling this method, the ``permissions`` declaration for the app will
187 only contain keys that are *not* cross-platform keys.
188
189 :param app: The config object for the app
190 :returns: A dictionary of known cross-platform permission definitions.
191 """
192 return {
193 key: app.permission.pop(key, None)
194 for key in [
195 "bluetooth",
196 "camera",
197 "microphone",
198 "coarse_location",
199 "fine_location",
200 "background_location",
201 "photo_library",
202 ]
203 }
204
205 def permissions_context(self, app: AppConfig, x_permissions: dict[str, str]):
206 """Additional template context for permissions.
207
208 :param app: The config object for the app
209 :param x_permissions: The dictionary of known cross-platform permission
210 definitions.
211 :returns: The template context describing permissions for the app.
212 """
213 return {}
214
215 def output_format_template_context(self, app: AppConfig):
216 """Additional template context required by the output format.
217
218 :param app: The config object for the app
219 """
220 return {}
221
222 def generate_app_template(self, app: AppConfig):
223 """Create an application bundle.
224
225 :param app: The config object for the app
226 """
227 # If the app config doesn't explicitly define a template,
228 # use a default template.
229
230 # Construct a template context from the app configuration.
231 extra_context = {
232 key: value
233 for key, value in app.__dict__.items()
234 if key not in self.hidden_app_properties
235 }
236
237 # Remove the context items that describe the template
238 extra_context.pop("template")
239 extra_context.pop("template_branch")
240
241 # Augment with some extra fields.
242 extra_context.update(
243 {
244 # Ensure the output format is in the case we expect
245 "format": self.output_format.lower(),
246 # Ensure the version number is in string form
247 "version": str(app.version),
248 # Properties of the generating environment
249 # The full Python version string, including minor and dev/a/b/c suffixes
250 # (e.g., 3.11.0rc2)
251 "python_version": platform.python_version(),
252 # The host architecture
253 "host_arch": self.tools.host_arch,
254 # Transformations of explicit properties into useful forms
255 "class_name": app.class_name,
256 "module_name": app.module_name,
257 "package_name": app.package_name,
258 "bundle_identifier": app.bundle_identifier,
259 # Properties that are a function of the execution
260 "year": date.today().strftime("%Y"),
261 "month": date.today().strftime("%B"),
262 }
263 )
264
265 # Add in any extra template context to support permissions
266 extra_context.update(self.permissions_context(app, self._x_permissions(app)))
267
268 # Add in any extra template context required by the output format.
269 extra_context.update(self.output_format_template_context(app))
270
271 # Create the platform directory (if it doesn't already exist)
272 output_path = self.bundle_path(app).parent
273 output_path.mkdir(parents=True, exist_ok=True)
274
275 self.generate_template(
276 template=app.template or self.app_template_url,
277 branch=app.template_branch,
278 output_path=output_path,
279 extra_context=extra_context,
280 )
281
282 def _unpack_support_package(self, support_file_path, support_path):
283 """Unpack a support package into a specific location.
284
285 :param support_file_path: The path to the support file to be unpacked.
286 :param support_path: The path where support files should be unpacked.
287 """
288 try:
289 with self.console.wait_bar("Unpacking support package..."):
290 support_path.mkdir(parents=True, exist_ok=True)
291 self.tools.file.unpack_archive(
292 support_file_path,
293 extract_dir=support_path,
294 )
295 except (shutil.ReadError, EOFError) as e:
296 raise InvalidSupportPackage(support_file_path) from e
297
298 def _cleanup_app_support_package(self, support_path):
299 """The internal implementation of the app support cleanup method.
300
301 Guaranteed to only be invoked if the backend uses a support package, and the
302 support path exists.
303
304 :param support_path: The support path to clean up.
305 """
306 with self.console.wait_bar("Removing existing support package..."):
307 self.tools.shutil.rmtree(support_path)
308
309 def cleanup_app_support_package(self, app: AppConfig):
310 """Clean up an existing application support package.
311
312 :param app: The config object for the app
313 """
314 try:
315 support_path = self.support_path(app)
316 except KeyError:
317 # No cleanup required.
318 pass
319 else:
320 if support_path.exists():
321 self._cleanup_app_support_package(support_path)
322
323 def install_app_support_package(self, app: AppConfig):
324 """Install the application support package.
325
326 :param app: The config object for the app
327 """
328 try:
329 support_path = self.support_path(app)
330 except KeyError:
331 self.console.info("No support package required.")
332 else:
333 support_file_path = self._download_support_package(app)
334 self._unpack_support_package(support_file_path, support_path)
335
336 def _download_support_package(self, app: AppConfig):
337 try:
338 # Work out if the app defines a custom override for
339 # the support package URL.
340 try:
341 support_package_url = app.support_package
342 custom_support_package = True
343 self.console.info(f"Using custom support package {support_package_url}")
344 try:
345 # If the app has a custom support package *and* a support revision,
346 # that's an error.
347 _ = app.support_revision
348 self.console.warning(
349 "App specifies both a support package and a support revision; "
350 "support revision will be ignored."
351 )
352 except AttributeError:
353 pass
354 except AttributeError:
355 # If the app specifies a support revision, use it;
356 # otherwise, use the support revision named by the template
357 try:
358 support_revision = app.support_revision
359 except AttributeError:
360 # No support revision specified; use the template-specified version
361 try:
362 support_revision = self.support_revision(app)
363 except KeyError:
364 # No template-specified support revision
365 raise MissingSupportPackage(
366 python_version_tag=self.python_version_tag,
367 platform=self.platform,
368 host_arch=self.tools.host_arch,
369 is_32bit=self.tools.is_32bit_python,
370 ) from None
371
372 support_package_url = self.support_package_url(support_revision)
373 custom_support_package = False
374 self.console.info(f"Using support package {support_package_url}")
375
376 if support_package_url.startswith(("https://", "http://")):
377 if custom_support_package:
378 # If the support package is custom, cache it using a hash of
379 # the download URL. This is needed to differentiate to support
380 # packages with the same filename, served at different URLs.
381 # (or a custom package that collides with an official package name)
382 download_path = (
383 self.data_path
384 / "support"
385 / hashlib.sha256(
386 support_package_url.encode("utf-8")
387 ).hexdigest()
388 )
389 else:
390 download_path = self.data_path / "support"
391
392 # Download the support file, caching the result
393 # in the user's briefcase support cache directory.
394 return self.tools.file.download(
395 url=support_package_url,
396 download_path=download_path,
397 role="support package",
398 )
399 else:
400 return Path(support_package_url)
401 except MissingNetworkResourceError as e:
402 # If there is a custom support package, report the missing resource as-is.
403 if custom_support_package:
404 raise
405 else:
406 raise MissingSupportPackage(
407 python_version_tag=self.python_version_tag,
408 platform=self.platform,
409 host_arch=self.tools.host_arch,
410 is_32bit=self.tools.is_32bit_python,
411 ) from e
412
413 def cleanup_stub_binary(self, app: AppConfig):
414 """Clean up an existing application support package.
415
416 :param app: The config object for the app
417 """
418 with self.console.wait_bar("Removing existing stub binary..."):
419 self.binary_executable_path(app).unlink(missing_ok=True)
420 self.unbuilt_executable_path(app).unlink(missing_ok=True)
421
422 def install_stub_binary(self, app: AppConfig):
423 """Install the application stub binary into the "unbuilt" location.
424
425 :param app: The config object for the app
426 """
427 unbuilt_executable_path = self.unbuilt_executable_path(app)
428 stub_binary_path = self._download_stub_binary(app)
429
430 with self.console.wait_bar("Installing stub binary..."):
431 # Ensure the folder for the stub binary exists
432 unbuilt_executable_path.parent.mkdir(exist_ok=True, parents=True)
433
434 # Install the stub binary into the unbuilt location.
435 # Allow for both raw and compressed artefacts.
436 try:
437 if self.tools.file.is_archive(stub_binary_path):
438 self.tools.file.unpack_archive(
439 stub_binary_path,
440 extract_dir=unbuilt_executable_path.parent,
441 )
442 elif stub_binary_path.is_file():
443 self.tools.shutil.copyfile(
444 stub_binary_path, unbuilt_executable_path
445 )
446 else:
447 raise InvalidStubBinary(stub_binary_path)
448 except (shutil.ReadError, EOFError, OSError) as e:
449 raise InvalidStubBinary(stub_binary_path) from e
450 else:
451 # Ensure the binary is executable
452 self.tools.os.chmod(unbuilt_executable_path, 0o755)
453
454 def _download_stub_binary(self, app: AppConfig) -> Path:
455 try:
456 # Work out if the app defines a custom override for
457 # the support package URL.
458 try:
459 stub_binary_url = app.stub_binary
460 custom_stub_binary = True
461 self.console.info(f"Using custom stub binary {stub_binary_url}")
462 try:
463 # If the app has a custom stub binary *and* a support revision,
464 # that's an error.
465 _ = app.stub_binary_revision
466 self.console.warning(
467 "App specifies both a stub binary and a stub binary revision; "
468 "stub binary revision will be ignored."
469 )
470 except AttributeError:
471 pass
472 except AttributeError:
473 # If the app specifies a support revision, use it; otherwise, use the
474 # support revision named by the template. This value *must* exist, as
475 # stub binary handling won't be triggered at all unless it is present.
476 try:
477 stub_binary_revision = app.stub_binary_revision
478 except AttributeError:
479 stub_binary_revision = self.stub_binary_revision(app)
480
481 stub_binary_url = self.stub_binary_url(
482 stub_binary_revision, app.console_app
483 )
484 custom_stub_binary = False
485 self.console.info(f"Using stub binary {stub_binary_url}")
486
487 if stub_binary_url.startswith(("https://", "http://")):
488 if custom_stub_binary:
489 # If the support package is custom, cache it using a hash of
490 # the download URL. This is needed to differentiate to support
491 # packages with the same filename, served at different URLs.
492 # (or a custom package that collides with an official package name)
493 download_path = (
494 self.data_path
495 / "stub"
496 / hashlib.sha256(stub_binary_url.encode("utf-8")).hexdigest()
497 )
498 else:
499 download_path = self.data_path / "stub"
500
501 # Download the stub binary, caching the result
502 # in the user's briefcase stub cache directory.
503 return self.tools.file.download(
504 url=stub_binary_url,
505 download_path=download_path,
506 role="stub binary",
507 )
508 else:
509 return Path(stub_binary_url)
510 except MissingNetworkResourceError as e:
511 # If there is a custom support package, report the missing resource as-is.
512 if custom_stub_binary:
513 raise
514 else:
515 raise MissingStubBinary(
516 python_version_tag=self.python_version_tag,
517 platform=self.platform,
518 host_arch=self.tools.host_arch,
519 is_32bit=self.tools.is_32bit_python,
520 ) from e
521
522 def _write_requirements_file(
523 self,
524 app: AppConfig,
525 requires: list[str],
526 requirements_path: Path,
527 requirement_installer_args_path: Path | None,
528 ):
529 """Configure application requirements by writing a requirements.txt file.
530
531 :param app: The app configuration
532 :param requires: The full list of requirements
533 :param requirements_path: The full path to a requirements.txt file that will be
534 written.
535 :param requirement_installer_args_path: The full path to where newline delimited
536 additional requirement installer argumentss should be written if the
537 template supports it.
538 """
539
540 with self.console.wait_bar("Writing requirements file..."):
541 with requirements_path.open("w", encoding="utf-8") as f:
542 # Add timestamp so build systems (such as Gradle) detect a change
543 # in the file and perform a re-installation of all requirements.
544 f.write(f"# Generated {datetime.now()}\n")
545
546 if requires:
547 for requirement in requires:
548 # If the requirement is a local path, convert it to
549 # absolute, because Flatpak moves the requirements file
550 # to a different place before using it.
551 if _is_local_path(requirement):
552 # We use os.path.abspath() rather than Path.resolve()
553 # because we *don't* want Path's symlink resolving behavior.
554 requirement = os.path.abspath(self.base_path / requirement)
555 f.write(f"{requirement}\n")
556
557 if requirement_installer_args_path:
558 pip_args = "\n".join(self._extra_pip_args(app))
559 requirement_installer_args_path.write_text(
560 f"{pip_args}\n", encoding="utf-8"
561 )
562
563 def _pip_requires(self, app: AppConfig, requires: list[str]):
564 """Convert the list of requirements to be passed to pip into its final form.
565
566 :param app: The app configuration
567 :param requires: The user-specified list of app requirements
568 :returns: The final list of requirement arguments to pass to pip
569 """
570 return requires
571
572 def _extra_pip_args(self, app: AppConfig):
573 """Any additional arguments that must be passed to pip when installing packages.
574
575 :param app: The app configuration
576 :returns: A list of additional arguments
577 """
578 args: list[str] = []
579 for argument in app.requirement_installer_args:
580 to_append = argument
581 if relative_path_matcher.match(argument) and _is_local_path(argument):
582 abs_path = os.path.abspath(self.base_path / argument)
583 if Path(abs_path).exists():
584 to_append = abs_path
585
586 args.append(to_append)
587
588 return args
589
590 def _pip_install(
591 self,
592 app: AppConfig,
593 app_packages_path: Path,
594 pip_args: list[str],
595 install_hint: str = "",
596 **pip_kwargs,
597 ):
598 """Invoke pip to install a set of requirements.
599
600 :param app: The app configuration
601 :param app_packages_path: The full path of the app_packages folder into which
602 requirements should be installed.
603 :param pip_args: The list of arguments (including the list of requirements to
604 install) to pass to pip. This is in addition to the default arguments that
605 disable pip version checks, forces upgrades, and installs into the nominated
606 ``app_packages`` path.
607 :param install_hint: Additional hint information to provide in the exception
608 message if the pip install call fails.
609 :param pip_kwargs: Any additional keyword arguments to pass to
610 ``subprocess.run`` when invoking pip.
611 """
612 try:
613 self.tools[app].app_context.run(
614 [
615 sys.executable,
616 "-u",
617 "-X",
618 "utf8",
619 "-m",
620 "pip",
621 "install",
622 "--disable-pip-version-check",
623 "--upgrade",
624 "--no-user",
625 f"--target={app_packages_path}",
626 ]
627 + (["-vv"] if self.console.is_deep_debug else [])
628 + self._extra_pip_args(app)
629 + pip_args,
630 check=True,
631 encoding="UTF-8",
632 **pip_kwargs,
633 )
634 except subprocess.CalledProcessError as e:
635 raise RequirementsInstallError(install_hint=install_hint) from e
636
637 def _install_app_requirements(
638 self,
639 app: AppConfig,
640 requires: list[str],
641 app_packages_path: Path,
642 *,
643 progress_message: str = "Installing app requirements...",
644 pip_args: list[str] | None = None,
645 pip_kwargs: dict[str, dict[str, str | None]] | None = None,
646 install_hint: str = "",
647 ):
648 """Install requirements for the app with pip.
649
650 :param app: The app configuration
651 :param requires: The list of requirements to install
652 :param app_packages_path: The full path of the app_packages folder into which
653 requirements should be installed.
654 :param progress_message: The waitbar progress message to display to the user.
655 :param pip_args: Any additional command line arguments to use when invoking pip.
656 :param pip_kwargs: Any additional keyword arguments to pass to the subprocess
657 when invoking pip.
658 :param install_hint: Additional hint information to provide in the exception
659 message if the pip install call fails.
660 """
661 # Clear existing dependency directory
662 if app_packages_path.is_dir():
663 self.tools.shutil.rmtree(app_packages_path)
664 self.tools.os.mkdir(app_packages_path)
665
666 # Install requirements
667 if requires:
668 with self.console.wait_bar(progress_message):
669 self._pip_install(
670 app,
671 app_packages_path=app_packages_path,
672 pip_args=(
673 ([] if pip_args is None else pip_args)
674 + self._pip_requires(app, requires)
675 ),
676 install_hint=install_hint,
677 **(pip_kwargs or {}),
678 )
679 else:
680 self.console.info("No application requirements.")
681
682 def install_app_requirements(self, app: AppConfig):
683 """Handle requirements for the app.
684
685 This will result in either (in preferential order):
686 * a requirements.txt file being written at a location specified by
687 ``app_requirements_path`` in the template path index
688 * requirements being installed with pip into the location specified
689 by the ``app_packages_path`` in the template path index.
690
691 If the path index doesn't specify either of the path index entries,
692 an error is raised.
693
694 :param app: The config object for the app
695 """
696 requires = app.requires.copy() if app.requires else []
697 if app.test_mode and app.test_requires:
698 requires.extend(app.test_requires)
699
700 if app.debugger:
701 requires.append(app.debugger.debugger_support_pkg)
702
703 try:
704 requirements_path = self.app_requirements_path(app)
705 except KeyError:
706 requirements_path = None
707
708 try:
709 requirement_installer_args_path = self.app_requirement_installer_args_path(
710 app
711 )
712 except KeyError:
713 requirement_installer_args_path = None
714
715 if requirements_path:
716 self._write_requirements_file(
717 app, requires, requirements_path, requirement_installer_args_path
718 )
719 else:
720 try:
721 app_packages_path = self.app_packages_path(app)
722 self._install_app_requirements(app, requires, app_packages_path)
723 except KeyError as e:
724 raise BriefcaseCommandError(
725 "Application path index file does not define "
726 "`app_requirements_path` or `app_packages_path`"
727 ) from e
728
729 def install_app_code(self, app: AppConfig):
730 """Install the application code into the bundle.
731
732 :param app: The config object for the app
733 """
734 # Remove existing app folder if it exists
735 app_path = self.app_path(app)
736 if app_path.exists():
737 self.tools.shutil.rmtree(app_path)
738 self.tools.os.mkdir(app_path)
739
740 sources = app.all_sources()
741
742 # Install app code.
743 if sources:
744 for src in sources:
745 with self.console.wait_bar(f"Installing {src}..."):
746 original = self.base_path / src
747 target = app_path / original.name
748
749 # Install the new copy of the app code.
750 if not original.exists():
751 raise MissingAppSources(src)
752 elif original.is_dir():
753 self.tools.shutil.copytree(original, target, dirs_exist_ok=True)
754 else:
755 self.tools.shutil.copy(original, target)
756 else:
757 self.console.info(f"No sources defined for {app.app_name}.")
758
759 # Write the dist-info folder for the application.
760 write_dist_info(
761 app=app,
762 dist_info_path=self.app_path(app)
763 / f"{app.module_name}-{app.version}.dist-info",
764 )
765
766 def install_image(self, role, variant, size, source, target):
767 """Install an icon/image of the requested size at a target location, using the
768 source images defined by the app config.
769
770 :param role: A string describing the role the of the image.
771 :param variant: The image variant. A variant of ``None`` means the image
772 has no variants
773 :param size: The requested size for the image. A size of
774 ``None`` means the largest available size should be used.
775 :param source: The image source; or a dictionary of sources for each
776 variant. The sources will *not* include any extension or size
777 modifier; these will be added based on the requested target and
778 variant.
779 :param target: The full path where the image should be installed.
780 """
781 if source is not None:
782 if size is None:
783 if variant is None:
784 source_filename = f"{source}{target.suffix}"
785 full_role = role
786 else:
787 try:
788 full_role = f"{variant} {role}"
789 source_filename = f"{source[variant]}{target.suffix}"
790 except TypeError:
791 source_filename = f"{source}-{variant}{target.suffix}"
792 except KeyError:
793 self.console.info(
794 f"Unknown variant {variant!r} for {role}; using default"
795 )
796 return
797 else:
798 if variant is None:
799 # An annoying edge case is the case of an unsized variant.
800 # In that case, `size` is actually the variant, and the
801 # source is a dictionary keyed by variant. Try that
802 # lookup; if it fails, we have a sized image with no
803 # variant.
804 try:
805 source_filename = f"{source[size]}{target.suffix}"
806 full_role = f"{size} {role}"
807 except TypeError:
808 # The lookup on the source failed; that means we
809 # have a sized image without variants.
810 source_filename = f"{source}-{size}{target.suffix}"
811 full_role = f"{size}px {role}"
812 else:
813 try:
814 full_role = f"{size}px {variant} {role}"
815 source_filename = f"{source[variant]}-{size}{target.suffix}"
816 except TypeError:
817 source_filename = f"{source}-{variant}-{size}{target.suffix}"
818 except KeyError:
819 self.console.info(
820 f"Unknown variant {variant!r} for {size}px {role}; "
821 f"using default"
822 )
823 return
824
825 full_source = self.base_path / source_filename
826 if full_source.exists():
827 with self.console.wait_bar(
828 f"Installing {source_filename} as {full_role}..."
829 ):
830 # Make sure the target directory exists
831 target.parent.mkdir(parents=True, exist_ok=True)
832 # Copy the source image to the target location
833 self.tools.shutil.copy(full_source, target)
834 else:
835 self.console.info(
836 f"Unable to find {source_filename} for {full_role}; using default"
837 )
838
839 def install_app_resources(self, app: AppConfig):
840 """Install the application resources (such as icons and splash screens) into the
841 bundle.
842
843 :param app: The config object for the app
844 """
845 for variant_or_size, targets in self.icon_targets(app).items():
846 try:
847 # Treat the targets as a dictionary of sizes;
848 # if there's no `items`, then it's an icon without variants.
849 for size, target in targets.items():
850 self.install_image(
851 "application icon",
852 source=app.icon,
853 variant=variant_or_size,
854 size=size,
855 target=self.bundle_path(app) / target,
856 )
857 except AttributeError:
858 # Either a single variant, or a single size.
859 self.install_image(
860 "application icon",
861 source=app.icon,
862 variant=None,
863 size=variant_or_size,
864 target=self.bundle_path(app) / targets,
865 )
866
867 # Briefcase v0.3.18 - splash screens deprecated.
868 if getattr(app, "splash", None):
869 self.console.warning()
870 self.console.warning(
871 "Splash screens are now configured based on the icon. "
872 "The splash configuration will be ignored."
873 )
874
875 for extension, doctype in self.document_type_icon_targets(app).items():
876 self.console.info()
877 for size, target in doctype.items():
878 self.install_image(
879 f"icon for .{extension} documents",
880 size=size,
881 source=app.document_types[extension]["icon"],
882 variant=None,
883 target=self.bundle_path(app) / target,
884 )
885
886 def cleanup_app_content(self, app: AppConfig):
887 """Remove any content not needed by the final app bundle.
888
889 :param app: The config object for the app
890 """
891 try:
892 # Retrieve any cleanup paths defined by the app template
893 paths_to_remove = self.cleanup_paths(app)
894 except KeyError:
895 paths_to_remove = []
896
897 try:
898 # Add any user-specified paths, expanded using the app as template context.
899 paths_to_remove.extend([glob.format(app=app) for glob in app.cleanup_paths])
900 except AttributeError:
901 pass
902
903 # Remove __pycache__ folders. These folders might contain stale PYC
904 # artefacts, or encode file paths that reflect the original source
905 # location. The stub binaries all disable PYC generation, to avoid
906 # corrupting any app bundle signatures.
907 paths_to_remove.append("**/__pycache__")
908
909 with self.console.wait_bar("Removing unneeded app bundle content..."):
910 for glob in paths_to_remove:
911 # Expand each glob into a full list of files that actually exist
912 # on the file system.
913 for path in self.bundle_path(app).glob(glob):
914 relative_path = path.relative_to(self.bundle_path(app))
915 if path.is_dir() and not path.is_symlink():
916 self.console.verbose(f"Removing directory {relative_path}")
917 self.tools.shutil.rmtree(path)
918 else:
919 self.console.verbose(f"Removing {relative_path}")
920 path.unlink()
921
922 def create_app(self, app: AppConfig, **options):
923 """Create an application bundle.
924
925 :param app: The config object for the app
926 """
927 if not app.supported:
928 raise UnsupportedPlatform(self.platform)
929
930 bundle_path = self.bundle_path(app)
931 if bundle_path.exists():
932 self.console.info()
933 confirm = self.console.input_boolean(
934 f"The directory {self.bundle_path(app).relative_to(self.base_path)} "
935 "already exists; overwrite",
936 default=False,
937 )
938 if not confirm:
939 self.console.error(
940 f"Aborting creation of app {app.app_name!r}; "
941 "existing application template will not be overwritten."
942 )
943 return
944 self.console.info(
945 "Removing old application template...", prefix=app.app_name
946 )
947 self.tools.shutil.rmtree(bundle_path)
948
949 self.console.info("Generating application template...", prefix=app.app_name)
950 self.generate_app_template(app=app)
951
952 # External apps (apps that define 'external_package_path') need the packaging
953 # metadata from the template, but not the app content, dependencies, support
954 # package etc. App *resources* are installed, because they might be required for
955 # the installer.
956 if app.external_package_path:
957 self.console.info(
958 "Installing application resources...", prefix=app.app_name
959 )
960 self.install_app_resources(app=app)
961
962 self.console.info("Removing generated app content...", prefix=app.app_name)
963 self.tools.shutil.rmtree(self.bundle_package_path(app))
964
965 self.console.info(
966 "Created configuration for an externally packaged app "
967 f"in {bundle_path.relative_to(self.base_path)}",
968 prefix=app.app_name,
969 )
970 else:
971 self.console.info("Installing support package...", prefix=app.app_name)
972 self.install_app_support_package(app=app)
973
974 try:
975 # If the platform uses a stub binary, the template will define a binary
976 # revision. If this template configuration item doesn't exist, no stub
977 # binary is required.
978 self.stub_binary_revision(app)
979 except KeyError:
980 pass
981 else:
982 self.console.info("Installing stub binary...", prefix=app.app_name)
983 self.install_stub_binary(app=app)
984
985 # Verify the app after the app template and support package
986 # are in place since the app tools may be dependent on them.
987 self.verify_app(app)
988
989 self.console.info("Installing application code...", prefix=app.app_name)
990 self.install_app_code(app=app)
991
992 self.console.info("Installing requirements...", prefix=app.app_name)
993 self.install_app_requirements(app=app)
994
995 self.console.info(
996 "Installing application resources...", prefix=app.app_name
997 )
998 self.install_app_resources(app=app)
999
1000 self.console.info("Removing unneeded app content...", prefix=app.app_name)
1001 self.cleanup_app_content(app=app)
1002
1003 self.console.info(
1004 f"Created {bundle_path.relative_to(self.base_path)}",
1005 prefix=app.app_name,
1006 )
1007
1008 def verify_tools(self):
1009 """Verify that the tools needed to run this command exist.
1010
1011 Raises MissingToolException if a required system tool is missing.
1012 """
1013 super().verify_tools()
1014 Git.verify(tools=self.tools)
1015
1016 def verify_app_tools(self, app: AppConfig):
1017 """Verify that tools needed to run the command for this app exist."""
1018 super().verify_app_tools(app)
1019 NativeAppContext.verify(tools=self.tools, app=app)
1020
1021 def __call__(
1022 self,
1023 app: AppConfig | None = None,
1024 app_name: str | None = None,
1025 **options,
1026 ) -> dict | None:
1027 apps_to_create = self.resolve_apps(app=app, app_name=app_name)
1028
1029 # Confirm host compatibility, that all required tools are available,
1030 # and finalize configurations for the apps that will be created.
1031 self.finalize(apps=apps_to_create.values())
1032
1033 state = None
1034 for _, app_obj in sorted(apps_to_create.items()):
1035 state = self.create_app(
1036 app_obj,
1037 **full_options(state, options),
1038 )
1039
1040 return state
1041
1042
1043 def _has_url(requirement):
1044 """Determine if the requirement is defined as a URL.
1045
1046 Detects any of the URL schemes supported by pip
1047 (https://pip.pypa.io/en/stable/topics/vcs-support/).
1048
1049 :param requirement: The requirement to check
1050 :returns: True if the requirement is a URL supported by pip.
1051 """
1052 return any(
1053 f"{scheme}:" in requirement
1054 for scheme in (
1055 "http",
1056 "https",
1057 "file",
1058 "ftp",
1059 "git+file",
1060 "git+https",
1061 "git+ssh",
1062 "git+http",
1063 "git+git",
1064 "git",
1065 "hg+file",
1066 "hg+http",
1067 "hg+https",
1068 "hg+ssh",
1069 "hg+static-http",
1070 "svn",
1071 "svn+svn",
1072 "svn+http",
1073 "svn+https",
1074 "svn+ssh",
1075 "bzr+http",
1076 "bzr+https",
1077 "bzr+ssh",
1078 "bzr+sftp",
1079 "bzr+ftp",
1080 "bzr+lp",
1081 )
1082 )
1083
1084
1085 def _is_local_path(reference):
1086 """Determine if the reference is a local file path.
1087
1088 :param reference: The reference to check
1089 :returns: True if the reference is a local file path
1090 """
1091 # Windows allows both / and \ as a path separator in references.
1092 separators = [os.sep]
1093 if os.altsep:
1094 separators.append(os.altsep)
1095
1096 return any(sep in reference for sep in separators) and (not _has_url(reference))
1097
1098
1099 relative_path_matcher = re.compile(r"^\.{1,2}[\\/]")