forked from beeware/briefcase
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path__init__.py
More file actions
637 lines (541 loc) · 23.5 KB
/
__init__.py
File metadata and controls
637 lines (541 loc) · 23.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
from __future__ import annotations
import re
import subprocess
import uuid
from collections.abc import Collection
from pathlib import Path, PurePath
from typing import TYPE_CHECKING
from zipfile import ZIP_DEFLATED, ZipFile
from briefcase.commands import CreateCommand, PackageCommand, RunCommand
from briefcase.config import FinalizedAppConfig
from briefcase.exceptions import (
BriefcaseCommandError,
BriefcaseConfigError,
UnsupportedHostError,
)
from briefcase.integrations.windows_sdk import WindowsSDK
from briefcase.integrations.wix import WiX
if TYPE_CHECKING:
from briefcase.commands.base import BaseCommand
_MixinBase = BaseCommand
else:
_MixinBase = object
DEFAULT_OUTPUT_FORMAT = "app"
def txt_to_rtf(txt: str | list[str]) -> str:
"""Convert plain text to a full RTF document.
The entire document is rendered in Courier. Any blank line is interpreted as a
paragraph marker; any line starting with a * is rendered as a bullet. Everything
else is rendered verbatim in the RTF document.
If a list of strings is provided, each string is converted to an RTF body section
and the sections are joined with an RTF horizontal-rule separator.
:param txt: The original plain text, either as a single string or a list of strings.
:returns: A complete RTF document string.
"""
RTF_HEADER = "{\\rtf1\\ansi\\deff0 {\\fonttbl {\\f0 Courier;}}"
RTF_SEPARATOR = "\\par\\line\\brdrb\\brdrs\\brdrw10\\brsp20\\par\\line"
texts = [txt] if isinstance(txt, str) else txt
bodies = []
for text in texts:
rtf = []
for line in text.split("\n"):
if line.lstrip().startswith("*"):
rtf.append(f"\\bullet{line[line.index('*') + 1 :]} ")
elif line:
# Add a space at the end to ensure multi-line paragraphs
# have a word break. Strip whitespace to ensure that
# indented bullet paragraphs don't have extra space.
rtf.append(line.strip() + " ")
else:
# A blank line is a paragraph+line break.
rtf.append("\\par\\line")
bodies.append("\n".join(rtf))
separator = f"\n{RTF_SEPARATOR}\n"
return f"{RTF_HEADER}\n{separator.join(bodies)}\n}}"
class WindowsMixin(_MixinBase):
platform = "windows"
supported_host_os: Collection[str] = {"Windows"}
supported_host_os_reason = "Windows applications can only be built on Windows."
platform_target_version = "0.3.24"
def bundle_package_executable_path(self, app):
if app.console_app:
return f"{app.app_name}.exe"
else:
return f"{app.formal_name}.exe"
def bundle_package_path(self, app):
return self.bundle_path(app) / self.packaging_root
def binary_path(self, app):
return self.package_path(app) / self.package_executable_path(app)
def distribution_path(self, app):
suffix = "zip" if app.packaging_format == "zip" else "msi"
return self.dist_path / f"{app.formal_name}-{app.version}.{suffix}"
@property
def vscode_platform(self):
return "ARM64" if self.tools.host_arch == "ARM64" else "x64"
def verify_host(self):
super().verify_host()
if (
self.tools.host_arch == "ARM64"
and "AMD64" in self.tools.platform.python_compiler()
):
raise UnsupportedHostError(
"The Python interpreter that is being used to run Briefcase has been "
"compiled for x86_64, and is running in emulation mode on ARM64 "
"hardware. You must use a Python interpreter that has been "
"compiled for ARM64."
)
if self.tools.host_arch not in ("AMD64", "ARM64"):
if all(app.external_package_path for app in self.apps.values()):
if not self.is_clone:
self.console.warning(f"""
*************************************************************************
** WARNING: Possible architecture mismatch **
*************************************************************************
The build machine is {self.tools.host_arch}, but Briefcase on Windows only
supports x86-64 and ARM64 installers.
You are responsible for ensuring that the content of external_package_path
is compatible with supported platforms.
*************************************************************************
""")
else:
raise UnsupportedHostError(
"Windows applications cannot be built on an "
f"{self.tools.host_arch} machine."
)
# 64bit Python is required to ensure 64bit wheels are installed/created
# for the app
if self.tools.is_32bit_python:
raise UnsupportedHostError("""\
Windows applications cannot be built using a 32bit version of Python.
Install a 64bit version of Python and run Briefcase again.
""")
class WindowsCreateCommand(CreateCommand):
def support_package_filename(self, support_revision):
arch = self.tools.host_arch.lower()
return f"python-{self.python_version_tag}.{support_revision}-embed-{arch}.zip"
def support_package_url(self, support_revision):
micro = re.match(r"\d+", str(support_revision)).group(0)
return (
"https://www.python.org/ftp/python/"
f"{self.python_version_tag}.{micro}/"
f"{self.support_package_filename(support_revision)}"
)
def extras_path(self, app: FinalizedAppConfig) -> Path:
"""Obtain the path for extra installer content.
Extra installer content is content that needs to be inserted into the installer,
in addition to material in the packaging path. It is primarily used to add
installer scripts when packaging an externally managed app.
:param app: The config object for the app
:return: The full path where install scripts should be installed.
"""
try:
extras_path = self.path_index(app, "extras_path")
except KeyError:
# For backwards compatibility - if the template doesn't define an extras
# path, default to `extras`.
extras_path = "extras"
return self.bundle_path(app) / extras_path
def output_format_template_context(self, app: FinalizedAppConfig):
"""Additional template context required by the output format.
:param app: The config object for the app
"""
# WiX requires a 3-element, integer-only version number. If a version
# triple isn't explicitly provided, generate one by stripping any
# non-numeric portions from the version number.
# If there are less than 3 numeric parts, 0s will be appended.
try:
version_triple = app.version_triple
except AttributeError:
version_triple = ".".join(
([str(v) for v in app.version.release] + ["0", "0"])[:3]
)
# The application needs a unique GUID.
# This is used to track the application, even if the application
# name changes. We can generate a default GUID using the bundle
# and the formal name; but you'll need to manually set this value
# if you ever change those two keys.
try:
guid = app.guid
except AttributeError:
# Create a DNS domain by reversing the bundle identifier
domain = ".".join(app.bundle_identifier.split(".")[::-1])
guid = uuid.uuid5(uuid.NAMESPACE_DNS, domain)
self.console.info(f"Assigning {app.app_name} an application GUID of {guid}")
try:
install_scope = "perMachine" if app.system_installer else "perUser"
except AttributeError:
# system_installer not defined in config; default to asking the user
install_scope = "perUserOrMachine"
return {
"version_triple": version_triple,
"guid": str(guid),
"install_scope": install_scope,
"package_path": str(self.package_path(app)),
"binary_path": self.package_executable_path(app),
}
def _cleanup_app_support_package(self, support_path):
# On Windows, the support path is co-mingled with app content.
# This means updating the support package is imperfect.
# Warn the user that there could be problems.
self.console.warning("""
*************************************************************************
** WARNING: Support package update may be imperfect **
*************************************************************************
Support packages in Windows apps are overlaid with app content,
so it isn't possible to remove all old support files before
installing new ones.
Briefcase will unpack the new support package without cleaning up
existing support package content. This *should* work; however,
ensure a reproducible release artefacts, it is advisable to
perform a clean app build before release.
*************************************************************************
""")
def install_license(self, app: FinalizedAppConfig):
"""Install the license for the project as a single RTF document.
The following cases are handled:
- Single ``.rtf`` file: copied directly without any transformation.
- Single non-``.rtf`` file: converted to RTF via ``txt_to_rtf()``.
- Multiple files, all non-``.rtf``: converted and merged with a
separator via ``txt_to_rtf()``.
- Multiple files where any is ``.rtf``, or a mix of ``.rtf`` and
non-``.rtf``: raises ``BriefcaseConfigError``.
:param app: The config object for the app
"""
installed_license = self.bundle_path(app) / "LICENSE.rtf"
rtf_files = [
p for p in app.license_files if (self.base_path / p).suffix == ".rtf"
]
if len(app.license_files) == 0:
raise BriefcaseCommandError("""\
Your project does not include any license files.
Ensure your `pyproject.toml` is in PEP 639 format and specifies at least
one file in the `license-files` setting.
""")
elif len(app.license_files) == 1:
license_file = self.base_path / app.license_files[0]
if license_file.suffix == ".rtf":
# Single RTF file: copy directly.
self.tools.shutil.copy(license_file, installed_license)
return
else:
# Single text file: convert to full RTF document.
installed_license.write_text(
txt_to_rtf(license_file.read_text(encoding="utf-8")),
encoding="utf-8",
)
return
# Multiple files.
if rtf_files:
raise BriefcaseConfigError(f"""\
The license configuration for {app.app_name!r} contains multiple
license files, and at least one is an RTF file. Briefcase cannot
automatically merge RTF license files.
Either provide a single RTF file, or provide only plain-text license
files that Briefcase can convert and merge automatically.
""")
# Multiple non-RTF files: convert each and merge via txt_to_rtf().
texts = [
(self.base_path / p).read_text(encoding="utf-8") for p in app.license_files
]
installed_license.write_text(txt_to_rtf(texts), encoding="utf-8")
def install_app_resources(self, app: FinalizedAppConfig):
"""Install Windows-specific app resources.
This includes any post-install or pre-uninstall scripts, plus converting the
LICENSE file into an RTF file.
:param app: The config object for the app
"""
super().install_app_resources(app)
installer_path = getattr(app, "installer_path", "_installer")
install_scripts_path = self.extras_path(app) / installer_path
# Ensure the extras path exists, so that the path used by WiX exists
self.extras_path(app).mkdir(exist_ok=True, parents=True)
# Install the post-install script
if post_install := getattr(app, "post_install_script", None):
post_install_script = self.base_path / post_install
if post_install_script.suffix != ".bat":
raise BriefcaseCommandError(
"Windows post-install scripts must be .bat files."
)
elif not post_install_script.is_file():
raise BriefcaseCommandError(
f"Couldn't find post-install script {post_install}."
)
with self.console.wait_bar("Installing post-install script..."):
install_scripts_path.mkdir(exist_ok=True, parents=True)
self.tools.shutil.copyfile(
post_install_script,
install_scripts_path / "post_install.bat",
)
# Install the pre-uninstall script
if pre_uninstall := getattr(app, "pre_uninstall_script", None):
pre_uninstall_script = self.base_path / pre_uninstall
if pre_uninstall_script.suffix != ".bat":
raise BriefcaseCommandError(
"Windows pre-uninstall scripts must be .bat files."
)
elif not pre_uninstall_script.is_file():
raise BriefcaseCommandError(
f"Couldn't find pre-uninstall script {pre_uninstall}."
)
with self.console.wait_bar("Installing pre-uninstall script..."):
install_scripts_path.mkdir(exist_ok=True, parents=True)
self.tools.shutil.copyfile(
pre_uninstall_script,
install_scripts_path / "pre_uninstall.bat",
)
# Install the license.
with self.console.wait_bar("Installing license..."):
self.install_license(app)
class WindowsRunCommand(RunCommand):
supports_debugger = True
def run_app(
self,
app: FinalizedAppConfig,
passthrough: list[str],
**kwargs,
):
"""Start the application.
:param app: The config object for the app
:param passthrough: The list of arguments to pass to the app
"""
# Set up the log stream
kwargs = self._prepare_app_kwargs(app=app)
# Console apps must operate in non-streaming mode so that console input can
# be handled correctly. However, if we're in test mode, we *must* stream so
# that we can see the test exit sentinel
if app.console_app and not app.test_mode:
self.console.info("=" * 75)
self.tools.subprocess.run(
[self.binary_path(app), *passthrough],
cwd=self.tools.home_path,
encoding="UTF-8",
bufsize=1,
stream_output=False,
**kwargs,
)
else:
# Start the app in a way that lets us stream the logs
app_popen = self.tools.subprocess.Popen(
[self.binary_path(app), *passthrough],
cwd=self.tools.home_path,
encoding="UTF-8",
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
bufsize=1,
**kwargs,
)
# Start streaming logs for the app.
self._stream_app_logs(
app,
popen=app_popen,
clean_output=False,
)
class WindowsPackageCommand(PackageCommand):
ADHOC_SIGN_HELP = (
"Perform no signing on the app. "
"Your app will be reported as coming from an unverified publisher."
)
IDENTITY_HELP = "The 40-digit hex checksum of the code signing identity to use"
@property
def packaging_formats(self):
return ["msi", "zip"]
@property
def default_packaging_format(self):
return "msi"
def verify_tools(self):
super().verify_tools()
WiX.verify(tools=self.tools)
if self._windows_sdk_needed:
WindowsSDK.verify(tools=self.tools)
def add_options(self, parser):
super().add_options(parser)
parser.add_argument(
"--file-digest",
help="File digest algorithm to use for code signing; defaults to sha256",
default="sha256",
required=False,
)
parser.add_argument(
"--use-local-machine-stores",
help=(
"Specifies the code signing certificate is stored in the "
"Local Machine's stores instead of the Current User's"
),
action="store_true",
dest="use_local_machine",
required=False,
)
parser.add_argument(
"--cert-store",
help=(
"The internal Windows name for the certificate store containing the "
"certificate for code signing; defaults to 'My' for the Personal store"
),
default="My",
required=False,
)
parser.add_argument(
"--timestamp-url",
help=(
"URL for the Timestamp Authority server to timestamp the code signing; "
"defaults to timestamp.digicert.com"
),
default="http://timestamp.digicert.com",
required=False,
)
parser.add_argument(
"--timestamp-digest",
help=(
"Digest algorithm to request the Timestamp Authority server uses "
"for the timestamp for code signing; defaults to sha256"
),
default="sha256",
required=False,
)
def parse_options(self, extra):
"""Require the Windows SDK tool if an `identity` is specified for signing."""
options, overrides = super().parse_options(extra=extra)
self._windows_sdk_needed = options["identity"] is not None
return options, overrides
def sign_file(
self,
app: FinalizedAppConfig,
filepath: Path,
identity: str,
file_digest: str,
use_local_machine: bool,
cert_store: str,
timestamp_url: str,
timestamp_digest: str,
):
"""Sign a file."""
if not re.fullmatch(r"^[0-9a-f]{40}$", identity, flags=re.IGNORECASE):
raise BriefcaseCommandError(
f"Codesigning identify {identity!r} must be a "
"certificate SHA-1 thumbprint."
)
sign_command = [
self.tools.windows_sdk.signtool_exe,
"sign",
"-s",
cert_store,
"-sha1",
identity,
"-fd",
file_digest,
"-d",
app.description,
"-du",
app.url,
"-tr",
timestamp_url,
"-td",
timestamp_digest,
]
if use_local_machine:
# Look for cert in Local Machine instead of Current User
sign_command.append("-sm")
# Filepath to sign must come last
sign_command.append(filepath)
try:
self.tools.subprocess.run(sign_command, check=True)
except subprocess.CalledProcessError as e:
raise BriefcaseCommandError(f"Unable to sign {filepath}") from e
def package_app(
self,
app: FinalizedAppConfig,
identity: str | None = None,
adhoc_sign: bool = False,
file_digest: str | None = None,
use_local_machine: bool = False,
cert_store: str | None = None,
timestamp_url: str | None = None,
timestamp_digest: str | None = None,
**kwargs,
):
"""Package an application.
Code signing parameters are ignored if ``sign_app=False``. If a code signing
identity is not provided, then ``sign_app=False`` will be enforced.
:param app: The application to package
:param identity: SHA-1 thumbprint of the certificate to use for code signing.
:param adhoc_sign: Should the application be signed? Default: ``True``
:param file_digest: File hashing algorithm for code signing.
:param use_local_machine: True to use cert stores for the Local Machine instead
of the Current User; default to False for Current User.
:param cert_store: Certificate store within Current User or Local Machine to
search for the certificate within.
:param timestamp_url: Timestamp authority server to use in code signing.
:param timestamp_digest: Hashing algorithm to request from the timestamp server.
"""
if adhoc_sign:
sign_app = False
elif identity:
sign_app = True
else:
sign_app = False
self.console.warning("""
*************************************************************************
** WARNING: No signing identity provided **
*************************************************************************
Briefcase will not sign the app. To provide a signing identity,
use the `--identity` option; or, to explicitly disable signing,
use `--adhoc-sign`.
*************************************************************************
""")
if sign_app:
self.console.info("Signing App...", prefix=app.app_name)
sign_options = {
"identity": identity,
"file_digest": file_digest,
"use_local_machine": use_local_machine,
"cert_store": cert_store,
"timestamp_url": timestamp_url,
"timestamp_digest": timestamp_digest,
}
self.sign_file(app=app, filepath=self.binary_path(app), **sign_options)
if app.packaging_format == "zip":
self._package_zip(app)
else:
self._package_msi(app)
if sign_app:
self.console.info("Signing MSI...", prefix=app.app_name)
self.sign_file(
app=app,
filepath=self.distribution_path(app),
**sign_options,
)
def _package_msi(self, app):
"""Build the msi installer."""
try:
with self.console.wait_bar("Building MSI..."):
self.tools.subprocess.run(
[
self.tools.wix.wix_exe,
"build",
"-ext",
self.tools.wix.ext_path("UI"),
"-arch",
self.vscode_platform.lower(),
f"{app.app_name}.wxs",
"-loc",
"unicode.wxl",
"-pdbtype",
"none",
"-o",
self.distribution_path(app),
],
check=True,
cwd=self.bundle_path(app),
)
except subprocess.CalledProcessError as e:
raise BriefcaseCommandError(f"Unable to package app {app.app_name}.") from e
def _package_zip(self, app):
"""Package the app as simple zip file."""
self.console.info("Building zip file...", prefix=app.app_name)
with self.console.wait_bar("Packing..."):
source = self.package_path(app)
zip_root = f"{app.formal_name}-{app.version}"
with ZipFile(self.distribution_path(app), "w", ZIP_DEFLATED) as archive:
for file_path in source.glob("**/*"):
archive.write(
file_path, zip_root / PurePath(file_path).relative_to(source)
)