refactor: move the pack downloader into release

This commit is contained in:
Abdessamad Derraz committed 2026-11-21 14:58:26 +01:00
1 parent 1ca8a775c1
commit 2f428a01a8
9 files changed
+377 -327

No files matched your search

+4 -288
View File
@@ -21,73 +21,19 @@ import argparse
import http.client
import json
import os
import re
import shutil
import sys
import tempfile
import urllib.error
import urllib.parse
import urllib.request
from dataclasses import dataclass
from pathlib import Path
sys.path.insert(0, os.path.dirname(__file__))
from core.hashing import compute_hashes, parse_sha256sums
from core.paths import REPO_ROOT
from core.sizes import size_text
from core.text import count_text
from core.upstream import UpstreamError, forge_headers, open_retrying
from core.upstream import UpstreamError
from core.ziptools import safe_extract_zip
from packs.parts import part_of
from model.releaserecord import PACK_SUFFIX, RECORD, load_record, match_key, pack_label, recorded_pack
DEFAULT_API = "https://api.github.com"
REPO = "Abdess/retrobios"
CHECKSUMS_ASSET = "SHA256SUMS.txt"
STAGING_PREFIX = ".retrobios-download-"
MAX_CHECKSUMS_BYTES = 1 << 20
CHUNK = 1 << 20
_VOLUME_RE = re.compile(rf"^(?P<base>.+{re.escape(PACK_SUFFIX)})\.(?P<index>\d+)$")
_LOOPBACK_HOSTS = {"127.0.0.1", "::1", "localhost"}
def _checked_url(value: str, label: str) -> str:
"""Refuse a URL that is neither HTTPS nor loopback.
This endpoint names the assets and, through them, the bytes that land in
the BIOS directory, so it is the trust anchor of the whole download.
Plain HTTP to loopback stays allowed: it is how this is tested end to end.
"""
parsed = urllib.parse.urlparse(value)
if parsed.scheme == "https":
return value.rstrip("/")
host = (parsed.hostname or "").lower()
if parsed.scheme == "http" and host in _LOOPBACK_HOSTS:
return value.rstrip("/")
print(f"Error: {label} must use HTTPS, got {value!r}", file=sys.stderr)
sys.exit(1)
API = _checked_url(os.environ.get("RETROBIOS_API", DEFAULT_API), "RETROBIOS_API")
@dataclass(frozen=True)
class Pack:
"""A platform pack: one asset, or the files it was published in.
`joined` says the files are byte ranges of one archive. `expected_parts`
is the count a part's own name declares, so a release that lists fewer
is recognised before anything is downloaded.
"""
name: str
platform: str
parts: tuple[dict, ...]
size: int
joined: bool = False
expected_parts: int = 1
from release.latest import get_latest_release
from release.packfetch import fetch_checksums, fetch_pack, make_staging
from release.packgroups import find_pack, list_platforms
# A release publishes packs for the setups most people download. The others
# are served file by file by the installer.
@@ -97,236 +43,6 @@ NO_PACK_HINT = (
)
def get_latest_release() -> dict:
"""Fetch latest release info from GitHub API."""
url = f"{API}/repos/{REPO}/releases/latest"
# The anonymous quota is 60 calls an hour per address. The token goes to
# GitHub's API only: RETROBIOS_API can name any host.
headers = forge_headers(url, "application/vnd.github.v3+json", "retrobios-downloader/1.0")
req = urllib.request.Request(url, headers=headers)
try:
return json.loads(open_retrying(req, lambda resp: resp.read(), 30))
except urllib.error.HTTPError as e:
if e.code == 404:
print("No releases found. The repository may not have any releases yet.")
sys.exit(1)
raise
def group_packs(release: dict) -> list[Pack]:
"""Group release assets into packs, the files of one pack folded together."""
groups: dict[str, list[tuple[int, dict]]] = {}
joined: set[str] = set()
expected: dict[str, int] = {}
for asset in release.get("assets", []):
name = asset["name"]
volume = _VOLUME_RE.match(name)
part = part_of(name)
if volume:
groups.setdefault(volume["base"], []).append((int(volume["index"]), asset))
joined.add(volume["base"])
elif part:
base, index, count = part
groups.setdefault(base, []).append((index, asset))
expected[base] = count
elif name.endswith(PACK_SUFFIX):
groups.setdefault(name, []).append((0, asset))
packs = []
for base, volumes in sorted(groups.items()):
parts = tuple(asset for _, asset in sorted(volumes, key=lambda v: v[0]))
packs.append(
Pack(
name=base,
platform=pack_label(base),
parts=parts,
size=sum(part.get("size", 0) for part in parts),
joined=base in joined,
expected_parts=expected.get(base, len(parts)),
)
)
return packs
def list_platforms(release: dict) -> list[str]:
"""List available platform packs from release assets."""
return sorted(pack.platform for pack in group_packs(release))
def find_pack(release: dict, platform: str) -> Pack | None:
"""Find the pack for a platform name.
release.json names the platforms each pack serves, and is read when it
records this release. Otherwise the platform is matched against the pack
names, the shortest first: RetroArch_v1.22.2 is the full pack, and
RetroArch_v1.22.2_AndroidArm64V8A one target's.
"""
packs = group_packs(release)
record = load_record(REPO_ROOT / RECORD)
if record.get("tag") and record.get("tag") == release.get("tag_name"):
name = recorded_pack(platform, record)
return next((pack for pack in packs if pack.name == name), None)
needle = match_key(platform)
if not needle:
return None
matches = [pack for pack in packs if needle in match_key(pack.name)]
return min(matches, key=lambda pack: (len(match_key(pack.name)), pack.name), default=None)
def fetch_checksums(release: dict) -> dict[str, str]:
"""Read the published SHA-256 of each pack, keyed by archive name."""
for asset in release.get("assets", []):
if asset["name"] != CHECKSUMS_ASSET:
continue
url = _checked_url(asset["browser_download_url"], "asset URL")
req = urllib.request.Request(
url, headers={"User-Agent": "retrobios-downloader/1.0"}
)
body = open_retrying(
req, lambda resp: resp.read(MAX_CHECKSUMS_BYTES), 60
).decode("utf-8", "replace")
# A file that is not sha256sum output refuses the download: read
# leniently, a `*name` line matched nothing and the pack went
# unchecked.
try:
return parse_sha256sums(body)
except ValueError as exc:
raise SystemExit(f"ERROR: {CHECKSUMS_ASSET}: {exc}") from exc
return {}
def download_file(
url: str, dest: Path, expected_size: int = 0, label: str = ""
) -> None:
"""Download a file with progress indication.
core.upstream.open_retrying asks again after a dropped connection, a
stream cut midway or a 5xx, and waits out a rate limit: each attempt
writes `dest` from its first byte.
"""
url = _checked_url(url, "asset URL")
req = urllib.request.Request(
url, headers={"User-Agent": "retrobios-downloader/1.0"}
)
# A redrawn bar only on a terminal: written to a log, 32,768 redraws of a
# 2 GiB part made one line of nearly 3 MB.
live = sys.stdout.isatty() and os.environ.get("TERM") != "dumb"
def save(resp: http.client.HTTPResponse) -> int:
total = int(resp.headers.get("Content-Length", expected_size))
downloaded = 0
shown = -1
with open(dest, "wb") as f:
while chunk := resp.read(65536):
f.write(chunk)
downloaded += len(chunk)
if total > 0 and live:
pct = downloaded * 100 // total
if pct != shown:
shown = pct
columns = shutil.get_terminal_size((80, 24)).columns
line = _progress_line(label, downloaded, total, columns)
print(f"\r\033[K{line}", end="", flush=True)
return downloaded
downloaded = open_retrying(req, save, 300)
if live:
print()
else:
print(f" {label}{downloaded:,} bytes")
if expected_size and downloaded != expected_size:
raise ValueError(f"downloaded {downloaded} bytes, expected {expected_size}")
def _progress_line(label: str, done: int, total: int, columns: int) -> str:
"""One physical line shorter than the terminal: a wrapped line leaves a
copy of itself on every redraw, since \\r goes back one row only. The
bar shrinks first, then goes."""
pct = done * 100 // total
figures = f" {pct}% ({size_text(done)}/{size_text(total)})"
room = min(50, columns - 1 - len(f" {label}[]") - len(figures))
if room < 10:
return f" {label}{figures.strip()}"[: columns - 1]
filled = room * pct // 100
return f" {label}[{'=' * filled}{' ' * (room - filled)}]{figures}"
def join_volumes(parts: list[Path], dest: Path) -> None:
"""Concatenate split volumes into one archive, streaming."""
with open(dest, "wb") as out:
for part in parts:
with open(part, "rb") as src:
shutil.copyfileobj(src, out, CHUNK)
def make_staging(dest: Path) -> Path:
"""Return a staging directory of this run's own, on the destination volume.
A pack is gigabytes and that is the filesystem the user picked for them:
the system temp directory is a RAM disk on the appliances these packs
target. The name is unique per run because two downloads into one BIOS
folder used to share a fixed path, so whichever finished first removed the
other's archive mid-transfer and the second died on the missing file with
nothing installed.
"""
return Path(tempfile.mkdtemp(prefix=STAGING_PREFIX, dir=dest))
def _check(archive: Path, checksums: dict[str, str]) -> None:
"""Compare a downloaded file with its published SHA-256, when there is one."""
expected = checksums.get(archive.name)
if not expected:
print(f"No checksum published for {archive.name}, skipping.")
return
print(f"Checking {archive.name}...")
actual = compute_hashes(str(archive))["sha256"].lower()
if actual != expected:
archive.unlink()
print(
f"Error: checksum mismatch for {archive.name}\n"
f" expected {expected}\n got {actual}\n"
"Download the parts again: a truncated part gives this.",
file=sys.stderr,
)
sys.exit(1)
def fetch_pack(pack: Pack, staging: Path, checksums: dict[str, str]) -> list[Path]:
"""Download a pack and return the archives to extract, each one checked."""
if len(pack.parts) != pack.expected_parts:
print(
f"Error: the release lists {len(pack.parts)} of "
f"{pack.expected_parts} parts of {pack.name}.",
file=sys.stderr,
)
sys.exit(1)
staging.mkdir(parents=True, exist_ok=True)
volumes = []
for index, part in enumerate(pack.parts, start=1):
label = f"part {index}/{len(pack.parts)} " if len(pack.parts) > 1 else ""
target = staging / part["name"]
print(f"Downloading {part['name']} ({part.get('size', 0):,} bytes)...")
download_file(part["browser_download_url"], target, part.get("size", 0), label)
volumes.append(target)
if pack.joined:
archive = staging / pack.name
print(f"Joining {len(volumes)} parts into {pack.name}...")
join_volumes(volumes, archive)
for volume in volumes:
volume.unlink()
volumes = [archive]
if not checksums:
print(f"No {CHECKSUMS_ASSET} in the release, skipping the checksum.")
return volumes
for archive in volumes:
_check(archive, checksums)
return volumes
def show_info(platform: str, release: dict) -> None:
"""Show pack information for a platform."""
pack = find_pack(release, platform)
+1 -1
View File
@@ -1 +1 @@
"""Release artifacts: what the packs of a release hold, its notes, and the checks of its assets."""
"""Release artifacts: what the packs of a release hold, its notes, the checks of its assets, and its download."""
+54
View File
@@ -0,0 +1,54 @@
"""The release endpoint the downloader trusts, and the latest release it names."""
from __future__ import annotations
import json
import os
import sys
import urllib.error
import urllib.parse
import urllib.request
from core.upstream import forge_headers, open_retrying
DEFAULT_API = "https://api.github.com"
REPO = "Abdess/retrobios"
_LOOPBACK_HOSTS = {"127.0.0.1", "::1", "localhost"}
def checked_url(value: str, label: str) -> str:
"""Refuse a URL that is neither HTTPS nor loopback.
This endpoint names the assets and, through them, the bytes that land in
the BIOS directory, so it is the trust anchor of the whole download.
Plain HTTP to loopback stays allowed: it is how this is tested end to end.
"""
parsed = urllib.parse.urlparse(value)
if parsed.scheme == "https":
return value.rstrip("/")
host = (parsed.hostname or "").lower()
if parsed.scheme == "http" and host in _LOOPBACK_HOSTS:
return value.rstrip("/")
print(f"Error: {label} must use HTTPS, got {value!r}", file=sys.stderr)
sys.exit(1)
API = checked_url(os.environ.get("RETROBIOS_API", DEFAULT_API), "RETROBIOS_API")
def get_latest_release() -> dict:
"""Fetch latest release info from GitHub API."""
url = f"{API}/repos/{REPO}/releases/latest"
# The anonymous quota is 60 calls an hour per address. The token goes to
# GitHub's API only: RETROBIOS_API can name any host.
headers = forge_headers(url, "application/vnd.github.v3+json", "retrobios-downloader/1.0")
req = urllib.request.Request(url, headers=headers)
try:
return json.loads(open_retrying(req, lambda resp: resp.read(), 30))
except urllib.error.HTTPError as e:
if e.code == 404:
print("No releases found. The repository may not have any releases yet.")
sys.exit(1)
raise
+119
View File
@@ -0,0 +1,119 @@
"""A platform pack downloaded into a staging directory, joined and checked."""
from __future__ import annotations
import shutil
import sys
import tempfile
import urllib.request
from pathlib import Path
from typing import TYPE_CHECKING
from core.hashing import compute_hashes, parse_sha256sums
from core.upstream import open_retrying
from release.latest import checked_url
from release.transfer import download_file
if TYPE_CHECKING:
from release.packgroups import Pack
CHECKSUMS_ASSET = "SHA256SUMS.txt"
STAGING_PREFIX = ".retrobios-download-"
MAX_CHECKSUMS_BYTES = 1 << 20
CHUNK = 1 << 20
def fetch_checksums(release: dict) -> dict[str, str]:
"""Read the published SHA-256 of each pack, keyed by archive name."""
for asset in release.get("assets", []):
if asset["name"] != CHECKSUMS_ASSET:
continue
url = checked_url(asset["browser_download_url"], "asset URL")
req = urllib.request.Request(
url, headers={"User-Agent": "retrobios-downloader/1.0"}
)
body = open_retrying(
req, lambda resp: resp.read(MAX_CHECKSUMS_BYTES), 60
).decode("utf-8", "replace")
# A file that is not sha256sum output refuses the download: read
# leniently, a `*name` line matched nothing and the pack went
# unchecked.
try:
return parse_sha256sums(body)
except ValueError as exc:
raise SystemExit(f"ERROR: {CHECKSUMS_ASSET}: {exc}") from exc
return {}
def join_volumes(parts: list[Path], dest: Path) -> None:
"""Concatenate split volumes into one archive, streaming."""
with open(dest, "wb") as out:
for part in parts:
with open(part, "rb") as src:
shutil.copyfileobj(src, out, CHUNK)
def make_staging(dest: Path) -> Path:
"""Return a staging directory of this run's own, on the destination volume.
A pack is gigabytes and that is the filesystem the user picked for them:
the system temp directory is a RAM disk on the appliances these packs
target. The name is unique per run because two downloads into one BIOS
folder used to share a fixed path, so whichever finished first removed the
other's archive mid-transfer and the second died on the missing file with
nothing installed.
"""
return Path(tempfile.mkdtemp(prefix=STAGING_PREFIX, dir=dest))
def _check(archive: Path, checksums: dict[str, str]) -> None:
"""Compare a downloaded file with its published SHA-256, when there is one."""
expected = checksums.get(archive.name)
if not expected:
print(f"No checksum published for {archive.name}, skipping.")
return
print(f"Checking {archive.name}...")
actual = compute_hashes(str(archive))["sha256"].lower()
if actual != expected:
archive.unlink()
print(
f"Error: checksum mismatch for {archive.name}\n"
f" expected {expected}\n got {actual}\n"
"Download the parts again: a truncated part gives this.",
file=sys.stderr,
)
sys.exit(1)
def fetch_pack(pack: Pack, staging: Path, checksums: dict[str, str]) -> list[Path]:
"""Download a pack and return the archives to extract, each one checked."""
if len(pack.parts) != pack.expected_parts:
print(
f"Error: the release lists {len(pack.parts)} of "
f"{pack.expected_parts} parts of {pack.name}.",
file=sys.stderr,
)
sys.exit(1)
staging.mkdir(parents=True, exist_ok=True)
volumes = []
for index, part in enumerate(pack.parts, start=1):
label = f"part {index}/{len(pack.parts)} " if len(pack.parts) > 1 else ""
target = staging / part["name"]
print(f"Downloading {part['name']} ({part.get('size', 0):,} bytes)...")
download_file(part["browser_download_url"], target, part.get("size", 0), label)
volumes.append(target)
if pack.joined:
archive = staging / pack.name
print(f"Joining {len(volumes)} parts into {pack.name}...")
join_volumes(volumes, archive)
for volume in volumes:
volume.unlink()
volumes = [archive]
if not checksums:
print(f"No {CHECKSUMS_ASSET} in the release, skipping the checksum.")
return volumes
for archive in volumes:
_check(archive, checksums)
return volumes
+89
View File
@@ -0,0 +1,89 @@
"""The assets of a release grouped into platform packs, and the pack of a platform."""
from __future__ import annotations
import re
from dataclasses import dataclass
from core.paths import REPO_ROOT
from model.releaserecord import PACK_SUFFIX, RECORD, load_record, match_key, pack_label, recorded_pack
from packs.parts import part_of
_VOLUME_RE = re.compile(rf"^(?P<base>.+{re.escape(PACK_SUFFIX)})\.(?P<index>\d+)$")
@dataclass(frozen=True)
class Pack:
"""A platform pack: one asset, or the files it was published in.
`joined` says the files are byte ranges of one archive. `expected_parts`
is the count a part's own name declares, so a release that lists fewer
is recognised before anything is downloaded.
"""
name: str
platform: str
parts: tuple[dict, ...]
size: int
joined: bool = False
expected_parts: int = 1
def group_packs(release: dict) -> list[Pack]:
"""Group release assets into packs, the files of one pack folded together."""
groups: dict[str, list[tuple[int, dict]]] = {}
joined: set[str] = set()
expected: dict[str, int] = {}
for asset in release.get("assets", []):
name = asset["name"]
volume = _VOLUME_RE.match(name)
part = part_of(name)
if volume:
groups.setdefault(volume["base"], []).append((int(volume["index"]), asset))
joined.add(volume["base"])
elif part:
base, index, count = part
groups.setdefault(base, []).append((index, asset))
expected[base] = count
elif name.endswith(PACK_SUFFIX):
groups.setdefault(name, []).append((0, asset))
packs = []
for base, volumes in sorted(groups.items()):
parts = tuple(asset for _, asset in sorted(volumes, key=lambda v: v[0]))
packs.append(
Pack(
name=base,
platform=pack_label(base),
parts=parts,
size=sum(part.get("size", 0) for part in parts),
joined=base in joined,
expected_parts=expected.get(base, len(parts)),
)
)
return packs
def list_platforms(release: dict) -> list[str]:
"""List available platform packs from release assets."""
return sorted(pack.platform for pack in group_packs(release))
def find_pack(release: dict, platform: str) -> Pack | None:
"""Find the pack for a platform name.
release.json names the platforms each pack serves, and is read when it
records this release. Otherwise the platform is matched against the pack
names, the shortest first: RetroArch_v1.22.2 is the full pack, and
RetroArch_v1.22.2_AndroidArm64V8A one target's.
"""
packs = group_packs(release)
record = load_record(REPO_ROOT / RECORD)
if record.get("tag") and record.get("tag") == release.get("tag_name"):
name = recorded_pack(platform, record)
return next((pack for pack in packs if pack.name == name), None)
needle = match_key(platform)
if not needle:
return None
matches = [pack for pack in packs if needle in match_key(pack.name)]
return min(matches, key=lambda pack: (len(match_key(pack.name)), pack.name), default=None)
+74
View File
@@ -0,0 +1,74 @@
"""One release asset downloaded to disk, with its progress line."""
from __future__ import annotations
import os
import shutil
import sys
import urllib.request
from typing import TYPE_CHECKING
from core.sizes import size_text
from core.upstream import open_retrying
from release.latest import checked_url
if TYPE_CHECKING:
import http.client
from pathlib import Path
def download_file(
url: str, dest: Path, expected_size: int = 0, label: str = ""
) -> None:
"""Download a file with progress indication.
core.upstream.open_retrying asks again after a dropped connection, a
stream cut midway or a 5xx, and waits out a rate limit: each attempt
writes `dest` from its first byte.
"""
url = checked_url(url, "asset URL")
req = urllib.request.Request(
url, headers={"User-Agent": "retrobios-downloader/1.0"}
)
# A redrawn bar only on a terminal: written to a log, 32,768 redraws of a
# 2 GiB part made one line of nearly 3 MB.
live = sys.stdout.isatty() and os.environ.get("TERM") != "dumb"
def save(resp: http.client.HTTPResponse) -> int:
total = int(resp.headers.get("Content-Length", expected_size))
downloaded = 0
shown = -1
with open(dest, "wb") as f:
while chunk := resp.read(65536):
f.write(chunk)
downloaded += len(chunk)
if total > 0 and live:
pct = downloaded * 100 // total
if pct != shown:
shown = pct
columns = shutil.get_terminal_size((80, 24)).columns
line = progress_line(label, downloaded, total, columns)
print(f"\r\033[K{line}", end="", flush=True)
return downloaded
downloaded = open_retrying(req, save, 300)
if live:
print()
else:
print(f" {label}{downloaded:,} bytes")
if expected_size and downloaded != expected_size:
raise ValueError(f"downloaded {downloaded} bytes, expected {expected_size}")
def progress_line(label: str, done: int, total: int, columns: int) -> str:
"""One physical line shorter than the terminal: a wrapped line leaves a
copy of itself on every redraw, since \\r goes back one row only. The
bar shrinks first, then goes."""
pct = done * 100 // total
figures = f" {pct}% ({size_text(done)}/{size_text(total)})"
room = min(50, columns - 1 - len(f" {label}[]") - len(figures))
if room < 10:
return f" {label}{figures.strip()}"[: columns - 1]
filled = room * pct // 100
return f" {label}[{'=' * filled}{' ' * (room - filled)}]{figures}"
+3
View File
@@ -52,6 +52,9 @@ COMMANDS = {
"check_release_assets.py": ("release/assets.py",),
"sync_release_assets.py": ("release/sync.py",),
"restore_large_files.py": ("release/restore.py",),
"download.py": (
"release/latest.py", "release/packgroups.py", "release/transfer.py", "release/packfetch.py",
),
"build_installer.py": ("installer_build/amalgamate.py",),
"pin_installer.py": ("installer_build/pins.py",),
"build_port.py": ("installer_build/port.py",),
+32 -37
View File
@@ -33,6 +33,7 @@ from pathlib import Path
from unittest import mock
from packs import parts as packs_parts
from release import packfetch, packgroups, transfer
REPO_ROOT = Path(__file__).resolve().parent.parent
_spec = importlib.util.spec_from_file_location(
@@ -84,12 +85,12 @@ class TestPackGrouping(unittest.TestCase):
self.assertIn("EmuDeck", out.getvalue())
def test_whole_pack_has_one_part(self):
packs = download.group_packs(_release(["EmuDeck_2.3.8_BIOS_Pack.zip"]))
packs = packgroups.group_packs(_release(["EmuDeck_2.3.8_BIOS_Pack.zip"]))
self.assertEqual([p.name for p in packs], ["EmuDeck_2.3.8_BIOS_Pack.zip"])
self.assertEqual(len(packs[0].parts), 1)
def test_volumes_group_into_one_pack(self):
packs = download.group_packs(
packs = packgroups.group_packs(
_release(
[
"Batocera_43.1_BIOS_Pack.zip.001",
@@ -107,7 +108,7 @@ class TestPackGrouping(unittest.TestCase):
)
def test_pack_size_is_the_sum_of_its_volumes(self):
packs = download.group_packs(
packs = packgroups.group_packs(
_release(
[
"Batocera_43.1_BIOS_Pack.zip.001",
@@ -119,7 +120,7 @@ class TestPackGrouping(unittest.TestCase):
self.assertEqual(packs[0].size, 14)
def test_volumes_order_numerically_not_lexically(self):
packs = download.group_packs(
packs = packgroups.group_packs(
_release(
[
"Big_BIOS_Pack.zip.010",
@@ -134,7 +135,7 @@ class TestPackGrouping(unittest.TestCase):
)
def test_zip_parts_group_into_one_pack(self):
packs = download.group_packs(
packs = packgroups.group_packs(
_release(
[
"Batocera_43.1_BIOS_Pack.part2of2.zip",
@@ -160,7 +161,7 @@ class TestPackGrouping(unittest.TestCase):
def test_zip_parts_order_numerically_not_lexically(self):
names = [f"Big_BIOS_Pack.part{n}of12.zip" for n in (10, 9, 1)]
pack = download.group_packs(_release(names))[0]
pack = packgroups.group_packs(_release(names))[0]
self.assertEqual(
[part["name"] for part in pack.parts],
[f"Big_BIOS_Pack.part{n}of12.zip" for n in (1, 9, 10)],
@@ -168,34 +169,34 @@ class TestPackGrouping(unittest.TestCase):
self.assertEqual(pack.expected_parts, 12)
def test_byte_range_volumes_are_joined(self):
pack = download.group_packs(
pack = packgroups.group_packs(
_release(["Old_BIOS_Pack.zip.001", "Old_BIOS_Pack.zip.002"])
)[0]
self.assertTrue(pack.joined)
def test_other_assets_are_not_packs(self):
packs = download.group_packs(_release(["SHA256SUMS.txt", "database.json"]))
packs = packgroups.group_packs(_release(["SHA256SUMS.txt", "database.json"]))
self.assertEqual(packs, [])
def test_list_platforms_names_split_packs(self):
names = download.list_platforms(_release(RELEASE_ASSETS))
names = packgroups.list_platforms(_release(RELEASE_ASSETS))
self.assertIn("Batocera 43.1", names)
self.assertIn("RetroDECK 0.10.9b", names)
self.assertEqual(len(names), 5)
def test_find_pack_resolves_a_split_platform(self):
pack = download.find_pack(_release(RELEASE_ASSETS), "batocera")
pack = packgroups.find_pack(_release(RELEASE_ASSETS), "batocera")
self.assertIsNotNone(pack)
self.assertEqual(pack.name, "Batocera_43.1_BIOS_Pack.zip")
self.assertEqual(len(pack.parts), 2)
def test_find_pack_maps_retroarch_to_the_lakka_asset(self):
pack = download.find_pack(_release(RELEASE_ASSETS), "retroarch")
pack = packgroups.find_pack(_release(RELEASE_ASSETS), "retroarch")
self.assertEqual(pack.name, "RetroArch_Lakka_v1.22.2_BIOS_Pack.zip")
def test_find_pack_prefers_the_full_pack_to_a_target_pack(self):
names = ["RetroArch_v1.22.2_AndroidArm64V8A_BIOS_Pack.zip", "RetroArch_v1.22.2_BIOS_Pack.zip"]
pack = download.find_pack(_release(names), "retroarch")
pack = packgroups.find_pack(_release(names), "retroarch")
self.assertEqual(pack.name, "RetroArch_v1.22.2_BIOS_Pack.zip")
def test_find_pack_reads_the_record_of_this_release(self):
@@ -205,20 +206,20 @@ class TestPackGrouping(unittest.TestCase):
}}
release = {**_release(["RetroArch_Lakka_v1.22.2_BIOS_Pack.zip",
"RetroArch_v1.22.2_BIOS_Pack.zip"]), "tag_name": "v1"}
with mock.patch.object(download, "load_record", return_value=record):
self.assertEqual(download.find_pack(release, "lakka").name,
with mock.patch.object(packgroups, "load_record", return_value=record):
self.assertEqual(packgroups.find_pack(release, "lakka").name,
"RetroArch_Lakka_v1.22.2_BIOS_Pack.zip")
self.assertIsNone(download.find_pack(release, "batocera"))
with mock.patch.object(download, "load_record", return_value={**record, "tag": "v0"}):
self.assertEqual(download.find_pack(release, "lakka").name,
self.assertIsNone(packgroups.find_pack(release, "batocera"))
with mock.patch.object(packgroups, "load_record", return_value={**record, "tag": "v0"}):
self.assertEqual(packgroups.find_pack(release, "lakka").name,
"RetroArch_Lakka_v1.22.2_BIOS_Pack.zip")
def test_find_pack_returns_none_for_an_unknown_platform(self):
self.assertIsNone(download.find_pack(_release(RELEASE_ASSETS), "nintendo"))
self.assertIsNone(packgroups.find_pack(_release(RELEASE_ASSETS), "nintendo"))
def test_find_pack_resolves_a_platform_id_that_drops_separators(self):
# The platform is `misterfpga` everywhere else, but the asset is MiSTer_FPGA.
pack = download.find_pack(
pack = packgroups.find_pack(
_release(RELEASE_ASSETS + ["MiSTer_FPGA_2026-08-29_BIOS_Pack.zip"]),
"misterfpga",
)
@@ -243,7 +244,7 @@ class TestJoinVolumes(unittest.TestCase):
self.assertGreater(len(parts), 1)
joined = tmp / "joined.zip"
download.join_volumes(parts, joined)
packfetch.join_volumes(parts, joined)
self.assertEqual(joined.read_bytes(), raw)
with zipfile.ZipFile(joined) as zf:
@@ -255,21 +256,17 @@ class TestProgressLineWidth(unittest.TestCase):
redraw wrapped and left a line behind."""
def test_the_line_fits_every_width(self):
from download import _progress_line
for columns in (20, 40, 80, 120, 200):
for done in (0, 1_000_000_000, 2_000_000_000):
with self.subTest(columns=columns, done=done):
line = _progress_line("part 1/2 ", done, 2_000_000_000, columns)
line = transfer.progress_line("part 1/2 ", done, 2_000_000_000, columns)
self.assertLess(len(line), columns)
self.assertIn("%", line)
def test_the_figures_read_like_the_site(self):
"""The bar counted decimal megabytes (8,127 MB) where --info and the
site gave the same pack as 7.6 GB."""
from download import _progress_line
line = _progress_line("", 1024**3, 8_127_352_876, 200)
line = transfer.progress_line("", 1024**3, 8_127_352_876, 200)
self.assertTrue(line.endswith(" 13% (1.0 GB/7.6 GB)"), line)
@@ -281,16 +278,16 @@ class TestStagingIsolation(unittest.TestCase):
self.addCleanup(shutil.rmtree, self.dest, True)
def test_two_runs_stage_in_separate_directories(self):
first = download.make_staging(self.dest)
second = download.make_staging(self.dest)
first = packfetch.make_staging(self.dest)
second = packfetch.make_staging(self.dest)
self.assertNotEqual(first, second)
for staging in (first, second):
self.assertEqual(staging.parent, self.dest)
self.assertTrue(staging.name.startswith(download.STAGING_PREFIX))
self.assertTrue(staging.name.startswith(packfetch.STAGING_PREFIX))
def test_one_run_cleaning_up_leaves_the_other_transfer_alone(self):
finished = download.make_staging(self.dest)
in_flight = download.make_staging(self.dest)
finished = packfetch.make_staging(self.dest)
in_flight = packfetch.make_staging(self.dest)
(in_flight / "Batocera_BIOS_Pack.zip").write_bytes(b"still downloading")
# What main() does in its finally clause once a pack is extracted.
@@ -699,8 +696,6 @@ class AProgressBarOnlyOnATerminal(unittest.TestCase):
from pathlib import Path as _Path
from unittest import mock
import download
class Body(_io.BytesIO):
headers = {"Content-Length": str(200_000)}
@@ -712,10 +707,10 @@ class AProgressBarOnlyOnATerminal(unittest.TestCase):
out = _io.StringIO()
with _tempfile.TemporaryDirectory() as directory, \
mock.patch.object(download.urllib.request, "urlopen",
mock.patch.object(transfer.urllib.request, "urlopen",
lambda *a, **k: Body(b"x" * 200_000)), \
contextlib.redirect_stdout(out):
download.download_file("https://example.com/a.zip",
transfer.download_file("https://example.com/a.zip",
_Path(directory) / "a.zip", 200_000, "a.zip ")
self.assertNotIn("\r", out.getvalue())
self.assertEqual(out.getvalue().count("\n"), 1)
@@ -741,12 +736,12 @@ class AProgressBarOnlyOnATerminal(unittest.TestCase):
answers = [Cut(b""), Body(b"packed")]
with tempfile.TemporaryDirectory() as directory, \
mock.patch.object(download.urllib.request, "urlopen",
mock.patch.object(transfer.urllib.request, "urlopen",
lambda *a, **k: answers.pop(0)), \
mock.patch.object(upstream, "_sleep", lambda _s: None), \
contextlib.redirect_stdout(io.StringIO()):
target = Path(directory) / "a.zip"
download.download_file("https://example.com/a.zip", target, 6, "a.zip ")
transfer.download_file("https://example.com/a.zip", target, 6, "a.zip ")
self.assertEqual(target.read_bytes(), b"packed")
self.assertEqual(answers, [])
+1 -1
View File
@@ -50,7 +50,7 @@ scripts/ all tooling (Python and pyyaml, jsonschema for schema c
exporter/ native format exporters (batocera, recalbox, emudeck...)
sitegen/ the site and README generators: pages, navigation, data files
probes/ real-condition runs: the campaign, the pack and region probes
release/ the release record, its notes and the checks of its assets
release/ the release record, its notes, the checks of its assets and the pack downloader
installer_build/ install.py from installer/, its pins, launchers and PyPI package
devtools/ the commit message rules and the checks of a pull request
schemas/ the data contracts behind validate_schemas.py: schemas and semantic invariants