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
|
from __future__ import annotations
import io
import os
import plistlib
import tarfile
import zipfile
from email.message import EmailMessage
from pathlib import Path
import httpx
from rich.markup import escape
from briefcase.console import Console, InputDisabled
class PartialMatchString(str):
"A string-like class that has equality on a partial match"
def __eq__(self, other):
return self in other
class NoMatchString(str):
"A string-like class that has equality when there is no match"
def __eq__(self, other):
return self not in other
class DummyConsole(Console):
def __init__(self, *values, input_enabled=True):
super().__init__(input_enabled=input_enabled)
self.prompts = []
self.values = list(values)
def input(self, prompt, *args, **kwargs):
if not self.input_enabled:
raise InputDisabled()
self.prompts.append(prompt)
return self.values.pop(0)
def default_rich_prompt(prompt: str) -> str:
"""Formats a prompt as what is actually passed to Rich."""
return f"[bold]{escape(prompt)}[/bold]"
def create_file(filepath, content, mode="w", chmod=None):
"""A test utility to create a file with known content.
Ensures that the directory for the file exists, and writes a file with
specific content.
:param filepath: The path for the file to create
:param content: A string containing the content to write.
:param mode: The mode to open the file. This is `w` by default;
use `wb` and provide content as a bitstring if you need to
write a binary file.
:param chmod: file permissions to apply
:returns: The path to the file that was created.
"""
filepath.parent.mkdir(parents=True, exist_ok=True)
with filepath.open(mode, **({} if "b" in mode else {"encoding": "utf-8"})) as f:
f.write(content)
if chmod:
os.chmod(filepath, chmod)
return filepath
def create_plist_file(plistpath, content):
"""A test utility to create a plist file with known content.
Ensures that the directory for the file exists, and writes an XML plist with
specific content.
:param plistpath: The path for the plist file to create.
:param content: A dictionary of content that plistlib can use to create the plist
file.
:returns: The path to the file that was created.
"""
plistpath.parent.mkdir(parents=True, exist_ok=True)
with plistpath.open("wb") as f:
plistlib.dump(content, f)
return plistpath
def create_zip_file(zippath, content):
"""A test utility to create a .zip file with known content.
Ensures that the directory for the file exists, and writes a file with specific
content.
:param zippath: The path for the ZIP file to create
:param content: A list of pairs; each pair is (path, data) describing an item to be
added to the zip file.
:returns: The path to the file that was created.
"""
zippath.parent.mkdir(parents=True, exist_ok=True)
with zipfile.ZipFile(zippath, "w") as f:
for path, data in content:
f.writestr(path, data=data)
return zippath
def create_tgz_file(tgzpath, content, links=None):
"""A test utility to create a .tar.gz file with known content.
Ensures that the directory for the file exists, and writes a file with specific
content.
:param tgzpath: The path for the gzipped tarfile file to create
:param content: A list of pairs; each pair is (path, data) describing an item to be
added to the tgz file.
:param links: (Optional) A list of pairs; each pair is a (path, target) describing a
symlink item to be added to the tgz file, and the file it will target.
:returns: The path to the file that was created.
"""
tgzpath.parent.mkdir(parents=True, exist_ok=True)
with tarfile.open(tgzpath, "w:gz") as f:
for path, data in content:
tarinfo = tarfile.TarInfo(path)
payload = data.encode("utf-8")
tarinfo.size = len(payload)
f.addfile(tarinfo, io.BytesIO(payload))
if links:
for path, target in links:
tarinfo = tarfile.TarInfo(path)
tarinfo.linkname = target
tarinfo.type = tarfile.SYMTYPE
f.addfile(tarinfo, None)
return tgzpath
def mock_file_download(filename, content, mode="w", role=None):
"""Create a side effect function that mocks the download of a zip file.
:param filename: The file name (*not* the path - just the file name) to
create as a side effect
:param content: A string containing the content to write.
:param mode: The mode to open the file. This is `w` by default;
use `wb` and provide content as a bitstring if you need to
write a binary file.
:param role: The role played by the content being downloaded
:returns: a function that can act as a mock side effect for `file.download()`
"""
def _download_file(url, download_path, role):
return create_file(download_path / filename, content, mode=mode)
return _download_file
def mock_zip_download(filename, content, role=None):
"""Create a side effect function that mocks the download of a zip file.
:param filename: The file name (*not* the path - just the file name) to
create as a side effect
:param content: A string containing the content to write.
:param role: The role played by the content being downloaded
:returns: a function that can act as a mock side effect for `file.download()`
"""
def _download_file(url, download_path, role):
return create_zip_file(download_path / filename, content)
return _download_file
def mock_tgz_download(filename, content, role=None, links=None):
"""Create a side effect function that mocks the download of a .tar.gz file.
:param content: A string containing the content to write.
:param role: The role played by the content being downloaded
:param links: (Optional) A list of pairs; each pair is a (path, target) describing a
symlink item to be added to the tgz file, and the file it will target.
:returns: a function that can act as a mock side effect for `file.download()`
"""
def _download_file(url, download_path, role):
return create_tgz_file(download_path / filename, content, links)
return _download_file
def distinfo_metadata(
package: str = "dummy",
version: str = "1.2.3",
tag: str = "py3-none-any",
):
"""Generate the content for a distinfo folder.
:param package: The name of the package.
:param version: The version number of the package.
:param tag: The packaging tag for the package.
"""
content = []
# INSTALLER
installer = "pip\n"
content.append((f"{package}-{version}.dist-info/INSTALLER", installer))
# METADATA
metadata = EmailMessage()
metadata["Metadata-Version"] = "2.1"
metadata["Name"] = package
metadata["Version"] = version
metadata["Summary"] = f"A packaged named {package}."
metadata["Author-email"] = "Jane Developer <jane@example.com>"
content.append((f"{package}-{version}.dist-info/METADATA", str(metadata)))
# WHEEL
wheel = EmailMessage()
wheel["Wheel-Version"] = "1.0"
wheel["Generator"] = "test-case"
wheel["Root-Is-Purelib"] = "true" if tag == "py3-none-any" else "false"
wheel["Tag"] = tag
content.append((f"{package}-{version}.dist-info/WHEEL", str(wheel)))
# RECORD
# Create the file, but don't actually populate it.
record = ""
content.append((f"{package}-{version}.dist-info/RECORD", record))
return content
def installed_package_content(
package="dummy",
version="1.2.3",
tag="py3-none-any",
extra_content=None,
):
"""Generate the content for an installed package.
:param path: The site-packages folder into which to install the package.
:param package: The name of the package in the wheel. Defaults to ``dummy``
:param version: The version number of the package. Defaults to ``1.2.3``
:param tag: The installation tag for the package. Defaults to a pure python wheel.
:param extra_content: Optional. A list of tuples of ``(path, content)`` that will be
added to the wheel.
"""
return (
[
(f"{package}/__init__.py", ""),
(f"{package}/app.py", "# This is the app"),
]
+ (extra_content if extra_content else [])
+ distinfo_metadata(package=package, version=version, tag=tag)
)
def create_installed_package(
path,
package="dummy",
version="1.2.3",
tag="py3-none-any",
extra_content=None,
):
"""Write an installed package into a 'site-packages' folder.
:param path: The site-packages folder into which to install the package.
:param package: The name of the package in the wheel. Defaults to ``dummy``
:param version: The version number of the package. Defaults to ``1.2.3``
:param tag: The installation tag for the package. Defaults to a pure python wheel.
:param extra_content: Optional. A list of tuples of ``(path, content)`` or
``(path, content, chmod)`` that will be added to the wheel. If ``chmod`` is
not specified, default filesystem permissions will be used.
"""
for entry in installed_package_content(
package=package,
version=version,
tag=tag,
extra_content=extra_content,
):
try:
filename, content, chmod = entry
except ValueError:
filename, content = entry
chmod = None
create_file(path / filename, content=content, chmod=chmod)
def create_wheel(
path,
package="dummy",
version="1.2.3",
tag="py3-none-any",
extra_content=None,
):
"""Create a sample wheel file.
:param path: The folder where the wheel should be written.
:param package: The name of the package in the wheel. Defaults to ``dummy``
:param version: The version number of the package. Defaults to ``1.2.3``
:param tag: The installation tag for the package. Defaults to a pure python wheel.
:param extra_content: Optional. A list of tuples of ``(path, content)`` or
``(path, content, chmod)`` that will be added to the wheel. If ``chmod`` is
not specified, default filesystem permissions will be used.
"""
wheel_filename = path / f"{package}-{version}-{tag}.whl"
create_zip_file(
wheel_filename,
content=installed_package_content(
package=package,
version=version,
tag=tag,
extra_content=extra_content,
),
)
return wheel_filename
def file_content(path: Path) -> str | None:
"""Return the content of a file, or None if the path is a directory."""
if path.is_dir():
return None
with path.open(encoding="utf-8") as f:
return f.read()
def assert_url_resolvable(url: str):
"""Tests whether a URL is resolvable with retries; raises for failure."""
transport = httpx.HTTPTransport(
# Retry for connection issues
retries=3,
)
with httpx.Client(transport=transport, follow_redirects=True) as client:
bad_response_retries = 3
retry_status_codes = {500, 502, 504}
while bad_response_retries > 0:
response = client.head(url)
if response.status_code not in retry_status_codes:
# break if the status code is not one we care to retry (hopefully a success!)
break
response.raise_for_status()
|