mirror of
https://github.com/Abdess/retroarch_system.git
synced 2026-11-23 18:17:53 -06:00
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:
1 parent
ebabb03e74
commit
758bc76b6f
6 files changed
+173
-81
No files matched your search
@@ -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."""
|
||||
@@ -3,13 +3,12 @@
|
||||
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
|
||||
from release.downloaderror import DownloadError
|
||||
|
||||
DEFAULT_API = "https://api.github.com"
|
||||
REPO = "Abdess/retrobios"
|
||||
@@ -18,7 +17,7 @@ _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.
|
||||
"""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
|
||||
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()
|
||||
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)
|
||||
raise DownloadError(f"Error: {label} must use HTTPS, got {value!r}")
|
||||
|
||||
|
||||
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"
|
||||
def get_latest_release(api: str) -> dict:
|
||||
"""Fetch the latest release info from the releases endpoint *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")
|
||||
@@ -49,6 +44,7 @@ def get_latest_release() -> dict:
|
||||
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 DownloadError(
|
||||
"No releases found. The repository may not have any releases yet."
|
||||
) from e
|
||||
raise
|
||||
@@ -3,7 +3,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
@@ -11,10 +10,13 @@ from typing import TYPE_CHECKING
|
||||
|
||||
from core.hashing import compute_hashes, parse_sha256sums
|
||||
from core.upstream import open_retrying
|
||||
from release.downloaderror import DownloadError
|
||||
from release.latest import checked_url
|
||||
from release.transfer import download_file
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
|
||||
from release.packgroups import Pack
|
||||
|
||||
CHECKSUMS_ASSET = "SHA256SUMS.txt"
|
||||
@@ -41,7 +43,7 @@ def fetch_checksums(release: dict) -> dict[str, str]:
|
||||
try:
|
||||
return parse_sha256sums(body)
|
||||
except ValueError as exc:
|
||||
raise SystemExit(f"ERROR: {CHECKSUMS_ASSET}: {exc}") from exc
|
||||
raise DownloadError(f"ERROR: {CHECKSUMS_ASSET}: {exc}") from exc
|
||||
return {}
|
||||
|
||||
|
||||
@@ -66,54 +68,55 @@ def make_staging(dest: Path) -> Path:
|
||||
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."""
|
||||
expected = checksums.get(archive.name)
|
||||
if not expected:
|
||||
print(f"No checksum published for {archive.name}, skipping.")
|
||||
say(f"No checksum published for {archive.name}, skipping.")
|
||||
return
|
||||
print(f"Checking {archive.name}...")
|
||||
say(f"Checking {archive.name}...")
|
||||
actual = compute_hashes(str(archive))["sha256"].lower()
|
||||
if actual != expected:
|
||||
archive.unlink()
|
||||
print(
|
||||
raise DownloadError(
|
||||
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,
|
||||
"Download the parts again: a truncated part gives this."
|
||||
)
|
||||
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."""
|
||||
def fetch_pack(
|
||||
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:
|
||||
print(
|
||||
raise DownloadError(
|
||||
f"Error: the release lists {len(pack.parts)} of "
|
||||
f"{pack.expected_parts} parts of {pack.name}.",
|
||||
file=sys.stderr,
|
||||
f"{pack.expected_parts} parts of {pack.name}."
|
||||
)
|
||||
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)...")
|
||||
say(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}...")
|
||||
say(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.")
|
||||
say(f"No {CHECKSUMS_ASSET} in the release, skipping the checksum.")
|
||||
return volumes
|
||||
for archive in volumes:
|
||||
_check(archive, checksums)
|
||||
_check(archive, checksums, say)
|
||||
return volumes
|
||||
Reference in new issue
Block a user