refactor: raise download errors to the command

release.latest no longer reads RETROBIOS_API at import: download.py checks
it and passes the endpoint to get_latest_release. The release modules raise
DownloadError and hand progress lines to a callback, so download.py reports
every failure on stderr with exit code 1, the missing release included.
This commit is contained in:
Abdessamad Derraz committed 2026-11-22 02:26:45 +01:00
1 parent ebabb03e74
commit 758bc76b6f
6 files changed
+173 -81

No files matched your search

+54 -47
View File
@@ -29,13 +29,19 @@ from pathlib import Path
sys.path.insert(0, os.path.dirname(__file__)) sys.path.insert(0, os.path.dirname(__file__))
from core.upstream import UpstreamError from core.upstream import UpstreamError
from core.ziptools import safe_extract_zip from core.ziptools import safe_extract_zip
from release.latest import get_latest_release from release.downloaderror import DownloadError
from release.latest import DEFAULT_API, checked_url, get_latest_release
from release.packfetch import fetch_checksums, fetch_pack, make_staging from release.packfetch import fetch_checksums, fetch_pack, make_staging
from release.packgroups import find_pack, list_platforms from release.packgroups import find_pack, list_platforms
from release.packinfo import exit_without_pack, show_info from release.packinfo import exit_without_pack, show_info
FETCH_ERRORS = (
urllib.error.URLError, OSError, http.client.HTTPException, UpstreamError,
json.JSONDecodeError,
)
def main() -> None:
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser( parser = argparse.ArgumentParser(
allow_abbrev=False, allow_abbrev=False,
description="Download BIOS packs from GitHub Releases", description="Download BIOS packs from GitHub Releases",
@@ -53,62 +59,63 @@ To check files already in place, use: python install.py --check
parser.add_argument("dest", nargs="?", help="Destination directory") parser.add_argument("dest", nargs="?", help="Destination directory")
parser.add_argument("--list", action="store_true", help="List available platforms") parser.add_argument("--list", action="store_true", help="List available platforms")
parser.add_argument("--info", action="store_true", help="Show platform info") parser.add_argument("--info", action="store_true", help="Show platform info")
args = parser.parse_args() return parser
if args.list:
try: def main() -> None:
release = get_latest_release() parser = build_parser()
platforms = list_platforms(release) args = parser.parse_args()
try:
api = checked_url(os.environ.get("RETROBIOS_API", DEFAULT_API), "RETROBIOS_API")
if args.list:
try:
platforms = list_platforms(get_latest_release(api))
except FETCH_ERRORS as e:
print(f"Error: {e}", file=sys.stderr)
sys.exit(1)
if platforms: if platforms:
print("Available platforms:") print("Available platforms:")
for p in platforms: for p in platforms:
print(f" - {p}") print(f" - {p}")
else: else:
print("No platform packs found in latest release") print("No platform packs found in latest release")
except ( return
urllib.error.URLError,
urllib.error.HTTPError, if not args.platform:
OSError, parser.error("Platform name required (use --list to see options)")
http.client.HTTPException,
UpstreamError, try:
json.JSONDecodeError, release = get_latest_release(api)
) as e: except FETCH_ERRORS as e:
print(f"Error: {e}", file=sys.stderr) print(f"Error fetching release info: {e}", file=sys.stderr)
sys.exit(1) sys.exit(1)
return
if not args.platform: if args.info:
parser.error("Platform name required (use --list to see options)") show_info(args.platform, release)
return
try: if not args.dest:
release = get_latest_release() parser.error("Destination directory required")
except (urllib.error.URLError, OSError, http.client.HTTPException, UpstreamError,
json.JSONDecodeError) as e: pack = find_pack(release, args.platform)
print(f"Error fetching release info: {e}", file=sys.stderr) if not pack:
exit_without_pack(args.platform, release)
dest = Path(os.path.expanduser(args.dest))
dest.mkdir(parents=True, exist_ok=True)
staging = make_staging(dest)
try:
archives = fetch_pack(pack, staging, fetch_checksums(release), print)
print(f"Extracting to {dest}/...")
for archive in archives:
safe_extract_zip(str(archive), str(dest))
finally:
shutil.rmtree(staging, ignore_errors=True)
except DownloadError as exc:
print(exc, file=sys.stderr)
sys.exit(1) sys.exit(1)
if args.info:
show_info(args.platform, release)
return
if not args.dest:
parser.error("Destination directory required")
pack = find_pack(release, args.platform)
if not pack:
exit_without_pack(args.platform, release)
dest = Path(os.path.expanduser(args.dest))
dest.mkdir(parents=True, exist_ok=True)
staging = make_staging(dest)
try:
archives = fetch_pack(pack, staging, fetch_checksums(release))
print(f"Extracting to {dest}/...")
for archive in archives:
safe_extract_zip(str(archive), str(dest))
finally:
shutil.rmtree(staging, ignore_errors=True)
print("Done!") print("Done!")
+7
View File
@@ -0,0 +1,7 @@
"""The error a release download stops on, worded for the user who reads it."""
from __future__ import annotations
class DownloadError(ValueError):
"""A release download that cannot go on: its message is printed as is."""
+9 -13
View File
@@ -3,13 +3,12 @@
from __future__ import annotations from __future__ import annotations
import json import json
import os
import sys
import urllib.error import urllib.error
import urllib.parse import urllib.parse
import urllib.request import urllib.request
from core.upstream import forge_headers, open_retrying from core.upstream import forge_headers, open_retrying
from release.downloaderror import DownloadError
DEFAULT_API = "https://api.github.com" DEFAULT_API = "https://api.github.com"
REPO = "Abdess/retrobios" REPO = "Abdess/retrobios"
@@ -18,7 +17,7 @@ _LOOPBACK_HOSTS = {"127.0.0.1", "::1", "localhost"}
def checked_url(value: str, label: str) -> str: def checked_url(value: str, label: str) -> str:
"""Refuse a URL that is neither HTTPS nor loopback. """Return *value* cleaned, or raise DownloadError when it is neither HTTPS nor loopback.
This endpoint names the assets and, through them, the bytes that land in 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. the BIOS directory, so it is the trust anchor of the whole download.
@@ -30,16 +29,12 @@ def checked_url(value: str, label: str) -> str:
host = (parsed.hostname or "").lower() host = (parsed.hostname or "").lower()
if parsed.scheme == "http" and host in _LOOPBACK_HOSTS: if parsed.scheme == "http" and host in _LOOPBACK_HOSTS:
return value.rstrip("/") return value.rstrip("/")
print(f"Error: {label} must use HTTPS, got {value!r}", file=sys.stderr) raise DownloadError(f"Error: {label} must use HTTPS, got {value!r}")
sys.exit(1)
API = checked_url(os.environ.get("RETROBIOS_API", DEFAULT_API), "RETROBIOS_API") def get_latest_release(api: str) -> dict:
"""Fetch the latest release info from the releases endpoint *api*."""
url = f"{api}/repos/{REPO}/releases/latest"
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 # The anonymous quota is 60 calls an hour per address. The token goes to
# GitHub's API only: RETROBIOS_API can name any host. # GitHub's API only: RETROBIOS_API can name any host.
headers = forge_headers(url, "application/vnd.github.v3+json", "retrobios-downloader/1.0") headers = forge_headers(url, "application/vnd.github.v3+json", "retrobios-downloader/1.0")
@@ -49,6 +44,7 @@ def get_latest_release() -> dict:
return json.loads(open_retrying(req, lambda resp: resp.read(), 30)) return json.loads(open_retrying(req, lambda resp: resp.read(), 30))
except urllib.error.HTTPError as e: except urllib.error.HTTPError as e:
if e.code == 404: if e.code == 404:
print("No releases found. The repository may not have any releases yet.") raise DownloadError(
sys.exit(1) "No releases found. The repository may not have any releases yet."
) from e
raise raise
+22 -19
View File
@@ -3,7 +3,6 @@
from __future__ import annotations from __future__ import annotations
import shutil import shutil
import sys
import tempfile import tempfile
import urllib.request import urllib.request
from pathlib import Path from pathlib import Path
@@ -11,10 +10,13 @@ from typing import TYPE_CHECKING
from core.hashing import compute_hashes, parse_sha256sums from core.hashing import compute_hashes, parse_sha256sums
from core.upstream import open_retrying from core.upstream import open_retrying
from release.downloaderror import DownloadError
from release.latest import checked_url from release.latest import checked_url
from release.transfer import download_file from release.transfer import download_file
if TYPE_CHECKING: if TYPE_CHECKING:
from collections.abc import Callable
from release.packgroups import Pack from release.packgroups import Pack
CHECKSUMS_ASSET = "SHA256SUMS.txt" CHECKSUMS_ASSET = "SHA256SUMS.txt"
@@ -41,7 +43,7 @@ def fetch_checksums(release: dict) -> dict[str, str]:
try: try:
return parse_sha256sums(body) return parse_sha256sums(body)
except ValueError as exc: except ValueError as exc:
raise SystemExit(f"ERROR: {CHECKSUMS_ASSET}: {exc}") from exc raise DownloadError(f"ERROR: {CHECKSUMS_ASSET}: {exc}") from exc
return {} return {}
@@ -66,54 +68,55 @@ def make_staging(dest: Path) -> Path:
return Path(tempfile.mkdtemp(prefix=STAGING_PREFIX, dir=dest)) return Path(tempfile.mkdtemp(prefix=STAGING_PREFIX, dir=dest))
def _check(archive: Path, checksums: dict[str, str]) -> None: def _check(archive: Path, checksums: dict[str, str], say: Callable[[str], None]) -> None:
"""Compare a downloaded file with its published SHA-256, when there is one.""" """Compare a downloaded file with its published SHA-256, when there is one."""
expected = checksums.get(archive.name) expected = checksums.get(archive.name)
if not expected: if not expected:
print(f"No checksum published for {archive.name}, skipping.") say(f"No checksum published for {archive.name}, skipping.")
return return
print(f"Checking {archive.name}...") say(f"Checking {archive.name}...")
actual = compute_hashes(str(archive))["sha256"].lower() actual = compute_hashes(str(archive))["sha256"].lower()
if actual != expected: if actual != expected:
archive.unlink() archive.unlink()
print( raise DownloadError(
f"Error: checksum mismatch for {archive.name}\n" f"Error: checksum mismatch for {archive.name}\n"
f" expected {expected}\n got {actual}\n" f" expected {expected}\n got {actual}\n"
"Download the parts again: a truncated part gives this.", "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]: def fetch_pack(
"""Download a pack and return the archives to extract, each one checked.""" pack: Pack, staging: Path, checksums: dict[str, str], say: Callable[[str], None]
) -> list[Path]:
"""Download a pack and return the archives to extract, each one checked.
Each progress line goes to *say*, and a failure raises DownloadError.
"""
if len(pack.parts) != pack.expected_parts: if len(pack.parts) != pack.expected_parts:
print( raise DownloadError(
f"Error: the release lists {len(pack.parts)} of " f"Error: the release lists {len(pack.parts)} of "
f"{pack.expected_parts} parts of {pack.name}.", f"{pack.expected_parts} parts of {pack.name}."
file=sys.stderr,
) )
sys.exit(1)
staging.mkdir(parents=True, exist_ok=True) staging.mkdir(parents=True, exist_ok=True)
volumes = [] volumes = []
for index, part in enumerate(pack.parts, start=1): for index, part in enumerate(pack.parts, start=1):
label = f"part {index}/{len(pack.parts)} " if len(pack.parts) > 1 else "" label = f"part {index}/{len(pack.parts)} " if len(pack.parts) > 1 else ""
target = staging / part["name"] target = staging / part["name"]
print(f"Downloading {part['name']} ({part.get('size', 0):,} bytes)...") say(f"Downloading {part['name']} ({part.get('size', 0):,} bytes)...")
download_file(part["browser_download_url"], target, part.get("size", 0), label) download_file(part["browser_download_url"], target, part.get("size", 0), label)
volumes.append(target) volumes.append(target)
if pack.joined: if pack.joined:
archive = staging / pack.name archive = staging / pack.name
print(f"Joining {len(volumes)} parts into {pack.name}...") say(f"Joining {len(volumes)} parts into {pack.name}...")
join_volumes(volumes, archive) join_volumes(volumes, archive)
for volume in volumes: for volume in volumes:
volume.unlink() volume.unlink()
volumes = [archive] volumes = [archive]
if not checksums: if not checksums:
print(f"No {CHECKSUMS_ASSET} in the release, skipping the checksum.") say(f"No {CHECKSUMS_ASSET} in the release, skipping the checksum.")
return volumes return volumes
for archive in volumes: for archive in volumes:
_check(archive, checksums) _check(archive, checksums, say)
return volumes return volumes
+1 -1
View File
@@ -147,7 +147,7 @@ COMMANDS = {
), ),
"download.py": ( "download.py": (
"release/latest.py", "release/packgroups.py", "release/transfer.py", "release/packfetch.py", "release/latest.py", "release/packgroups.py", "release/transfer.py", "release/packfetch.py",
"release/packinfo.py", "release/packinfo.py", "release/downloaderror.py",
), ),
"cleanup_disk.py": ("devtools/diskcleanup.py",), "cleanup_disk.py": ("devtools/diskcleanup.py",),
"migrate.py": ("devtools/biosclassify.py", "devtools/biosmigrate.py"), "migrate.py": ("devtools/biosclassify.py", "devtools/biosmigrate.py"),
+80 -1
View File
@@ -31,7 +31,8 @@ from pathlib import Path
from unittest import mock from unittest import mock
from packs import parts as packs_parts from packs import parts as packs_parts
from release import packfetch, packgroups, packinfo, transfer from release import latest, packfetch, packgroups, packinfo, transfer
from release.downloaderror import DownloadError
REPO_ROOT = Path(__file__).resolve().parent.parent REPO_ROOT = Path(__file__).resolve().parent.parent
@@ -522,6 +523,71 @@ class TestDownloadPython(DownloaderCase):
self.assertIn("RETROBIOS_API", proc.stderr) self.assertIn("RETROBIOS_API", proc.stderr)
def test_a_missing_release_is_reported_on_stderr(self):
"""The 404 message went to stdout, where a script reads platform names."""
self.server.index.unlink()
proc = self.run_cli("--list", expect_success=False)
self.assertEqual(proc.returncode, 1)
self.assertEqual(proc.stdout, "")
self.assertEqual(
proc.stderr,
"No releases found. The repository may not have any releases yet.\n",
)
class TestDownloadLibrary(DownloaderCase):
"""The release modules raise DownloadError and leave printing to the command."""
def fetch(self) -> tuple[list[Path], list[str]]:
release = latest.get_latest_release(self.server.base)
pack = packgroups.find_pack(release, self.platform)
assert pack is not None
lines: list[str] = []
staging = packfetch.make_staging(self.tmpdir)
with contextlib.redirect_stdout(io.StringIO()):
archives = packfetch.fetch_pack(
pack, staging, packfetch.fetch_checksums(release), lines.append
)
return archives, lines
def test_progress_lines_go_to_the_callback(self):
archives, lines = self.fetch()
self.assertEqual(len(archives), 1)
self.assertIn(f"Checking {self.pack_name}...", lines)
self.assertTrue(any(line.startswith("Downloading ") for line in lines))
def test_a_checksum_mismatch_raises(self):
self.server.corrupt_last_volume()
with self.assertRaises(DownloadError) as raised:
self.fetch()
self.assertIn("checksum mismatch", str(raised.exception))
def test_a_missing_release_raises(self):
self.server.index.unlink()
with self.assertRaises(DownloadError) as raised:
latest.get_latest_release(self.server.base)
self.assertIn("No releases found", str(raised.exception))
def test_a_plain_http_url_raises(self):
with self.assertRaises(DownloadError) as raised:
latest.checked_url("http://api.example.com/", "RETROBIOS_API")
self.assertEqual(
str(raised.exception),
"Error: RETROBIOS_API must use HTTPS, got 'http://api.example.com/'",
)
self.assertEqual(latest.checked_url("https://a.example/", "x"), "https://a.example")
def test_importing_the_library_ignores_the_endpoint_variable(self):
"""A stray RETROBIOS_API ended any process importing release.transfer."""
env = dict(os.environ, RETROBIOS_API="http://api.example.com")
proc = subprocess.run(
["python3", "-c", "from release import packfetch, transfer; print('imported')"],
cwd=REPO_ROOT / "scripts", env=env, capture_output=True, text=True,
timeout=60, check=False,
)
self.assertEqual((proc.returncode, proc.stdout), (0, "imported\n"), proc.stderr)
@unittest.skipUnless( @unittest.skipUnless(
shutil.which("curl") and shutil.which("unzip"), "curl and unzip required" shutil.which("curl") and shutil.which("unzip"), "curl and unzip required"
) )
@@ -674,6 +740,19 @@ class TestZipPartsShell(ZipPartsTests, ZipPartsCase, TestDownloadShell):
pass pass
class TestZipPartsLibrary(ZipPartsCase, TestDownloadLibrary):
def test_progress_lines_go_to_the_callback(self):
archives, lines = self.fetch()
self.assertEqual(len(archives), 2)
self.assertTrue(any(line.startswith("Checking ") for line in lines))
def test_a_short_part_list_raises(self):
self.server.unlist_last_part()
with self.assertRaises(DownloadError) as raised:
self.fetch()
self.assertIn("lists 1 of 2 parts", str(raised.exception))
class AProgressBarOnlyOnATerminal(unittest.TestCase): class AProgressBarOnlyOnATerminal(unittest.TestCase):
"""Redirected to a log, download.py wrote a carriage-return redraw per """Redirected to a log, download.py wrote a carriage-return redraw per