| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import copy |
| 4 |
import keyword |
| 5 |
import re |
| 6 |
import sys |
| 7 |
import unicodedata |
| 8 |
from urllib.parse import urlparse |
| 9 |
|
| 10 |
from packaging.version import InvalidVersion, Version |
| 11 |
|
| 12 |
if sys.version_info >= (3, 11): # pragma: no-cover-if-lt-py311 |
| 13 |
import tomllib |
| 14 |
else: # pragma: no-cover-if-gte-py311 |
| 15 |
import tomli as tomllib |
| 16 |
|
| 17 |
from briefcase.debuggers.base import BaseDebugger |
| 18 |
from briefcase.platforms import get_output_formats, get_platforms |
| 19 |
|
| 20 |
from .constants import RESERVED_WORDS |
| 21 |
from .exceptions import BriefcaseConfigError, InvalidVersionError |
| 22 |
|
| 23 |
# PEP 508 restricts the naming of modules. The PEP defines a regex that uses |
| 24 |
# re.IGNORECASE; but in in practice, packaging uses a version that rolls out the lower |
| 25 |
# case, which has very slightly different semantics with non-ASCII characters. This |
| 26 |
# definition is the one from |
| 27 |
# https://github.com/pypa/packaging/blob/24.0/src/packaging/_tokenizer.py#L80 |
| 28 |
PEP508_NAME_RE = re.compile(r"^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9._-]*[a-zA-Z0-9])$") |
| 29 |
|
| 30 |
|
| 31 |
def is_valid_pep508_name(app_name): |
| 32 |
"""Determine if the name is valid by PEP508 rules.""" |
| 33 |
return PEP508_NAME_RE.match(app_name) |
| 34 |
|
| 35 |
|
| 36 |
def is_reserved_keyword(app_name): |
| 37 |
"""Determine if the name is a reserved keyword.""" |
| 38 |
return keyword.iskeyword(app_name.lower()) or app_name.lower() in RESERVED_WORDS |
| 39 |
|
| 40 |
|
| 41 |
def is_valid_app_name(app_name): |
| 42 |
return not is_reserved_keyword(app_name) and is_valid_pep508_name(app_name) |
| 43 |
|
| 44 |
|
| 45 |
def make_class_name(formal_name): |
| 46 |
"""Construct a valid class name from a formal name. |
| 47 |
|
| 48 |
:param formal_name: The formal name |
| 49 |
:returns: The app's class name |
| 50 |
""" |
| 51 |
# Identifiers (including class names) can be unicode. |
| 52 |
# https://docs.python.org/3/reference/lexical_analysis.html#identifiers |
| 53 |
xid_start = { |
| 54 |
"Lu", # uppercase letters |
| 55 |
"Ll", # lowercase letters |
| 56 |
"Lt", # titlecase letters |
| 57 |
"Lm", # modifier letters |
| 58 |
"Lo", # other letters |
| 59 |
"Nl", # letter numbers |
| 60 |
} |
| 61 |
xid_continue = xid_start.union( |
| 62 |
{ |
| 63 |
"Mn", # nonspacing marks |
| 64 |
"Mc", # spacing combining marks |
| 65 |
"Nd", # decimal number |
| 66 |
"Pc", # connector punctuation |
| 67 |
} |
| 68 |
) |
| 69 |
|
| 70 |
# Normalize to NFKC form, then remove any character that isn't |
| 71 |
# in the allowed categories, or is the underscore character; |
| 72 |
# Capitalize the resulting word. |
| 73 |
class_name = "".join( |
| 74 |
ch |
| 75 |
for ch in unicodedata.normalize("NFKC", formal_name) |
| 76 |
if unicodedata.category(ch) in xid_continue or ch == "_" |
| 77 |
) |
| 78 |
|
| 79 |
# If the first character isn't in the 'start' character set, |
| 80 |
# and it isn't already an underscore, prepend an underscore. |
| 81 |
if ( |
| 82 |
class_name |
| 83 |
and unicodedata.category(class_name[0]) not in xid_start |
| 84 |
and class_name[0] != "_" |
| 85 |
): |
| 86 |
class_name = f"_{class_name}" |
| 87 |
|
| 88 |
return class_name |
| 89 |
|
| 90 |
|
| 91 |
def validate_url(candidate): |
| 92 |
"""Determine if the URL is valid. |
| 93 |
|
| 94 |
:param candidate: The candidate URL |
| 95 |
:returns: True. If there are any validation problems, raises ValueError with a |
| 96 |
diagnostic message. |
| 97 |
""" |
| 98 |
result = urlparse(candidate) |
| 99 |
if not all([result.scheme, result.netloc]): |
| 100 |
raise ValueError("Not a valid URL!") |
| 101 |
if result.scheme not in {"http", "https"}: |
| 102 |
raise ValueError("Not a valid website URL!") |
| 103 |
return True |
| 104 |
|
| 105 |
|
| 106 |
def validate_document_type_config(document_type_id, document_type): |
| 107 |
try: |
| 108 |
if not ( |
| 109 |
isinstance(document_type["extension"], str) |
| 110 |
and document_type["extension"].isalnum() |
| 111 |
): |
| 112 |
raise BriefcaseConfigError( |
| 113 |
f"The extension provided for document type " |
| 114 |
f"{document_type_id!r} is not alphanumeric." |
| 115 |
) |
| 116 |
except KeyError: |
| 117 |
raise BriefcaseConfigError( |
| 118 |
f"Document type {document_type_id!r} does not provide an extension." |
| 119 |
) from None |
| 120 |
|
| 121 |
try: |
| 122 |
if not isinstance(document_type["icon"], str): |
| 123 |
raise BriefcaseConfigError( |
| 124 |
f"The icon definition associated with document type " |
| 125 |
f"{document_type_id!r} is not a string." |
| 126 |
) |
| 127 |
except KeyError: |
| 128 |
raise BriefcaseConfigError( |
| 129 |
f"Document type {document_type_id!r} does not define an icon." |
| 130 |
) from None |
| 131 |
|
| 132 |
try: |
| 133 |
if not isinstance(document_type["description"], str): |
| 134 |
raise BriefcaseConfigError( |
| 135 |
f"The description associated with document type " |
| 136 |
f"{document_type_id!r} is not a string." |
| 137 |
) |
| 138 |
except KeyError: |
| 139 |
raise BriefcaseConfigError( |
| 140 |
f"Document type {document_type_id!r} does not provide a description." |
| 141 |
) from None |
| 142 |
|
| 143 |
try: |
| 144 |
validate_url(document_type["url"]) |
| 145 |
except KeyError: |
| 146 |
raise BriefcaseConfigError( |
| 147 |
f"Document type {document_type_id!r} does not provide a URL." |
| 148 |
) from None |
| 149 |
except ValueError as e: |
| 150 |
raise BriefcaseConfigError( |
| 151 |
f"The URL associated with document type {document_type_id!r} " |
| 152 |
f"is invalid: {e}" |
| 153 |
) from None |
| 154 |
|
| 155 |
if sys.platform == "darwin": # pragma: no-cover-if-not-macos |
| 156 |
from briefcase.platforms.macOS.utils import is_uti_core_type, mime_type_to_uti |
| 157 |
|
| 158 |
macOS = document_type.setdefault("macOS", {}) |
| 159 |
content_types = macOS.get("LSItemContentTypes", None) |
| 160 |
mime_type = document_type.get("mime_type", None) |
| 161 |
|
| 162 |
if isinstance(content_types, list): |
| 163 |
if len(content_types) > 1: |
| 164 |
raise BriefcaseConfigError( |
| 165 |
f""" |
| 166 |
Document type {document_type_id!r} has multiple content types. Specifying |
| 167 |
multiple values in a LSItemContentTypes key is only valid when multiple document |
| 168 |
types are manually grouped together in the Info.plist file. For Briefcase apps, |
| 169 |
document types are always separately declared in the configuration file, so only |
| 170 |
a single value should be provided. |
| 171 |
""" |
| 172 |
) |
| 173 |
|
| 174 |
macOS["LSItemContentTypes"] = content_types |
| 175 |
uti = content_types[0] |
| 176 |
elif isinstance(content_types, str): |
| 177 |
# If the content type is a string, convert it to a list |
| 178 |
macOS["LSItemContentTypes"] = [content_types] |
| 179 |
uti = content_types |
| 180 |
else: |
| 181 |
uti = None |
| 182 |
|
| 183 |
# If an UTI is provided in LSItemContentTypes, |
| 184 |
# that takes precedence over a MIME type |
| 185 |
if is_uti_core_type(uti) or ((uti := mime_type_to_uti(mime_type)) is not None): |
| 186 |
macOS.setdefault("is_core_type", True) |
| 187 |
macOS.setdefault("LSItemContentTypes", [uti]) |
| 188 |
macOS.setdefault("LSHandlerRank", "Alternate") |
| 189 |
else: |
| 190 |
# LSItemContentTypes will default to bundle.app_name.document_type_id |
| 191 |
# in the Info.plist template if it is not provided. |
| 192 |
macOS.setdefault("is_core_type", False) |
| 193 |
macOS.setdefault("LSHandlerRank", "Owner") |
| 194 |
macOS.setdefault("UTTypeConformsTo", ["public.data", "public.content"]) |
| 195 |
|
| 196 |
macOS.setdefault("CFBundleTypeRole", "Viewer") |
| 197 |
else: # pragma: no-cover-if-is-macos |
| 198 |
pass |
| 199 |
|
| 200 |
|
| 201 |
def validate_install_options_config(config, opt_type, **others): |
| 202 |
"""Validate that install/uninstall options are valid and complete, and convert to a |
| 203 |
dict. |
| 204 |
|
| 205 |
The dict format is required because Cookiecutter doesn't allow passing a list as a |
| 206 |
context value; you have to use the reliable iteration order of a dict instead. |
| 207 |
|
| 208 |
:param config: The table form of options |
| 209 |
:param opt_type: The label of the option type being parsed ("install" or |
| 210 |
"uninstall") |
| 211 |
:param others: A dictionary of other parsed option types. The keys are |
| 212 |
the option types, and the values are the dictionary of parse options. Options |
| 213 |
in `config` must be unique against these keys. |
| 214 |
""" |
| 215 |
options = {} |
| 216 |
known_names = set() |
| 217 |
if config: |
| 218 |
for i, config_item in enumerate(config): |
| 219 |
try: |
| 220 |
name = config_item["name"] |
| 221 |
if not isinstance(name, str): |
| 222 |
raise BriefcaseConfigError( |
| 223 |
f"Name for {opt_type} option {i} is not a string." |
| 224 |
) |
| 225 |
except KeyError: |
| 226 |
raise BriefcaseConfigError( |
| 227 |
f"{opt_type.title()} option {i} does not define a `name`." |
| 228 |
) from None |
| 229 |
|
| 230 |
# Options must be valid Python identifiers |
| 231 |
if not name.isidentifier(): |
| 232 |
raise BriefcaseConfigError( |
| 233 |
f"{name!r} cannot be used as an {opt_type} option name, " |
| 234 |
"as it is not a valid Python identifier." |
| 235 |
) |
| 236 |
|
| 237 |
# Option names may be coerced into upper case; and there are |
| 238 |
# a small number of reserved identifiers. |
| 239 |
if name.upper() == "ALLUSERS": |
| 240 |
raise BriefcaseConfigError( |
| 241 |
f"{name!r} is a reserved {opt_type} option identifier." |
| 242 |
) |
| 243 |
|
| 244 |
option = {} |
| 245 |
if name.upper() in known_names: |
| 246 |
raise BriefcaseConfigError( |
| 247 |
f"{opt_type.title()} option names must be unique. The name " |
| 248 |
f"{name!r}, used by {opt_type} option {i}, has already " |
| 249 |
"been defined." |
| 250 |
) |
| 251 |
else: |
| 252 |
for other_type, other_options in others.items(): |
| 253 |
if name.upper() in {n.upper() for n in other_options}: |
| 254 |
raise BriefcaseConfigError( |
| 255 |
f"{opt_type.title()} option names must be unique. The name " |
| 256 |
f"{name!r} is already used as an {other_type} option." |
| 257 |
) |
| 258 |
|
| 259 |
# options needs to retain the original name, but we need names to be |
| 260 |
# case-unique as well, so we track a separate set of known upper case names. |
| 261 |
known_names.add(name.upper()) |
| 262 |
options[name] = option |
| 263 |
|
| 264 |
try: |
| 265 |
# Options must have a string title. |
| 266 |
option["title"] = config_item["title"] |
| 267 |
if not isinstance(option["title"], str): |
| 268 |
raise BriefcaseConfigError( |
| 269 |
f"Title for {opt_type} option {name!r} is not a string." |
| 270 |
) |
| 271 |
except KeyError: |
| 272 |
raise BriefcaseConfigError( |
| 273 |
f"{opt_type.title()} option {name!r} does not provide a title." |
| 274 |
) from None |
| 275 |
|
| 276 |
try: |
| 277 |
# Options must have a string title. |
| 278 |
option["description"] = config_item["description"] |
| 279 |
if not isinstance(option["description"], str): |
| 280 |
raise BriefcaseConfigError( |
| 281 |
f"Description for {opt_type} option {name!r} is not a string." |
| 282 |
) |
| 283 |
except KeyError: |
| 284 |
raise BriefcaseConfigError( |
| 285 |
f"{opt_type.title()} option {name!r} does not provide " |
| 286 |
"a description." |
| 287 |
) from None |
| 288 |
|
| 289 |
# Options are booleans, and are False by default |
| 290 |
option["default"] = bool(config_item.get("default", False)) |
| 291 |
|
| 292 |
return options |
| 293 |
|
| 294 |
|
| 295 |
VALID_BUNDLE_RE = re.compile(r"[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$") |
| 296 |
|
| 297 |
|
| 298 |
def is_valid_bundle_identifier(bundle): |
| 299 |
"""Check if the bundle identifier follows the basic reversed domain name pattern.""" |
| 300 |
return VALID_BUNDLE_RE.match(bundle) is not None |
| 301 |
|
| 302 |
|
| 303 |
def parse_boolean(value: str) -> bool: |
| 304 |
"""Takes a string value and attempts to convert to a boolean value.""" |
| 305 |
|
| 306 |
truth_vals = {"true", "t", "yes", "y", "1", "on"} |
| 307 |
false_vals = {"false", "f", "no", "n", "0", "off"} |
| 308 |
|
| 309 |
normalised_val = value.strip().lower() |
| 310 |
|
| 311 |
if normalised_val in truth_vals: |
| 312 |
return True |
| 313 |
elif normalised_val in false_vals: |
| 314 |
return False |
| 315 |
else: |
| 316 |
raise ValueError( |
| 317 |
f"Invalid boolean value: {value!r}. " |
| 318 |
f"Expected one of {truth_vals | false_vals}" |
| 319 |
) |
| 320 |
|
| 321 |
|
| 322 |
class BaseConfig: |
| 323 |
def __init__(self, **kwargs): |
| 324 |
for attr, value in kwargs.items(): |
| 325 |
setattr(self, attr, value) |
| 326 |
|
| 327 |
def update(self, data): |
| 328 |
"""Add fields and values from data to BaseConfig instance. |
| 329 |
|
| 330 |
Any existing fields named in data will be overwritten. To merge |
| 331 |
data with existing configs, use the `merge_config` function. |
| 332 |
|
| 333 |
:param data: The new configuration data dictionary. |
| 334 |
""" |
| 335 |
for key, configs in data.items(): |
| 336 |
setattr(self, key, configs) |
| 337 |
|
| 338 |
def copy(self): |
| 339 |
return type(self)(**self.__dict__) |
| 340 |
|
| 341 |
def setdefault(self, field_name, default_value): |
| 342 |
"""Return the field_name field or, if it does not exist, create it to hold |
| 343 |
default_value. |
| 344 |
|
| 345 |
Behaves similarly to dict.setdefault(). |
| 346 |
|
| 347 |
:param field_name: The name of the desired/new field. |
| 348 |
:param default_value: The value to assign to self.field_name if it does not |
| 349 |
already exist. |
| 350 |
""" |
| 351 |
if not hasattr(self, field_name): |
| 352 |
setattr(self, field_name, default_value) |
| 353 |
|
| 354 |
return getattr(self, field_name) |
| 355 |
|
| 356 |
|
| 357 |
class GlobalConfig(BaseConfig): |
| 358 |
def __init__( |
| 359 |
self, |
| 360 |
project_name, |
| 361 |
version, |
| 362 |
bundle, |
| 363 |
license=None, |
| 364 |
url=None, |
| 365 |
author=None, |
| 366 |
author_email=None, |
| 367 |
requires_python=None, |
| 368 |
**kwargs, |
| 369 |
): |
| 370 |
super().__init__(**kwargs) |
| 371 |
self.project_name = project_name |
| 372 |
self.version = version |
| 373 |
self.bundle = bundle |
| 374 |
self.url = url |
| 375 |
self.author = author |
| 376 |
self.author_email = author_email |
| 377 |
self.license = license |
| 378 |
self.requires_python = requires_python |
| 379 |
|
| 380 |
# Version number is compliant with PEP440 (and related updates): |
| 381 |
try: |
| 382 |
# If input is already a version object (can happen by copying), use as-is |
| 383 |
if isinstance(version, Version): |
| 384 |
self.version = version |
| 385 |
else: |
| 386 |
self.version = Version(version) |
| 387 |
except InvalidVersion: |
| 388 |
raise InvalidVersionError( |
| 389 |
f"Version number ({self.version}) is not valid." |
| 390 |
) from None |
| 391 |
|
| 392 |
def __repr__(self): |
| 393 |
return f"<{self.project_name} v{self.version} GlobalConfig>" |
| 394 |
|
| 395 |
|
| 396 |
class AppConfig(BaseConfig): |
| 397 |
def __init__( |
| 398 |
self, |
| 399 |
app_name, |
| 400 |
version, |
| 401 |
bundle, |
| 402 |
description, |
| 403 |
license, |
| 404 |
sources=None, |
| 405 |
formal_name=None, |
| 406 |
url=None, |
| 407 |
author=None, |
| 408 |
author_email=None, |
| 409 |
requires=None, |
| 410 |
icon=None, |
| 411 |
document_type=None, |
| 412 |
install_option=None, |
| 413 |
uninstall_option=None, |
| 414 |
permission=None, |
| 415 |
template=None, |
| 416 |
template_branch=None, |
| 417 |
test_sources=None, |
| 418 |
test_requires=None, |
| 419 |
supported=True, |
| 420 |
long_description=None, |
| 421 |
console_app=False, |
| 422 |
requirement_installer_args: list[str] | None = None, |
| 423 |
external_package_path: str | None = None, |
| 424 |
external_package_executable_path: str | None = None, |
| 425 |
install_launcher: bool | None = None, |
| 426 |
**kwargs, |
| 427 |
): |
| 428 |
super().__init__(**kwargs) |
| 429 |
|
| 430 |
# All app configs are created in unfinalized draft form. |
| 431 |
self.__draft__ = True |
| 432 |
|
| 433 |
self.app_name = app_name |
| 434 |
self.version = version |
| 435 |
self.bundle = bundle.lower() |
| 436 |
# Description can only be a single line. Ignore everything else. |
| 437 |
self.description = description.split("\n")[0] |
| 438 |
self.sources = sources |
| 439 |
self.formal_name = app_name if formal_name is None else formal_name |
| 440 |
self.url = url |
| 441 |
self.author = author |
| 442 |
self.author_email = author_email |
| 443 |
self.requires = requires |
| 444 |
self.icon = icon |
| 445 |
self.document_types = {} if document_type is None else document_type |
| 446 |
self.permission = {} if permission is None else permission |
| 447 |
self.template = template |
| 448 |
self.template_branch = template_branch |
| 449 |
self.test_sources = test_sources |
| 450 |
self.test_requires = test_requires |
| 451 |
self.supported = supported |
| 452 |
self.long_description = long_description |
| 453 |
self.license = license |
| 454 |
self.console_app = console_app |
| 455 |
self.requirement_installer_args = ( |
| 456 |
[] if requirement_installer_args is None else requirement_installer_args |
| 457 |
) |
| 458 |
self.external_package_path = external_package_path |
| 459 |
self.external_package_executable_path = external_package_executable_path |
| 460 |
self.install_launcher = ( |
| 461 |
install_launcher if (install_launcher is not None) else (not console_app) |
| 462 |
) |
| 463 |
|
| 464 |
self.test_mode: bool = False |
| 465 |
|
| 466 |
self.debugger: BaseDebugger | None = None |
| 467 |
self.debugger_host: str | None = None # only for run command |
| 468 |
self.debugger_port: int | None = None # only for run command |
| 469 |
|
| 470 |
if not is_valid_app_name(self.app_name): |
| 471 |
raise BriefcaseConfigError( |
| 472 |
f"{self.app_name!r} is not a valid app name." |
| 473 |
f"\n\n" |
| 474 |
"App names must not be reserved keywords such as 'and', 'for' and " |
| 475 |
"'while'. They must also be PEP508 compliant (i.e., they can only " |
| 476 |
"include letters, numbers, '-' and '_'; must start with a letter; " |
| 477 |
"and cannot end with '-' or '_')." |
| 478 |
) |
| 479 |
|
| 480 |
if not is_valid_bundle_identifier(self.bundle): |
| 481 |
raise BriefcaseConfigError( |
| 482 |
f"{self.bundle!r} is not a valid bundle identifier." |
| 483 |
f"\n\n" |
| 484 |
"The bundle should be a reversed domain name. It must contain at least " |
| 485 |
"2 dot-separated sections; each section may only include letters, " |
| 486 |
"numbers, and hyphens; and each section may not contain any reserved " |
| 487 |
"words (like 'switch', or 'while')." |
| 488 |
) |
| 489 |
|
| 490 |
for document_type_id, document_type in self.document_types.items(): |
| 491 |
validate_document_type_config(document_type_id, document_type) |
| 492 |
|
| 493 |
self.install_options = validate_install_options_config( |
| 494 |
install_option, "install" |
| 495 |
) |
| 496 |
self.uninstall_options = validate_install_options_config( |
| 497 |
uninstall_option, |
| 498 |
"uininstall", |
| 499 |
install=self.install_options, |
| 500 |
) |
| 501 |
|
| 502 |
# Version number is compliant with PEP440 (and related updates): |
| 503 |
try: |
| 504 |
# If input is already a version object (can happen by copying), use as-is |
| 505 |
if isinstance(version, Version): |
| 506 |
self.version = version |
| 507 |
else: |
| 508 |
self.version = Version(version) |
| 509 |
except InvalidVersion: |
| 510 |
raise InvalidVersionError( |
| 511 |
f"Version number for {self.app_name!r} ({self.version}) is not valid." |
| 512 |
) from None |
| 513 |
|
| 514 |
if self.sources: |
| 515 |
# Sources list doesn't include any duplicates |
| 516 |
source_modules = {source.rsplit("/", 1)[-1] for source in self.sources} |
| 517 |
if len(self.sources) != len(source_modules): |
| 518 |
raise BriefcaseConfigError( |
| 519 |
f"The `sources` list for {self.app_name!r} contains duplicated " |
| 520 |
"package names." |
| 521 |
) |
| 522 |
|
| 523 |
# There is, at least, a source for the app module |
| 524 |
if self.module_name not in source_modules: |
| 525 |
raise BriefcaseConfigError( |
| 526 |
f"The `sources` list for {self.app_name!r} does not include a " |
| 527 |
f"package named {self.module_name!r}." |
| 528 |
) |
| 529 |
|
| 530 |
def __repr__(self): |
| 531 |
return f"<{self.bundle_identifier} v{self.version} AppConfig>" |
| 532 |
|
| 533 |
@property |
| 534 |
def module_name(self): |
| 535 |
"""The module name for the app. |
| 536 |
|
| 537 |
This is derived from the name, but: |
| 538 |
* all `-` have been replaced with `_`. |
| 539 |
""" |
| 540 |
return self.app_name.replace("-", "_") |
| 541 |
|
| 542 |
@property |
| 543 |
def bundle_name(self): |
| 544 |
"""The bundle name for the app. |
| 545 |
|
| 546 |
This is derived from the app name, but: |
| 547 |
* all `_` have been replaced with `-`. |
| 548 |
""" |
| 549 |
return self.app_name.replace("_", "-").lower() |
| 550 |
|
| 551 |
@property |
| 552 |
def bundle_identifier(self): |
| 553 |
"""The bundle identifier for the app. |
| 554 |
|
| 555 |
This is derived from the bundle and the bundle name, joined by a `.`. |
| 556 |
""" |
| 557 |
return f"{self.bundle}.{self.bundle_name}" |
| 558 |
|
| 559 |
@property |
| 560 |
def class_name(self): |
| 561 |
"""The class name for the app. |
| 562 |
|
| 563 |
This is derived from the formal name for the app. |
| 564 |
""" |
| 565 |
return make_class_name(self.formal_name) |
| 566 |
|
| 567 |
@property |
| 568 |
def package_name(self): |
| 569 |
"""The bundle name of the app, with `-` replaced with `_` to create something |
| 570 |
that can be used a namespace identifier on Python or Java, similar to |
| 571 |
`module_name`.""" |
| 572 |
return self.bundle.replace("-", "_") |
| 573 |
|
| 574 |
@property |
| 575 |
def dist_info_name(self): |
| 576 |
"""The name of the .dist-info directory for the app.""" |
| 577 |
return f"{self.module_name}.dist-info" |
| 578 |
|
| 579 |
def PYTHONPATH(self): |
| 580 |
"""The PYTHONPATH modifications needed to run this app.""" |
| 581 |
paths = [] |
| 582 |
sources = self.sources.copy() if self.sources else [] |
| 583 |
if self.test_mode and self.test_sources: |
| 584 |
sources.extend(self.test_sources) |
| 585 |
|
| 586 |
for source in sources: |
| 587 |
path = "/".join(source.rsplit("/", 1)[:-1]) |
| 588 |
if path not in paths: |
| 589 |
paths.append(path) |
| 590 |
return paths |
| 591 |
|
| 592 |
def all_sources(self) -> list[str]: |
| 593 |
"""Get all sources of the application that should be copied to the app. |
| 594 |
|
| 595 |
:returns: The Path to the dist-info folder. |
| 596 |
""" |
| 597 |
sources = self.sources.copy() if self.sources else [] |
| 598 |
if self.test_mode and self.test_sources: |
| 599 |
sources.extend(self.test_sources) |
| 600 |
return sources |
| 601 |
|
| 602 |
def main_module(self): |
| 603 |
"""The path to the main module for the app. |
| 604 |
|
| 605 |
In normal operation, this is ``app.module_name``; however, |
| 606 |
in test mode, it is prefixed with ``tests.``. |
| 607 |
""" |
| 608 |
if self.test_mode: |
| 609 |
return f"tests.{self.module_name}" |
| 610 |
else: |
| 611 |
return self.module_name |
| 612 |
|
| 613 |
|
| 614 |
def merge_config(config, data): |
| 615 |
"""Merge a new set of configuration requirements into a base configuration. |
| 616 |
|
| 617 |
:param config: the base configuration to update. This configuration is modified in- |
| 618 |
situ. |
| 619 |
:param data: The new configuration data to merge into the configuration. |
| 620 |
""" |
| 621 |
# Properties that are cumulative lists |
| 622 |
for option in [ |
| 623 |
"requires", |
| 624 |
"sources", |
| 625 |
"test_requires", |
| 626 |
"test_sources", |
| 627 |
]: |
| 628 |
value = data.pop(option, []) |
| 629 |
|
| 630 |
if value: |
| 631 |
config.setdefault(option, []).extend(value) |
| 632 |
|
| 633 |
# Properties that are cumulative tables |
| 634 |
for option in ["permission"]: |
| 635 |
value = data.pop(option, {}) |
| 636 |
|
| 637 |
if value: |
| 638 |
config.setdefault(option, {}).update(value) |
| 639 |
|
| 640 |
config.update(data) |
| 641 |
|
| 642 |
|
| 643 |
def merge_pep621_config(global_config, pep621_config): |
| 644 |
"""Merge a PEP621 configuration into a Briefcase configuration.""" |
| 645 |
|
| 646 |
if requires_python := pep621_config.get("requires-python"): |
| 647 |
global_config["requires_python"] = requires_python |
| 648 |
|
| 649 |
def maybe_update(field, *project_fields): |
| 650 |
# If there's an existing key in the Briefcase config, it takes priority. |
| 651 |
if field in global_config: |
| 652 |
return |
| 653 |
|
| 654 |
# Traverse the fields in the pep621 config; if the config exists, set it |
| 655 |
# in the Briefcase config. |
| 656 |
datum = pep621_config |
| 657 |
try: |
| 658 |
for key in project_fields: |
| 659 |
datum = datum[key] |
| 660 |
except KeyError: |
| 661 |
pass |
| 662 |
else: |
| 663 |
global_config[field] = datum |
| 664 |
|
| 665 |
# Keys that map directly |
| 666 |
maybe_update("description", "description") |
| 667 |
maybe_update("license", "license") |
| 668 |
maybe_update("url", "urls", "Homepage") |
| 669 |
maybe_update("version", "version") |
| 670 |
|
| 671 |
# Use the details of the first author as the Briefcase author. |
| 672 |
if "author" not in global_config: |
| 673 |
try: |
| 674 |
global_config["author"] = pep621_config["authors"][0]["name"] |
| 675 |
except (KeyError, IndexError): |
| 676 |
pass |
| 677 |
if "author_email" not in global_config: |
| 678 |
try: |
| 679 |
global_config["author_email"] = pep621_config["authors"][0]["email"] |
| 680 |
except (KeyError, IndexError): |
| 681 |
pass |
| 682 |
|
| 683 |
# Briefcase requires is cumulative over PEP621 dependencies |
| 684 |
try: |
| 685 |
pep621_dependencies = pep621_config["dependencies"] |
| 686 |
requires = global_config.get("requires", []) |
| 687 |
global_config["requires"] = pep621_dependencies + requires |
| 688 |
except KeyError: |
| 689 |
pass |
| 690 |
|
| 691 |
# Briefcase test_requires is cumulative over PEP621 optional test dependencies |
| 692 |
try: |
| 693 |
pep621_test_dependencies = pep621_config["optional-dependencies"]["test"] |
| 694 |
test_requires = global_config.get("test_requires", []) |
| 695 |
global_config["test_requires"] = pep621_test_dependencies + test_requires |
| 696 |
except KeyError: |
| 697 |
pass |
| 698 |
|
| 699 |
|
| 700 |
def parse_config(config_file, platform, output_format, console): |
| 701 |
"""Parse the briefcase section of the pyproject.toml configuration file. |
| 702 |
|
| 703 |
This method only does basic structural parsing of the TOML, looking for, |
| 704 |
at a minimum, a ``[tool.briefcase.app.<appname>]`` section declaring the |
| 705 |
existence of a single app. It will also search for: |
| 706 |
|
| 707 |
* ``[tool.briefcase]`` - global briefcase settings |
| 708 |
* ``[tool.briefcase.app.<appname>]`` - settings specific to the app |
| 709 |
* ``[tool.briefcase.app.<appname>.<platform>]`` - settings specific to |
| 710 |
the platform |
| 711 |
* ``[tool.briefcase.app.<appname>.<platform>.<format>]`` - settings |
| 712 |
specific to the output format |
| 713 |
|
| 714 |
A configuration can define multiple apps; the final output is the merged |
| 715 |
content of the global, app, platform and output format settings |
| 716 |
for each app, with output format definitions taking precedence over |
| 717 |
platform, over app-level, over global. The final result is a single |
| 718 |
(mostly) flat dictionary for each app. |
| 719 |
|
| 720 |
:param config_file: A file-like object containing TOML to be parsed. |
| 721 |
:param platform: The platform being targeted |
| 722 |
:param output_format: The output format |
| 723 |
:param console: The console to use for any output or logging. |
| 724 |
:returns: A dictionary of configuration data. The top level dictionary is |
| 725 |
keyed by the names of the apps that are declared; each value is |
| 726 |
itself the configuration data merged from global, app, platform and |
| 727 |
format definitions. |
| 728 |
""" |
| 729 |
try: |
| 730 |
pyproject = tomllib.load(config_file) |
| 731 |
except tomllib.TOMLDecodeError as e: |
| 732 |
raise BriefcaseConfigError(f"Invalid pyproject.toml: {e}") from e |
| 733 |
|
| 734 |
try: |
| 735 |
global_config = pyproject["tool"]["briefcase"] |
| 736 |
except KeyError as e: |
| 737 |
raise BriefcaseConfigError("No tool.briefcase section in pyproject.toml") from e |
| 738 |
|
| 739 |
# Merge the PEP621 configuration (if it exists) |
| 740 |
try: |
| 741 |
merge_pep621_config(global_config, pyproject["project"]) |
| 742 |
except KeyError: |
| 743 |
pass |
| 744 |
|
| 745 |
# For consistent results, sort the platforms and formats |
| 746 |
all_platforms = sorted(get_platforms().keys()) |
| 747 |
all_formats = sorted(get_output_formats(platform).keys()) |
| 748 |
|
| 749 |
try: |
| 750 |
all_apps = global_config.pop("app") |
| 751 |
except KeyError as e: |
| 752 |
raise BriefcaseConfigError("No Briefcase apps defined in pyproject.toml") from e |
| 753 |
|
| 754 |
for name, config in [("project", global_config), *all_apps.items()]: |
| 755 |
if isinstance(config.get("license"), str): |
| 756 |
section_name = "the Project" if name == "project" else f"{name!r}" |
| 757 |
console.warning( |
| 758 |
f""" |
| 759 |
************************************************************************* |
| 760 |
** {f"WARNING: License Definition for {section_name} is Deprecated":67} ** |
| 761 |
************************************************************************* |
| 762 |
|
| 763 |
Briefcase now uses PEP 621 format for license definitions. |
| 764 |
|
| 765 |
Previously, the name of the license was assigned to the 'license' |
| 766 |
field in pyproject.toml. For PEP 621, the name of the license is |
| 767 |
assigned to 'license.text' or the name of the file containing the |
| 768 |
license is assigned to 'license.file'. |
| 769 |
|
| 770 |
The current configuration for {section_name} has a 'license' field |
| 771 |
that is specified as a string: |
| 772 |
|
| 773 |
license = "{config["license"]}" |
| 774 |
|
| 775 |
To use the PEP 621 format (and to remove this warning), specify that |
| 776 |
the LICENSE file contains the license for {section_name}: |
| 777 |
|
| 778 |
license.file = "LICENSE" |
| 779 |
|
| 780 |
************************************************************************* |
| 781 |
""" |
| 782 |
) |
| 783 |
config["license"] = {"file": "LICENSE"} |
| 784 |
|
| 785 |
# Build the flat configuration for each app, |
| 786 |
# based on the requested platform and output format |
| 787 |
app_configs = {} |
| 788 |
for app_name, app_data in all_apps.items(): |
| 789 |
# At this point, the base configuration will contain a section |
| 790 |
# for each configured platform. Iterate over all the known platforms, |
| 791 |
# and remove these platform configurations. Keep a copy of the platform |
| 792 |
# configuration if it matches the requested platform, and merge it |
| 793 |
# into the app's configuration |
| 794 |
platform_data = None |
| 795 |
for p in all_platforms: |
| 796 |
try: |
| 797 |
platform_block = app_data.pop(p) |
| 798 |
|
| 799 |
if p == platform: |
| 800 |
# If the platform matches the requested format, preserve |
| 801 |
# it for later use. |
| 802 |
platform_data = platform_block |
| 803 |
merge_config(platform_data, platform_data) |
| 804 |
|
| 805 |
# The platform configuration will contain a section |
| 806 |
# for each configured output format. Iterate over all |
| 807 |
# the output format of the platform, and remove these |
| 808 |
# output format configurations. Keep a copy of the output |
| 809 |
# format configuration if it matches the requested output |
| 810 |
# format, and merge it into the platform's configuration. |
| 811 |
format_data = None |
| 812 |
for f in all_formats: |
| 813 |
try: |
| 814 |
format_block = platform_data.pop(f) |
| 815 |
|
| 816 |
if f == output_format: |
| 817 |
# If the output format matches the requested |
| 818 |
# one, preserve it. |
| 819 |
format_data = format_block |
| 820 |
|
| 821 |
except KeyError: |
| 822 |
pass |
| 823 |
|
| 824 |
# If we found a specific configuration for the requested |
| 825 |
# output format, add it to the platform configuration, |
| 826 |
# overwriting any platform-level settings with format-level |
| 827 |
# values. |
| 828 |
if format_data: |
| 829 |
merge_config(platform_data, format_data) |
| 830 |
|
| 831 |
except KeyError: |
| 832 |
pass |
| 833 |
|
| 834 |
# Now construct the final configuration. |
| 835 |
# First, convert the requirement definition at the global level |
| 836 |
merge_config(global_config, global_config) |
| 837 |
|
| 838 |
# The app's config starts as a copy of the base briefcase configuration. |
| 839 |
config = copy.deepcopy(global_config) |
| 840 |
|
| 841 |
# The app name is both the key, and a property of the configuration |
| 842 |
config["app_name"] = app_name |
| 843 |
|
| 844 |
# Merge the app-specific requirements |
| 845 |
merge_config(config, app_data) |
| 846 |
|
| 847 |
# If there is platform-specific configuration, merge the requirements, |
| 848 |
# then overwrite the platform-specific values. |
| 849 |
# This will already include any format-specific configuration. |
| 850 |
if platform_data: |
| 851 |
merge_config(config, platform_data) |
| 852 |
|
| 853 |
# Construct a configuration object, and add it to the list |
| 854 |
# of configurations that are being handled. |
| 855 |
app_configs[app_name] = config |
| 856 |
|
| 857 |
return global_config, app_configs |