Debian Codegraph @

src/briefcase/platforms/windows/__init__.py

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