| 1 |
import errno |
| 2 |
import re |
| 3 |
import subprocess |
| 4 |
import sys |
| 5 |
import webbrowser |
| 6 |
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer |
| 7 |
from pathlib import Path, PurePosixPath |
| 8 |
from textwrap import dedent, indent |
| 9 |
from typing import Any |
| 10 |
from zipfile import ZipFile |
| 11 |
|
| 12 |
from briefcase.console import Console |
| 13 |
from briefcase.exceptions import ( |
| 14 |
BriefcaseCommandError, |
| 15 |
BriefcaseConfigError, |
| 16 |
UnsupportedCommandError, |
| 17 |
) |
| 18 |
|
| 19 |
if sys.version_info >= (3, 11): # pragma: no-cover-if-lt-py311 |
| 20 |
import tomllib |
| 21 |
else: # pragma: no-cover-if-gte-py311 |
| 22 |
import tomli as tomllib |
| 23 |
|
| 24 |
import tomli_w |
| 25 |
|
| 26 |
from briefcase.commands import ( |
| 27 |
BuildCommand, |
| 28 |
CreateCommand, |
| 29 |
DevCommand, |
| 30 |
OpenCommand, |
| 31 |
PackageCommand, |
| 32 |
PublishCommand, |
| 33 |
RunCommand, |
| 34 |
UpdateCommand, |
| 35 |
) |
| 36 |
from briefcase.config import AppConfig |
| 37 |
|
| 38 |
# Banner templates (Constants used in write_inserts) |
| 39 |
HTML_BANNER = ( |
| 40 |
"<!--------------------------------------------------\n" |
| 41 |
" * {package}\n" |
| 42 |
" -------------------------------------------------->\n" |
| 43 |
"{content}" |
| 44 |
) |
| 45 |
|
| 46 |
CSS_BANNER = ( |
| 47 |
"/**************************************************\n" |
| 48 |
" * {package}\n" |
| 49 |
" *************************************************/\n" |
| 50 |
"{content}" |
| 51 |
) |
| 52 |
|
| 53 |
|
| 54 |
class StaticWebMixin: |
| 55 |
output_format = "static" |
| 56 |
platform = "web" |
| 57 |
platform_target_version = "0.3.21" |
| 58 |
|
| 59 |
def project_path(self, app): |
| 60 |
return self.bundle_path(app) / "www" |
| 61 |
|
| 62 |
def binary_path(self, app): |
| 63 |
return self.bundle_path(app) / "www/index.html" |
| 64 |
|
| 65 |
def static_path(self, app): |
| 66 |
return self.project_path(app) / "static" |
| 67 |
|
| 68 |
def wheel_path(self, app): |
| 69 |
return self.static_path(app) / "wheels" |
| 70 |
|
| 71 |
def distribution_path(self, app): |
| 72 |
return self.dist_path / f"{app.formal_name}-{app.version}.web.zip" |
| 73 |
|
| 74 |
|
| 75 |
class StaticWebCreateCommand(StaticWebMixin, CreateCommand): |
| 76 |
description = "Create and populate a static web project." |
| 77 |
|
| 78 |
|
| 79 |
class StaticWebUpdateCommand(StaticWebCreateCommand, UpdateCommand): |
| 80 |
description = "Update an existing static web project." |
| 81 |
|
| 82 |
|
| 83 |
class StaticWebOpenCommand(StaticWebMixin, OpenCommand): |
| 84 |
description = "Open the folder containing an existing static web project." |
| 85 |
|
| 86 |
|
| 87 |
class StaticWebBuildCommand(StaticWebMixin, BuildCommand): |
| 88 |
description = "Build a static web project." |
| 89 |
|
| 90 |
def write_inserts( |
| 91 |
self, |
| 92 |
app: AppConfig, |
| 93 |
filename: Path, |
| 94 |
inserts: dict[str, dict[str, str]], |
| 95 |
): |
| 96 |
"""Write inserts into an existing file. |
| 97 |
|
| 98 |
This function looks for start and end markers in the named file and |
| 99 |
replaces the content inside the markers with the inserted content. |
| 100 |
|
| 101 |
Multiple formats of insert marker are inspected to accommodate HTML |
| 102 |
and CSS/JS comment conventions: |
| 103 |
* HTML: `<!--@@ insert:start @@--> and <!--@@ insert:end @@-->` |
| 104 |
* CSS/JS: `/*@@ insert:start @@*/ and /*@@ insert:end @@*/` |
| 105 |
|
| 106 |
Inserts and package contributions are processed in sorted order to ensure |
| 107 |
deterministic builds. |
| 108 |
|
| 109 |
:param app: The application whose `pyscript.toml` is being written. |
| 110 |
:param filename: The file whose insert is to be written. |
| 111 |
:param inserts: The inserts for the file. A 2 level dictionary, keyed by |
| 112 |
the name of the insert to add, and then package that contributed the |
| 113 |
insert. |
| 114 |
""" |
| 115 |
# Load file content, skip if file not found |
| 116 |
target_path = self.project_path(app) / filename |
| 117 |
try: |
| 118 |
file_text = target_path.read_text(encoding="utf-8") |
| 119 |
except FileNotFoundError: |
| 120 |
self.console.warning(f" Target {filename} not found; skipping inserts.") |
| 121 |
return |
| 122 |
|
| 123 |
# Each insert slot and its package contributions are processed in sorted order |
| 124 |
for insert, pkg_contribs in sorted(inserts.items()): |
| 125 |
# Build bodies from the same contributions |
| 126 |
html_body = "\n".join( |
| 127 |
HTML_BANNER.format(package=pkg, content=text) |
| 128 |
for pkg, text in sorted(pkg_contribs.items()) |
| 129 |
if text |
| 130 |
) |
| 131 |
css_body = "\n".join( |
| 132 |
CSS_BANNER.format(package=pkg, content=text) |
| 133 |
for pkg, text in sorted(pkg_contribs.items()) |
| 134 |
if text |
| 135 |
) |
| 136 |
body_map = {"html": html_body, "css": css_body} |
| 137 |
|
| 138 |
slot = re.escape(insert) |
| 139 |
|
| 140 |
# Build the compiled patterns directly once per slot |
| 141 |
html_marker = ( |
| 142 |
re.compile( |
| 143 |
rf"(^[ \t]*)<!--@@ {slot}:start @@-->.*?<!--@@ {slot}:end @@-->", |
| 144 |
flags=re.MULTILINE | re.DOTALL, |
| 145 |
), |
| 146 |
( |
| 147 |
r"{indent}<!--@@ {insert}:start @@-->\n" |
| 148 |
r"{content}{indent}<!--@@ {insert}:end @@-->" |
| 149 |
), |
| 150 |
"html", |
| 151 |
) |
| 152 |
css_marker = ( |
| 153 |
re.compile( |
| 154 |
rf"(^[ \t]*)/\*@@ {slot}:start @@\*/.*?/\*@@ {slot}:end @@\*/", |
| 155 |
flags=re.MULTILINE | re.DOTALL, |
| 156 |
), |
| 157 |
( |
| 158 |
r"{indent}/*@@ {insert}:start @@*/\n" |
| 159 |
r"{content}{indent}/*@@ {insert}:end @@*/" |
| 160 |
), |
| 161 |
"css", |
| 162 |
) |
| 163 |
|
| 164 |
# Apply all matching marker styles |
| 165 |
any_match = False |
| 166 |
for pattern, repl_tmpl, kind in [html_marker, css_marker]: |
| 167 |
# Search for pattern within file. |
| 168 |
pattern_found = pattern.search(file_text) |
| 169 |
if pattern_found: |
| 170 |
# Indent content to align with markers. |
| 171 |
indented_content = indent( |
| 172 |
body_map.get(kind, "").strip("\n") + "\n", |
| 173 |
pattern_found.group(1), |
| 174 |
) |
| 175 |
file_text = pattern.sub( |
| 176 |
repl_tmpl.format( |
| 177 |
indent=pattern_found.group(1), |
| 178 |
insert=insert, |
| 179 |
content=indented_content, |
| 180 |
), |
| 181 |
file_text, |
| 182 |
) |
| 183 |
any_match = True |
| 184 |
|
| 185 |
if not any_match: |
| 186 |
self.console.warning( |
| 187 |
f" Slot '{insert}' markers not found in {filename}; skipping." |
| 188 |
) |
| 189 |
|
| 190 |
# Save modified content |
| 191 |
target_path.write_text(file_text, encoding="utf-8") |
| 192 |
|
| 193 |
def _append_pyscript_insert( |
| 194 |
self, |
| 195 |
app: AppConfig, |
| 196 |
filename: Path, |
| 197 |
pyscript_version: str, |
| 198 |
inserts: dict[str, dict[str, dict[str, str]]], |
| 199 |
): |
| 200 |
"""Write pyscript version into an existing html file. |
| 201 |
|
| 202 |
This function creates an insert for PyScript. |
| 203 |
|
| 204 |
:param app: The application whose html file is being written. |
| 205 |
:param filename: The html file whose pyscript version is to be written. |
| 206 |
:param pyscript_version: The pyscript version number to be inserted. |
| 207 |
:param inserts: Nested dict of inserts keyed by target - insert - package. |
| 208 |
""" |
| 209 |
package_key = "briefcase" |
| 210 |
target = filename |
| 211 |
head_insert = "head-python" |
| 212 |
body_insert = "body-python" |
| 213 |
|
| 214 |
# PyScript definitions for insertion: |
| 215 |
head_content = dedent(f"""\ |
| 216 |
<script type="module"> |
| 217 |
// Hide the splash screen when the page is ready. |
| 218 |
import {{ hooks }} from "https://pyscript.net/releases/{pyscript_version}/core.js"; |
| 219 |
hooks.main.onReady.add(() => {{ |
| 220 |
document.getElementById("briefcase-splash").classList.add("hidden"); |
| 221 |
}}); |
| 222 |
</script> |
| 223 |
|
| 224 |
<link rel="stylesheet" href="https://pyscript.net/releases/{pyscript_version}/core.css"> |
| 225 |
<script type="module" src="https://pyscript.net/releases/{pyscript_version}/core.js"></script> |
| 226 |
""") |
| 227 |
body_content = dedent(f"""\ |
| 228 |
<script type="py" async="false" config="pyscript.toml"> |
| 229 |
import runpy |
| 230 |
result = runpy.run_module( |
| 231 |
"{app.app_name}", run_name="__main__", alter_sys=True |
| 232 |
) |
| 233 |
</script> |
| 234 |
""") |
| 235 |
|
| 236 |
pkg_map_head = inserts.setdefault(target, {}).setdefault(head_insert, {}) |
| 237 |
pkg_map_head[package_key] = head_content |
| 238 |
|
| 239 |
pkg_map_body = inserts.setdefault(target, {}).setdefault(body_insert, {}) |
| 240 |
pkg_map_body[package_key] = body_content |
| 241 |
|
| 242 |
def _handle_legacy_css( |
| 243 |
self, |
| 244 |
wheel: ZipFile, |
| 245 |
path: PurePosixPath, |
| 246 |
package_key: str, |
| 247 |
inserts: dict[str, dict[str, dict[str, str]]], |
| 248 |
) -> None: |
| 249 |
"""Handle legacy CSS under /static/*.css and add to style.css. |
| 250 |
|
| 251 |
Emits a deprecation warning for every legacy CSS file discovered. |
| 252 |
|
| 253 |
:param wheel: Open wheel ZipFile being processed. |
| 254 |
:param path: PurePosixPath object of the file inside the wheel. |
| 255 |
:param filename: Filename string inside the wheel. |
| 256 |
:param package_key: Provenance label (e.g. "name version"). |
| 257 |
:param inserts: Nested dict of inserts keyed by target - insert - package. |
| 258 |
""" |
| 259 |
# Warn on every legacy usage |
| 260 |
self.console.warning( |
| 261 |
f" {Path(wheel.filename).name}: legacy '/static' CSS file {path} " |
| 262 |
"detected.\n" |
| 263 |
" Static file handling has been deprecated; this file should be " |
| 264 |
"converted into an insert." |
| 265 |
) |
| 266 |
|
| 267 |
css_text = wheel.read(str(path)).decode("utf-8") |
| 268 |
|
| 269 |
rel_inside = "/".join(path.parts[2:]) |
| 270 |
contrib_key = f"{package_key} (legacy static CSS: {rel_inside})" |
| 271 |
|
| 272 |
# Add CSS content to style.css insert slot |
| 273 |
target = "static/css/style.css" |
| 274 |
insert = "css" |
| 275 |
pkg_map = inserts.setdefault(target, {}).setdefault(insert, {}) |
| 276 |
if pkg_map.get(contrib_key): |
| 277 |
pkg_map[contrib_key] += "\n" + css_text |
| 278 |
else: |
| 279 |
pkg_map[contrib_key] = css_text |
| 280 |
|
| 281 |
def _handle_insert( |
| 282 |
self, |
| 283 |
wheel: ZipFile, |
| 284 |
path: PurePosixPath, |
| 285 |
package_key: str, |
| 286 |
inserts: dict[str, dict[str, dict[str, str]]], |
| 287 |
) -> None: |
| 288 |
"""Handle deploy/inserts/<target>~<insert> files and register inserts. |
| 289 |
|
| 290 |
:param wheel: Open wheel ZipFile being processed. |
| 291 |
:param path: PurePosixPath object of the file inside the wheel. |
| 292 |
:param package_key: Provenance label (e.g. "name version"). |
| 293 |
:param inserts: Nested dict of inserts keyed by target - insert - package. |
| 294 |
""" |
| 295 |
self.console.info(f" Found {path}") |
| 296 |
|
| 297 |
rel_inside = "/".join(path.parts[3:]) |
| 298 |
|
| 299 |
if not rel_inside or rel_inside.endswith("/"): |
| 300 |
self.console.warning( |
| 301 |
f" {path}: skipping; " |
| 302 |
"not a valid insert file (empty path or directory)." |
| 303 |
) |
| 304 |
return |
| 305 |
|
| 306 |
if "~" not in rel_inside: |
| 307 |
self.console.warning( |
| 308 |
f" {path}: skipping; filename must match '<target>~<insert>'." |
| 309 |
) |
| 310 |
return |
| 311 |
|
| 312 |
# Preserve any '~' that might exist in the target path |
| 313 |
target, insert = rel_inside.rsplit("~", 1) |
| 314 |
self.console.info(f" {path}: Adding {insert} insert for {target}") |
| 315 |
|
| 316 |
text = wheel.read(str(path)).decode("utf-8") |
| 317 |
|
| 318 |
contrib_key = f"{package_key} (deploy insert: {rel_inside} from {path})" |
| 319 |
pkg_map = inserts.setdefault(target, {}).setdefault(insert, {}) |
| 320 |
if pkg_map.get(contrib_key): |
| 321 |
pkg_map[contrib_key] += "\n" + text |
| 322 |
else: |
| 323 |
pkg_map[contrib_key] = text |
| 324 |
|
| 325 |
def _process_wheel( |
| 326 |
self, |
| 327 |
wheelfile, |
| 328 |
inserts: dict[str, dict[str, dict[str, str]]], |
| 329 |
) -> None: |
| 330 |
"""Process a wheel to collect insert and style content. |
| 331 |
|
| 332 |
Scans the wheel for: |
| 333 |
* Legacy CSS - .css files under /static/ added to style.css. |
| 334 |
* Deploy inserts - files under /deploy/inserts/<target>~<insert>. |
| 335 |
|
| 336 |
:param wheelfile: Path to the wheel file. |
| 337 |
:param inserts: Nested dict of inserts keyed by target - insert - package. |
| 338 |
""" |
| 339 |
name_parts = wheelfile.name.split("-") |
| 340 |
package_key = f"{name_parts[0]} {name_parts[1]}" |
| 341 |
|
| 342 |
with ZipFile(wheelfile) as wheel: |
| 343 |
for filename in sorted(wheel.namelist()): |
| 344 |
# Skip directories and shallow paths |
| 345 |
path = PurePosixPath(filename) |
| 346 |
parts = path.parts |
| 347 |
|
| 348 |
# Legacy CSS handling |
| 349 |
if ( |
| 350 |
len(parts) > 1 |
| 351 |
and parts[1] == "static" |
| 352 |
and path.suffix.lower() == ".css" |
| 353 |
): |
| 354 |
self._handle_legacy_css(wheel, path, package_key, inserts) |
| 355 |
|
| 356 |
# New deploy/inserts handling |
| 357 |
elif len(parts) >= 3 and parts[1] == "deploy" and parts[2] == "inserts": |
| 358 |
self._handle_insert(wheel, path, package_key, inserts) |
| 359 |
|
| 360 |
def extract_pyscript_config(self, wheels): |
| 361 |
"""Process multiple wheels to gather a config.toml and a base pyscript.toml |
| 362 |
file. |
| 363 |
|
| 364 |
:param wheels: A list of wheel files to be scanned. |
| 365 |
""" |
| 366 |
config_package = None |
| 367 |
config_package_list = [] |
| 368 |
config_filename = None |
| 369 |
pyscript_version = "2024.11.1" |
| 370 |
pyscript_config = None |
| 371 |
|
| 372 |
# Find packages containing a config.toml file. |
| 373 |
for wheelfile in wheels: |
| 374 |
with ZipFile(wheelfile) as wheel: |
| 375 |
for filename in wheel.namelist(): |
| 376 |
path = Path(filename) |
| 377 |
if ( |
| 378 |
len(path.parts) == 3 |
| 379 |
and path.parts[1] == "deploy" |
| 380 |
and path.name == "config.toml" |
| 381 |
): |
| 382 |
self.console.info(f" Found {filename}") |
| 383 |
config_package_list.append(wheelfile) |
| 384 |
config_filename = filename |
| 385 |
|
| 386 |
# Return a blank pyscript config if no configuration file is found. |
| 387 |
if len(config_package_list) == 0: |
| 388 |
pyscript_config = {} |
| 389 |
# Raise an error if more than one configuration file is supplied. |
| 390 |
elif len(config_package_list) > 1: |
| 391 |
raise BriefcaseConfigError( |
| 392 |
"Only one deployment configuration file can be supplied. " |
| 393 |
f"Initial config.toml found in package: {config_package}; " |
| 394 |
f"Duplicate config.toml found in package: {wheel.filename}" |
| 395 |
) |
| 396 |
# Gather a deployment configuration file from the package. For now, this is a |
| 397 |
# pyscript.toml as no other backend is currently supported. |
| 398 |
else: |
| 399 |
with ( |
| 400 |
ZipFile(config_package_list[0]) as wheel, |
| 401 |
wheel.open(config_filename) as config_file, |
| 402 |
): |
| 403 |
config_data = tomllib.load(config_file) |
| 404 |
|
| 405 |
# Gather implementation from config.toml |
| 406 |
implementation = config_data.get("implementation", None) |
| 407 |
|
| 408 |
# Currently, only pyscript is supported. |
| 409 |
# Warn if another implementation is found, |
| 410 |
# but fail safe to using pyscript with a warning. |
| 411 |
if implementation is None: |
| 412 |
self.console.warning( |
| 413 |
"No web implementation specified. Defaulting to 'pyscript'." |
| 414 |
) |
| 415 |
elif implementation != "pyscript": |
| 416 |
self.console.warning( |
| 417 |
"At present, 'pyscript' is the only supported web " |
| 418 |
"implementation. This project may not work correctly." |
| 419 |
) |
| 420 |
|
| 421 |
# Get pyscript version from config.toml. Use default if not present. |
| 422 |
pyscript_version = config_data.get("pyscript", {}).get( |
| 423 |
"version", pyscript_version |
| 424 |
) |
| 425 |
|
| 426 |
# Extract pyscript.toml |
| 427 |
pyscript_path = config_filename.replace("config.toml", "pyscript.toml") |
| 428 |
try: |
| 429 |
with wheel.open(pyscript_path) as pyscript_file: |
| 430 |
pyscript_config = tomllib.load(pyscript_file) |
| 431 |
except tomllib.TOMLDecodeError as e: |
| 432 |
raise BriefcaseConfigError( |
| 433 |
f"pyscript.toml content isn't valid TOML: {e}" |
| 434 |
) from e |
| 435 |
except (KeyError, FileNotFoundError): |
| 436 |
self.console.info( |
| 437 |
"Pyscript configuration file not found in " |
| 438 |
f"{config_package_list[0]}. Using default configuration." |
| 439 |
) |
| 440 |
pyscript_config = {} |
| 441 |
|
| 442 |
return pyscript_config, pyscript_version |
| 443 |
|
| 444 |
def build_app(self, app: AppConfig, **kwargs): |
| 445 |
"""Build the static web deployment for the application. |
| 446 |
|
| 447 |
:param app: The application to build |
| 448 |
""" |
| 449 |
self.console.info("Building web project...", prefix=app.app_name) |
| 450 |
|
| 451 |
if self.wheel_path(app).exists(): |
| 452 |
with self.console.wait_bar("Removing old wheels..."): |
| 453 |
self.tools.shutil.rmtree(self.wheel_path(app)) |
| 454 |
|
| 455 |
self.wheel_path(app).mkdir(parents=True) |
| 456 |
|
| 457 |
with self.console.wait_bar("Building app wheel..."): |
| 458 |
try: |
| 459 |
self.tools.subprocess.run( |
| 460 |
[ |
| 461 |
sys.executable, |
| 462 |
"-u", |
| 463 |
"-X", |
| 464 |
"utf8", |
| 465 |
"-m", |
| 466 |
"wheel", |
| 467 |
"pack", |
| 468 |
self.app_path(app), |
| 469 |
"--dest-dir", |
| 470 |
self.wheel_path(app), |
| 471 |
], |
| 472 |
check=True, |
| 473 |
encoding="UTF-8", |
| 474 |
) |
| 475 |
except subprocess.CalledProcessError as e: |
| 476 |
raise BriefcaseCommandError( |
| 477 |
f"Unable to build wheel for app {app.app_name!r}" |
| 478 |
) from e |
| 479 |
|
| 480 |
with self.console.wait_bar("Installing wheels for requirements..."): |
| 481 |
try: |
| 482 |
self.tools.subprocess.run( |
| 483 |
[ |
| 484 |
sys.executable, |
| 485 |
"-u", |
| 486 |
"-X", |
| 487 |
"utf8", |
| 488 |
"-m", |
| 489 |
"pip", |
| 490 |
"wheel", |
| 491 |
"--wheel-dir", |
| 492 |
self.wheel_path(app), |
| 493 |
"-r", |
| 494 |
self.bundle_path(app) / "requirements.txt", |
| 495 |
] |
| 496 |
+ (["-vv"] if self.console.is_deep_debug else []), |
| 497 |
check=True, |
| 498 |
encoding="UTF-8", |
| 499 |
) |
| 500 |
except subprocess.CalledProcessError as e: |
| 501 |
raise BriefcaseCommandError( |
| 502 |
f"Unable to install requirements for app {app.app_name!r}" |
| 503 |
) from e |
| 504 |
|
| 505 |
with self.console.wait_bar("Writing Pyscript configuration file..."): |
| 506 |
# Load any pre-existing pyscript.toml provided by a GUI Toolkit. If the file |
| 507 |
# doesn't exist, assume an empty pyscript.toml as a starting point. |
| 508 |
config, pyscript_version = self.extract_pyscript_config( |
| 509 |
self.wheel_path(app).glob("*.whl") |
| 510 |
) |
| 511 |
|
| 512 |
# Add the packages declaration to the existing pyscript.toml. |
| 513 |
# Ensure that we're using Unix path separators, as the content |
| 514 |
# will be parsed by pyscript in the browser. |
| 515 |
config["packages"] = [ |
| 516 |
f"/{'/'.join(wheel.relative_to(self.project_path(app)).parts)}" |
| 517 |
for wheel in sorted(self.wheel_path(app).glob("*.whl")) |
| 518 |
] |
| 519 |
|
| 520 |
# Parse any additional pyscript.toml content, and merge it into |
| 521 |
# the overall content |
| 522 |
try: |
| 523 |
extra = tomllib.loads(app.extra_pyscript_toml_content) |
| 524 |
config.update(extra) |
| 525 |
except tomllib.TOMLDecodeError as e: |
| 526 |
raise BriefcaseConfigError( |
| 527 |
f"Extra pyscript.toml content isn't valid TOML: {e}" |
| 528 |
) from e |
| 529 |
except AttributeError: |
| 530 |
pass |
| 531 |
|
| 532 |
# Write the final configuration |
| 533 |
with (self.project_path(app) / "pyscript.toml").open("wb") as f: |
| 534 |
tomli_w.dump(config, f) |
| 535 |
|
| 536 |
with self.console.wait_bar("Compiling static web content from wheels..."): |
| 537 |
inserts: dict[str, dict[str, dict[str, str]]] = {} |
| 538 |
|
| 539 |
for wheelfile in sorted(self.wheel_path(app).glob("*.whl")): |
| 540 |
self.console.info(f" Processing {wheelfile.name}...") |
| 541 |
self._process_wheel( |
| 542 |
wheelfile=wheelfile, |
| 543 |
inserts=inserts, |
| 544 |
) |
| 545 |
|
| 546 |
# Add pyscript insertion to inserts |
| 547 |
self._append_pyscript_insert(app, "index.html", pyscript_version, inserts) |
| 548 |
|
| 549 |
# Write inserts per target |
| 550 |
for target, target_inserts in sorted(inserts.items()): |
| 551 |
self.write_inserts(app, Path(target), target_inserts) |
| 552 |
|
| 553 |
return {} |
| 554 |
|
| 555 |
|
| 556 |
class HTTPHandler(SimpleHTTPRequestHandler): |
| 557 |
"""Convert any HTTP request into a path request on the static content folder.""" |
| 558 |
|
| 559 |
server: "LocalHTTPServer" |
| 560 |
|
| 561 |
def translate_path(self, path): |
| 562 |
return str(self.server.base_path / path[1:]) |
| 563 |
|
| 564 |
def end_headers(self): |
| 565 |
self.send_header("Cache-Control", "no-cache, no-store, must-revalidate") |
| 566 |
self.send_header("Pragma", "no-cache") |
| 567 |
self.send_header("Expires", "0") |
| 568 |
super().end_headers() |
| 569 |
|
| 570 |
# Strip out ANSI escape sequences from messages. This was added in security releases |
| 571 |
# before Python 3.12. |
| 572 |
_control_char_table = str.maketrans( |
| 573 |
{c: rf"\x{c:02x}" for c in [*range(0x20), *range(0x7F, 0xA0)]} |
| 574 |
) |
| 575 |
_control_char_table[ord("\\")] = r"\\" |
| 576 |
|
| 577 |
def log_message(self, format: str, *args: Any) -> None: |
| 578 |
message = (format % args).translate(self._control_char_table) |
| 579 |
self.server.logger.info( |
| 580 |
f"{self.address_string()} - - [{self.log_date_time_string()}] {message}" |
| 581 |
) |
| 582 |
|
| 583 |
|
| 584 |
class LocalHTTPServer(ThreadingHTTPServer): |
| 585 |
"""An HTTP server that serves local static content.""" |
| 586 |
|
| 587 |
def __init__( |
| 588 |
self, |
| 589 |
base_path, |
| 590 |
host, |
| 591 |
port, |
| 592 |
RequestHandlerClass=HTTPHandler, |
| 593 |
*, |
| 594 |
logger: Console, |
| 595 |
): |
| 596 |
self.base_path = base_path |
| 597 |
self.logger = logger |
| 598 |
super().__init__((host, port), RequestHandlerClass) |
| 599 |
|
| 600 |
|
| 601 |
class StaticWebRunCommand(StaticWebMixin, RunCommand): |
| 602 |
description = "Run a static web project." |
| 603 |
|
| 604 |
def add_options(self, parser): |
| 605 |
super().add_options(parser) |
| 606 |
parser.add_argument( |
| 607 |
"--host", |
| 608 |
default="localhost", |
| 609 |
help="The host on which to run the server (default: localhost)", |
| 610 |
required=False, |
| 611 |
) |
| 612 |
parser.add_argument( |
| 613 |
"-p", |
| 614 |
"--port", |
| 615 |
default=8080, |
| 616 |
type=int, |
| 617 |
help="The port on which to run the server (default: 8080)", |
| 618 |
required=False, |
| 619 |
) |
| 620 |
parser.add_argument( |
| 621 |
"--no-browser", |
| 622 |
action="store_false", |
| 623 |
dest="open_browser", |
| 624 |
help="Don't open a web browser on the newly opened server", |
| 625 |
required=False, |
| 626 |
) |
| 627 |
|
| 628 |
def run_app( |
| 629 |
self, |
| 630 |
app: AppConfig, |
| 631 |
passthrough: list[str], |
| 632 |
host, |
| 633 |
port, |
| 634 |
open_browser, |
| 635 |
**kwargs, |
| 636 |
): |
| 637 |
"""Start the application. |
| 638 |
|
| 639 |
:param app: The config object for the app |
| 640 |
:param passthrough: The list of arguments to pass to the app |
| 641 |
:param host: The host on which to run the server |
| 642 |
:param port: The port on which to run the server |
| 643 |
:param open_browser: Should a browser be opened on the newly started server. |
| 644 |
""" |
| 645 |
if app.test_mode: |
| 646 |
raise BriefcaseCommandError("Briefcase can't run web apps in test mode.") |
| 647 |
|
| 648 |
self.console.info("Starting web server...", prefix=app.app_name) |
| 649 |
|
| 650 |
# At least for now, there's no easy way to pass arguments to a web app. |
| 651 |
if passthrough: |
| 652 |
self.console.warning(f"Ignoring passthrough arguments: {passthrough}") |
| 653 |
|
| 654 |
httpd = None |
| 655 |
try: |
| 656 |
# Create a local HTTP server |
| 657 |
try: |
| 658 |
httpd = LocalHTTPServer( |
| 659 |
self.project_path(app), |
| 660 |
host=host, |
| 661 |
port=port, |
| 662 |
logger=self.console, |
| 663 |
) |
| 664 |
except OSError as e: |
| 665 |
if e.errno in (errno.EADDRINUSE, errno.ENOSR): |
| 666 |
self.console.warning( |
| 667 |
f"Using a system-allocated port since port {port} is already " |
| 668 |
"in use. Use -p/--port to manually specify a port." |
| 669 |
) |
| 670 |
httpd = LocalHTTPServer( |
| 671 |
self.project_path(app), |
| 672 |
host=host, |
| 673 |
port=0, |
| 674 |
logger=self.console, |
| 675 |
) |
| 676 |
else: |
| 677 |
raise |
| 678 |
|
| 679 |
# Extract the host and port from the server. This is needed |
| 680 |
# because specifying a port of 0 lets the server pick a port. |
| 681 |
host, port = httpd.socket.getsockname() |
| 682 |
url = f"http://{host}:{port}" |
| 683 |
|
| 684 |
self.console.info(f"Web server open on {url}") |
| 685 |
# If requested, open a browser tab on the newly opened server. |
| 686 |
if open_browser: |
| 687 |
webbrowser.open_new_tab(url) |
| 688 |
|
| 689 |
self.console.info( |
| 690 |
"Web server log output (type CTRL-C to stop log)...", |
| 691 |
prefix=app.app_name, |
| 692 |
) |
| 693 |
self.console.info("=" * 75) |
| 694 |
|
| 695 |
# Run the server. |
| 696 |
httpd.serve_forever() |
| 697 |
except PermissionError as e: |
| 698 |
if port < 1024: |
| 699 |
raise BriefcaseCommandError( |
| 700 |
"Unable to start web server; Permission denied. " |
| 701 |
"Try using a port > 1023." |
| 702 |
) from e |
| 703 |
else: |
| 704 |
raise BriefcaseCommandError( |
| 705 |
"Unable to start web server; Permission denied. " |
| 706 |
"Did you specify a valid host and port?" |
| 707 |
) from e |
| 708 |
except OSError as e: |
| 709 |
if e.errno in (errno.EADDRNOTAVAIL, errno.ENOSTR): |
| 710 |
raise BriefcaseCommandError( |
| 711 |
f"Unable to start web server. {host} is not a valid hostname." |
| 712 |
) from e |
| 713 |
else: |
| 714 |
raise BriefcaseCommandError(f"Unable to start web server. {e}") from e |
| 715 |
except OverflowError as e: |
| 716 |
raise BriefcaseCommandError( |
| 717 |
"Unable to start web server. Port must be in the range 0-65535." |
| 718 |
) from e |
| 719 |
except KeyboardInterrupt: |
| 720 |
# CTRL-C is the accepted way to stop the server. |
| 721 |
httpd.shutdown() |
| 722 |
finally: |
| 723 |
if httpd: |
| 724 |
with self.console.wait_bar("Shutting down server..."): |
| 725 |
httpd.server_close() |
| 726 |
|
| 727 |
# Not sure why, but this is needed to mollify coverage for the |
| 728 |
# "test_cleanup_server_error" case. Without this pass, a missing branch |
| 729 |
# is reported for the "if httpd: -> exit" branch |
| 730 |
pass # noqa: PIE790 (unnecessary pass) |
| 731 |
|
| 732 |
return {} |
| 733 |
|
| 734 |
|
| 735 |
class StaticWebPackageCommand(StaticWebMixin, PackageCommand): |
| 736 |
description = "Package a static web app." |
| 737 |
|
| 738 |
@property |
| 739 |
def packaging_formats(self): |
| 740 |
return ["zip"] |
| 741 |
|
| 742 |
@property |
| 743 |
def default_packaging_format(self): |
| 744 |
return "zip" |
| 745 |
|
| 746 |
def package_app(self, app: AppConfig, **kwargs): |
| 747 |
"""Package an app for distribution. |
| 748 |
|
| 749 |
:param app: The app to package. |
| 750 |
""" |
| 751 |
self.console.info( |
| 752 |
"Packaging web app for distribution...", |
| 753 |
prefix=app.app_name, |
| 754 |
) |
| 755 |
|
| 756 |
with self.console.wait_bar("Building archive..."): |
| 757 |
self.tools.shutil.make_archive( |
| 758 |
self.distribution_path(app).with_suffix(""), |
| 759 |
format="zip", |
| 760 |
root_dir=self.project_path(app), |
| 761 |
) |
| 762 |
|
| 763 |
|
| 764 |
class StaticWebPublishCommand(StaticWebMixin, PublishCommand): |
| 765 |
description = "Publish a static web app." |
| 766 |
|
| 767 |
|
| 768 |
class StaticWebDevCommand(StaticWebMixin, DevCommand): |
| 769 |
description = "Run a static web project in development mode. (Work in progress)" |
| 770 |
|
| 771 |
@property |
| 772 |
def venv_name(self) -> str: |
| 773 |
"""Returns the name of the virtual environment directory. |
| 774 |
|
| 775 |
The web environment uses a different venv because a web deployment has |
| 776 |
different requirements to a desktop deployment. The name is the same as the |
| 777 |
desktop deployment, but with `.web` appended. |
| 778 |
|
| 779 |
:returns: Name for virtual environment directory |
| 780 |
""" |
| 781 |
return f"{DevCommand.venv_name.fget(self)}.web" |
| 782 |
|
| 783 |
def run_dev_app(self, app: AppConfig, **options): |
| 784 |
raise UnsupportedCommandError( |
| 785 |
platform="web", |
| 786 |
output_format="static", |
| 787 |
command="dev", |
| 788 |
) |
| 789 |
|
| 790 |
|
| 791 |
# Declare the briefcase command bindings |
| 792 |
create = StaticWebCreateCommand |
| 793 |
update = StaticWebUpdateCommand |
| 794 |
open = StaticWebOpenCommand |
| 795 |
build = StaticWebBuildCommand |
| 796 |
run = StaticWebRunCommand |
| 797 |
package = StaticWebPackageCommand |
| 798 |
publish = StaticWebPublishCommand |
| 799 |
dev = StaticWebDevCommand |