diff --git a/install.ps1 b/install.ps1 index 98e8ffb92..6eedc6941 100644 --- a/install.ps1 +++ b/install.ps1 @@ -16,7 +16,7 @@ # and Invoke-WebRequest throws on a cut transfer before the hash is read: # the site's build rewrites this line there (scripts/sitebootstrap.py). $mismatchAdvice = "The download was most likely cut short: try again. Within minutes of an update of this project the two files can come from caches of different ages. Waiting five minutes settles that." - $defaultInstallSha256 = "9912b09dd3b6510a2ce00df042f234c74f23052e4ec0d100e2c3b48c34b502cb" + $defaultInstallSha256 = "581acaf87f2414ef9e1bfecb068ed8df6402f6f29b602ac5c3d3682f73710811" # The pin above refuses any changed byte: this cap only stops a body that # cannot be the installer (a sign-in portal's page) before it is hashed. $maximumInstallerBytes = 8MB diff --git a/install.py b/install.py index 42df4a838..7d0347667 100644 --- a/install.py +++ b/install.py @@ -478,18 +478,19 @@ def region_title(name: str) -> str: # installer came from. RETROBIOS_REF pins them to a tag or a commit when # reproducibility matters. DEFAULT_RELEASE_REF = "main" -RELEASE_REF = os.environ.get("RETROBIOS_REF", DEFAULT_RELEASE_REF) -DEFAULT_BASE_URL = ( - "https://raw.githubusercontent.com/Abdess/retrobios/" - + urllib.parse.quote(RELEASE_REF, safe="") -) + + +def default_base_url(ref: str) -> str: + """The project's own address for the file lists of ref.""" + return ("https://raw.githubusercontent.com/Abdess/retrobios/" + + urllib.parse.quote(ref, safe="")) _LOOPBACK_HOSTS = ("localhost", "127.0.0.1", "::1") def _checked_base_url(value: str) -> str: - """Refuse a base URL that is neither HTTPS nor loopback. + """Refuse a base URL that is neither HTTPS nor loopback, as ValueError. This base serves the manifest and the files it declares, so whoever controls it controls the expected hashes too and verification stops @@ -505,22 +506,69 @@ def _checked_base_url(value: str) -> str: host = (parsed.hostname or "").lower() if parsed.scheme == "http" and host in _LOOPBACK_HOSTS: return value - print( - f"Error: RETROBIOS_BASE_URL must use HTTPS, got {value!r}", - file=sys.stderr, - ) - sys.exit(1) + raise ValueError(f"RETROBIOS_BASE_URL must use HTTPS, got {value!r}") -BASE_URL = _checked_base_url(os.environ.get("RETROBIOS_BASE_URL", DEFAULT_BASE_URL)) -MANIFEST_URL = f"{BASE_URL}/install/{{platform}}.json" -TARGETS_URL = f"{BASE_URL}/install/targets/{{platform}}.json" # What --standalone reads, apart from the list every run downloads. STANDALONE_DIR = "standalone" -STANDALONE_URL = f"{BASE_URL}/install/standalone/{{platform}}.json" -RAW_FILE_URL = f"{BASE_URL}/{{path}}" +class Remote(NamedTuple): + """Where a run reads its lists and files: the revision, the base + address, and whether RETROBIOS_BASE_URL chose that base.""" + + ref: str + base: str + overridden: bool + + @property + def manifest_url(self) -> str: + return f"{self.base}/install/{{platform}}.json" + + @property + def targets_url(self) -> str: + return f"{self.base}/install/targets/{{platform}}.json" + + @property + def standalone_url(self) -> str: + return f"{self.base}/install/{STANDALONE_DIR}/{{platform}}.json" + + @property + def raw_file_url(self) -> str: + return f"{self.base}/{{path}}" + + +def remote_from_env() -> Remote: + """The remote RETROBIOS_REF and RETROBIOS_BASE_URL name, ValueError for + a base that is neither HTTPS nor loopback. A variable set but empty is + unset, as every other reading of them takes it.""" + ref = os.environ.get("RETROBIOS_REF") or DEFAULT_RELEASE_REF + override = os.environ.get("RETROBIOS_BASE_URL") or "" + if override: + return Remote(ref, _checked_base_url(override), True) + return Remote(ref, default_base_url(ref), False) + + +# The remote main resolved, for the length of its run. +_IN_USE: list[Remote] = [] + + +@contextlib.contextmanager +def remote_in_use(remote: Remote) -> Iterator[None]: + """remote answers active_remote() until the block ends.""" + _IN_USE.append(remote) + try: + yield + finally: + _IN_USE.pop() + + +def active_remote() -> Remote: + """The remote of this run: the one main resolved, else the one the + environment names now, for a caller that did not come through main.""" + return _IN_USE[-1] if _IN_USE else remote_from_env() + + RELEASE_URL = ( "https://github.com/Abdess/retrobios/releases/download/large-files/{asset}" ) @@ -7607,17 +7655,17 @@ def network_words( return code, words -def _address_lines(url: str) -> list[str]: +OVERRIDE_LINE = (" RETROBIOS_BASE_URL is set in this environment and chose that " + "address: unset it to read from the project itself.") + + +def _address_lines(url: str, overridden: bool) -> list[str]: """The address that failed, and the override that chose it if one did. A RETROBIOS_BASE_URL left from a mirror that is down read as a network fault: neither the host nor the variable was named. """ - lines = [f" Address: {url}"] - if os.environ.get("RETROBIOS_BASE_URL"): - lines.append(" RETROBIOS_BASE_URL is set in this environment and chose that " - "address: unset it to read from the project itself.") - return lines + return [f" Address: {url}", *([OVERRIDE_LINE] if overridden else [])] def _open_socket( @@ -7728,7 +7776,7 @@ def _fetch_json( raise AssertionError("unreachable") -def _manifest_invalid(plat: str, url: str, exc: ValueError) -> NoReturn: +def _manifest_invalid(plat: str, url: str, exc: ValueError, overridden: bool) -> NoReturn: """Stop on a file list that arrived and is not valid.""" words = f"the file list is not valid: {exc}" if isinstance(exc.__cause__, (json.JSONDecodeError, UnicodeDecodeError)): @@ -7740,7 +7788,7 @@ def _manifest_invalid(plat: str, url: str, exc: ValueError) -> NoReturn: message=words) print(f" For {display_name(plat)}, {words}.", file=sys.stderr) if words.startswith("what arrived"): - for line in _address_lines(url): + for line in _address_lines(url, overridden): print(line, file=sys.stderr) print(" Check the connection (sign in to the Wi-Fi if it asks), then run the " "same command again.", file=sys.stderr) @@ -7750,38 +7798,40 @@ def _manifest_invalid(plat: str, url: str, exc: ValueError) -> NoReturn: def missing_list_advice(plat: str, again: str) -> str: """What to do when the revision asked for has no file list for plat: the name was checked before any request, so the revision is the cause.""" - if RELEASE_REF != DEFAULT_RELEASE_REF: - return (f"RETROBIOS_REF={RELEASE_REF} has no list for {plat}: unset it, or pick a " + ref = active_remote().ref + if ref != DEFAULT_RELEASE_REF: + return (f"RETROBIOS_REF={ref} has no list for {plat}: unset it, or pick a " "newer tag from https://github.com/Abdess/retrobios/releases.") return f"The repository may be moving its files: {again} in a few minutes." -def _manifest_http_error(plat: str, url: str, exc: urllib.error.HTTPError) -> NoReturn: +def _manifest_http_error(plat: str, url: str, exc: urllib.error.HTTPError, + overridden: bool) -> NoReturn: """Stop on a file list the server answered with an HTTP error.""" EVENTS.emit( "error", stage="manifest", reason="not_found" if exc.code == 404 else "network", platform=plat, message=f"the file list could not be fetched: HTTP {exc.code}", ) - if exc.code == 404 and os.environ.get("RETROBIOS_BASE_URL"): + if exc.code == 404 and overridden: print(f" No file list for {plat} there.", file=sys.stderr) - for line in _address_lines(url): + for line in _address_lines(url, overridden): print(line, file=sys.stderr) sys.exit(1) if exc.code == 404: # Asked once, a 4xx being final. The name was checked before any # request, so the revision is what has no such list. - print(f" No file list for {plat} at {RELEASE_REF}.", file=sys.stderr) + print(f" No file list for {plat} at {active_remote().ref}.", file=sys.stderr) print(f" {missing_list_advice(plat, 'run the same command again')}", file=sys.stderr) sys.exit(1) print(f" Could not fetch the file list for {plat}: HTTP {exc.code}", file=sys.stderr) - for line in _address_lines(url): + for line in _address_lines(url, overridden): print(line, file=sys.stderr) print(NETWORK_ADVICE, file=sys.stderr) sys.exit(1) -def _manifest_unreachable(plat: str, url: str, exc: OSError) -> NoReturn: +def _manifest_unreachable(plat: str, url: str, exc: OSError, overridden: bool) -> NoReturn: """Stop on a file list the network did not bring.""" code, words = network_words(exc) EVENTS.emit("error", stage="manifest", reason=code, platform=plat, @@ -7799,7 +7849,7 @@ def _manifest_unreachable(plat: str, url: str, exc: OSError) -> NoReturn: tries = getattr(exc, "attempts", MAX_RETRIES) print(f" Could not fetch the file list for {plat} after {tries} " f"attempts: {words}", file=sys.stderr) - for line in _address_lines(url): + for line in _address_lines(url, overridden): print(line, file=sys.stderr) print(NETWORK_ADVICE, file=sys.stderr) sys.exit(1) @@ -7816,15 +7866,16 @@ def fetch_manifest(plat: str) -> dict: print(f" The file list in {LOCAL.pack.name} is not valid: {exc}", file=sys.stderr) sys.exit(1) - url = MANIFEST_URL.format(platform=plat) + remote = active_remote() + url = remote.manifest_url.format(platform=plat) try: return _validate_manifest(_fetch_json(url, MAX_MANIFEST_BYTES, "file list"), plat) except ValueError as exc: - _manifest_invalid(plat, url, exc) + _manifest_invalid(plat, url, exc, remote.overridden) except urllib.error.HTTPError as exc: - _manifest_http_error(plat, url, exc) + _manifest_http_error(plat, url, exc, remote.overridden) except (urllib.error.URLError, OSError) as exc: - _manifest_unreachable(plat, url, exc) + _manifest_unreachable(plat, url, exc, remote.overridden) def _pack_alone(plat: str) -> bool: @@ -7865,7 +7916,7 @@ def fetch_standalone(plat: str, manifest: dict) -> dict: invalid, the run stops on one line, code 1.""" beside = (LOCAL.manifest.parent / STANDALONE_DIR / f"{plat}.json" if LOCAL.manifest is not None else None) - url = STANDALONE_URL.format(platform=plat) + url = active_remote().standalone_url.format(platform=plat) where = str(beside) if beside is not None and _is_file(beside) else url try: if where != url: @@ -7910,7 +7961,8 @@ def fetch_targets(plat: str, attempts: int = MAX_RETRIES, f"install/targets/{plat}.json beside the --manifest file, or go online.", file=sys.stderr) sys.exit(2) - url = TARGETS_URL.format(platform=plat) + remote = active_remote() + url = remote.targets_url.format(platform=plat) try: return _validate_targets(_fetch_json(url, MAX_TARGETS_BYTES, "target list", attempts=attempts, timeout=timeout)) @@ -7918,7 +7970,7 @@ def fetch_targets(plat: str, attempts: int = MAX_RETRIES, if exc.code == 404: return {} print(f" Error: failed to fetch targets for {plat}: {exc}", file=sys.stderr) - for line in _address_lines(url): + for line in _address_lines(url, remote.overridden): print(line, file=sys.stderr) print(NETWORK_ADVICE, file=sys.stderr) return None @@ -7928,7 +7980,7 @@ def fetch_targets(plat: str, attempts: int = MAX_RETRIES, except (urllib.error.URLError, OSError) as exc: print(f" Error: failed to fetch targets for {plat}: " f"{network_words(exc)[1]}", file=sys.stderr) - for line in _address_lines(url): + for line in _address_lines(url, remote.overridden): print(line, file=sys.stderr) print(NETWORK_ADVICE, file=sys.stderr) return None @@ -9618,7 +9670,7 @@ def build_parser() -> argparse.ArgumentParser: parser.add_argument( "--version", action="version", - version=f"retrobios installer {installer_id()} (ref {RELEASE_REF})", + version=f"retrobios installer {installer_id()} (ref {active_remote().ref})", help="print the installer version and exit", ) parser.add_argument( @@ -10600,8 +10652,9 @@ def _older_list_advice(plat: str = "") -> str: if _pack_alone(plat) and LOCAL.pack is not None: return (f" The list in {LOCAL.pack.name} does not record it: add --manifest FILE, " f"a copy of install/{plat or ''}.json, or run without the option.") - if RELEASE_REF != DEFAULT_RELEASE_REF: - return (f" RETROBIOS_REF={RELEASE_REF} selects file lists published before " + ref = active_remote().ref + if ref != DEFAULT_RELEASE_REF: + return (f" RETROBIOS_REF={ref} selects file lists published before " "this option existed: unset RETROBIOS_REF to use the current ones, " "or run without the option.") return (" The file list comes from an older release: run the one-line " @@ -15765,8 +15818,8 @@ def _http_failure_lines(failures: list[tuple[str, str]]) -> list[str]: return [] more = f" (and {_plural(len(refused) - 1, 'other file')})" if len(refused) > 1 else "" lines = [f" The server answered {refused[0]} for {refused[0].url}{more}."] - if os.environ.get("RETROBIOS_BASE_URL"): - return lines + _address_lines(refused[0].url)[1:] + if active_remote().overridden: + return [*lines, OVERRIDE_LINE] return lines + [" The file list names files the server does not hold, and running " "again changes nothing until the two match.", f" More help: {TROUBLESHOOTING_PAGE}"] @@ -15872,9 +15925,9 @@ def _failure_advice( advice += _http_failure_lines(failures) if any(isinstance(reason, NetworkReason) for _dest, reason in failures): advice.append(NETWORK_FAILURE_ADVICE) - if os.environ.get("RETROBIOS_BASE_URL"): + if active_remote().overridden: # A mirror that is down read as this machine's connection. - advice += _address_lines(BASE_URL)[1:] + advice.append(OVERRIDE_LINE) if any(str(reason).startswith(NOT_KEPT) for _dest, reason in failures): # The same run fails the same way: "retry only those" sent a phone # user round the loop with nothing changed. @@ -16345,7 +16398,7 @@ def _download_one( if f.get("release_asset"): url = RELEASE_URL.format(asset=urllib.parse.quote(f["release_asset"], safe="")) else: - url = RAW_FILE_URL.format(path=urllib.parse.quote(f["repo_path"], safe="/")) + url = active_remote().raw_file_url.format(path=urllib.parse.quote(f["repo_path"], safe="/")) return _fetch_file(_FileFetch(f, bios_path, dest, url, verbose, progress)) @@ -17326,7 +17379,11 @@ def select_data_directories(manifest: dict, files: list[dict], narrowed: bool, # same ref as the file lists, listed with their hashes in # install/launchers/index.json, which scripts/generate_launcher_index.py # writes from the members of the launcher archives. -LAUNCHERS_URL = f"{BASE_URL}/install/launchers/index.json" +def launchers_url() -> str: + """Where install/launchers/index.json is read from in this run.""" + return f"{active_remote().base}/install/launchers/index.json" + + MAX_LAUNCHERS_BYTES = 256 * 1024 MAX_APP_FILE_SIZE = 8 * 1024 * 1024 MAX_APP_FILES = 64 @@ -17516,7 +17573,7 @@ def _app_bytes(entry: dict, name: str) -> bytes: if content is not None: data = content.encode("utf-8") else: - url = RAW_FILE_URL.format(path=urllib.parse.quote(entry["repo_path"], safe="/")) + url = active_remote().raw_file_url.format(path=urllib.parse.quote(entry["repo_path"], safe="/")) data = _app_download(url, entry["size"]) if len(data) != entry["size"]: raise ValueError(f"{name} holds {len(data)} bytes, the list records {entry['size']}") @@ -17569,7 +17626,7 @@ def put_app(card: CardApp) -> dict: if card.place is None: return fields try: - data = _fetch_json(LAUNCHERS_URL, MAX_LAUNCHERS_BYTES, "list of the app's files") + data = _fetch_json(launchers_url(), MAX_LAUNCHERS_BYTES, "list of the app's files") targets = app_targets(data, card.place) except (urllib.error.URLError, OSError, ValueError, http.client.HTTPException) as exc: fields["reason"] = f"its list of files could not be read: {_app_failure(exc)}" @@ -17709,8 +17766,14 @@ def finish_app( # and for an arcade set the BIOS sets its romof chain reaches. Any doubt # keeps the wider set: the game must run. -GAMES_URL = f"{BASE_URL}/install/games/{{path}}" GAMES_FORMAT = 1 + + +def games_url(path: str) -> str: + """Where install/games/ is read from in this run.""" + return f"{active_remote().base}/install/games/{path}" + + MAX_GAMES_INDEX_BYTES = 4 * 1024 * 1024 MAX_GAMES_DOC_BYTES = 32 * 1024 * 1024 @@ -17771,7 +17834,7 @@ class GamesData: failure = "" if raw is None and network: try: - raw = _fetch_json(GAMES_URL.format(path="index.json"), MAX_GAMES_INDEX_BYTES, + raw = _fetch_json(games_url("index.json"), MAX_GAMES_INDEX_BYTES, "games index", attempts=attempts, raw=True) except _Offline: reason = "offline" @@ -17817,7 +17880,7 @@ class GamesData: cached: Path | None) -> bytes | None: """A listed document downloaded and cached, None when offline.""" try: - fetched = _fetch_json(GAMES_URL.format(path=name), limit, f"games {kind}", + fetched = _fetch_json(games_url(name), limit, f"games {kind}", attempts=attempts, raw=True) except _Offline: return None @@ -21003,7 +21066,7 @@ def _other_setup_list(name: str) -> tuple[dict | None, str]: if offline_requested(): return None, "this run is offline: run it again with the internet" try: - return _validate_manifest(_fetch_json(MANIFEST_URL.format(platform=name), + return _validate_manifest(_fetch_json(active_remote().manifest_url.format(platform=name), MAX_MANIFEST_BYTES, "file list"), name), "" except urllib.error.HTTPError as exc: if exc.code == 404: @@ -25429,7 +25492,8 @@ def _tui_fetch(plat: str, inbox: queue.Queue, log: io.StringIO) -> None: inbox.put(("manifest_failed", plat, "", log.getvalue()[mark:].splitlines(), _event_exit_code(exc.code))) return - url = MANIFEST_URL.format(platform=plat) + remote = active_remote() + url = remote.manifest_url.format(platform=plat) try: data = _fetch_json(url, MAX_MANIFEST_BYTES, "file list", attempts=1, timeout=TUI_FETCH_TIMEOUT) @@ -25445,7 +25509,7 @@ def _tui_fetch(plat: str, inbox: queue.Queue, log: io.StringIO) -> None: title = "No file list" lines = [f"There is no file list for {display_name(plat)} at this address." if exc.code == 404 else f"The server answered HTTP {exc.code}."] - if exc.code == 404 and not os.environ.get("RETROBIOS_BASE_URL"): + if exc.code == 404 and not remote.overridden: # Line mode named RETROBIOS_REF as the cause, the screen nothing. lines.append(missing_list_advice(plat, "choose Try again")) except (urllib.error.URLError, OSError) as exc: @@ -25478,7 +25542,7 @@ def _tui_fetch(plat: str, inbox: queue.Queue, log: io.StringIO) -> None: # Named, never shown: the value can hold a password. lines.append(f"{proxy} is set, so the connection goes through a proxy: " "check that it answers.") - if os.environ.get("RETROBIOS_BASE_URL"): + if remote.overridden: lines.append(f"RETROBIOS_BASE_URL chose the address: {url}") inbox.put(("manifest_failed", plat, title, lines, 1)) @@ -31769,7 +31833,17 @@ def _main_dispatch(args: argparse.Namespace) -> None: def main() -> None: - """Entry point.""" + """Entry point: the remote resolved once, then the run.""" + try: + remote = remote_from_env() + except ValueError as exc: + print(f"Error: {exc}", file=sys.stderr) + sys.exit(1) + with remote_in_use(remote): + _main_run() + + +def _main_run() -> None: _INVOCATION.os_type = detect_os() parser = build_parser() args = parser.parse_args() diff --git a/install.sh b/install.sh index 337b4b83f..4a1e4c1ad 100755 --- a/install.sh +++ b/install.sh @@ -23,7 +23,7 @@ DEFAULT_INSTALL_URL="https://raw.githubusercontent.com/Abdess/retrobios/main/ins # curl or wget stop on a cut transfer before the hash is read: the site's # build rewrites this line there (scripts/sitebootstrap.py). MISMATCH_ADVICE="The download was most likely cut short: try again. Within minutes of an update of this project the two files can come from caches of different ages. Waiting five minutes settles that." -DEFAULT_INSTALL_SHA256="9912b09dd3b6510a2ce00df042f234c74f23052e4ec0d100e2c3b48c34b502cb" +DEFAULT_INSTALL_SHA256="581acaf87f2414ef9e1bfecb068ed8df6402f6f29b602ac5c3d3682f73710811" # The pin above refuses any changed byte: this cap only stops a body that # cannot be the installer (a sign-in portal's page) before it is hashed. MAX_INSTALLER_BYTES=8388608 diff --git a/install/launchers/index.json b/install/launchers/index.json index 5a84595f0..f5d424b29 100644 --- a/install/launchers/index.json +++ b/install/launchers/index.json @@ -27,8 +27,8 @@ { "dest": "roms/ports/retrobios/install.py", "repo_path": "install.py", - "size": 1449987, - "sha256": "9912b09dd3b6510a2ce00df042f234c74f23052e4ec0d100e2c3b48c34b502cb", + "size": 1451043, + "sha256": "581acaf87f2414ef9e1bfecb068ed8df6402f6f29b602ac5c3d3682f73710811", "executable": false }, { @@ -71,8 +71,8 @@ "muos": { "archive": { "dest": "ARCHIVE/RetroBIOS.muxapp", - "size": 1503612, - "sha256": "4247f8fe1a0aee1d958ce838701795d176fb4725a32e12a6ce601af4f9a39030" + "size": 1504668, + "sha256": "1f0887f59f9ef77fa2b99a30a95ef1819a79a35006b9de7becee7f99438f5d1c" }, "members": [ { @@ -92,8 +92,8 @@ { "name": "RetroBIOS/install.py", "repo_path": "install.py", - "size": 1449987, - "sha256": "9912b09dd3b6510a2ce00df042f234c74f23052e4ec0d100e2c3b48c34b502cb", + "size": 1451043, + "sha256": "581acaf87f2414ef9e1bfecb068ed8df6402f6f29b602ac5c3d3682f73710811", "executable": false }, { @@ -166,8 +166,8 @@ { "dest": ".config/modules/retrobios/install.py", "repo_path": "install.py", - "size": 1449987, - "sha256": "9912b09dd3b6510a2ce00df042f234c74f23052e4ec0d100e2c3b48c34b502cb", + "size": 1451043, + "sha256": "581acaf87f2414ef9e1bfecb068ed8df6402f6f29b602ac5c3d3682f73710811", "executable": false }, { diff --git a/installer/arguments.py b/installer/arguments.py index ee98f6231..a2b97228f 100644 --- a/installer/arguments.py +++ b/installer/arguments.py @@ -6,7 +6,7 @@ import re from pathlib import Path from installer.invocation import OFFLINE_VARIABLE, _INVOCATION, installer_id -from installer.remote import INSTALLER_PAGE, RELEASE_REF +from installer.remote import INSTALLER_PAGE, active_remote from installer.safe_replace import BACKUP_DIR from installer.text import format_size @@ -373,7 +373,7 @@ def build_parser() -> argparse.ArgumentParser: parser.add_argument( "--version", action="version", - version=f"retrobios installer {installer_id()} (ref {RELEASE_REF})", + version=f"retrobios installer {installer_id()} (ref {active_remote().ref})", help="print the installer version and exit", ) parser.add_argument( diff --git a/installer/choices.py b/installer/choices.py index 8f3e63ad7..d614dbf39 100644 --- a/installer/choices.py +++ b/installer/choices.py @@ -23,7 +23,7 @@ from installer.platforms import ( refuse_name, ) from installer.regions import WORLD_REGION, resolve_regions -from installer.remote import DEFAULT_RELEASE_REF, RELEASE_REF +from installer.remote import DEFAULT_RELEASE_REF, active_remote from installer.text import _plural if TYPE_CHECKING: @@ -280,8 +280,9 @@ def _older_list_advice(plat: str = "") -> str: if _pack_alone(plat) and LOCAL.pack is not None: return (f" The list in {LOCAL.pack.name} does not record it: add --manifest FILE, " f"a copy of install/{plat or ''}.json, or run without the option.") - if RELEASE_REF != DEFAULT_RELEASE_REF: - return (f" RETROBIOS_REF={RELEASE_REF} selects file lists published before " + ref = active_remote().ref + if ref != DEFAULT_RELEASE_REF: + return (f" RETROBIOS_REF={ref} selects file lists published before " "this option existed: unset RETROBIOS_REF to use the current ones, " "or run without the option.") return (" The file list comes from an older release: run the one-line " diff --git a/installer/cli.py b/installer/cli.py index cce15c7e1..180564758 100644 --- a/installer/cli.py +++ b/installer/cli.py @@ -31,6 +31,7 @@ from installer.network import _RAW_ERRORS, install_bounded_opener from installer.offline import LOCAL, OFFLINE_FLAG_VALUE, offline_named from installer.platforms import AVAILABLE_PLATFORMS, TARGET_PLATFORMS, _name_key, display_name, refuse_name from installer.regions import resolve_regions +from installer.remote import remote_from_env, remote_in_use from installer.removal import run_backups, run_delete_backup, run_removal from installer.run import _install from installer.tui_routes import TUI_LIST_ENV, TUI_RECORD_ENV, line_mode_reason, plain_requested, tui_blocker @@ -303,7 +304,17 @@ def _main_dispatch(args: argparse.Namespace) -> None: def main() -> None: - """Entry point.""" + """Entry point: the remote resolved once, then the run.""" + try: + remote = remote_from_env() + except ValueError as exc: + print(f"Error: {exc}", file=sys.stderr) + sys.exit(1) + with remote_in_use(remote): + _main_run() + + +def _main_run() -> None: _INVOCATION.os_type = detect_os() parser = build_parser() args = parser.parse_args() diff --git a/installer/download.py b/installer/download.py index 2195fbfed..b0080aece 100644 --- a/installer/download.py +++ b/installer/download.py @@ -41,7 +41,7 @@ from installer.offline import LOCAL, offline_words from installer.outcome import HttpReason, NetworkReason, OfflineReason, _transfer_failure from installer.pack_source import NOT_IN_PACK, _extract_from_pack from installer.paths import _entry_path, _entry_place -from installer.remote import MAX_DOWNLOAD_SIZE, MAX_RETRIES, RAW_FILE_URL, RELEASE_URL, RESUME_FROM_SIZE +from installer.remote import MAX_DOWNLOAD_SIZE, MAX_RETRIES, RELEASE_URL, RESUME_FROM_SIZE, active_remote from installer.safe_replace import KEPT, NOT_KEPT, _NotKept, _kept_slot from installer.terminal import Terminal @@ -134,7 +134,7 @@ def _download_one( if f.get("release_asset"): url = RELEASE_URL.format(asset=urllib.parse.quote(f["release_asset"], safe="")) else: - url = RAW_FILE_URL.format(path=urllib.parse.quote(f["repo_path"], safe="/")) + url = active_remote().raw_file_url.format(path=urllib.parse.quote(f["repo_path"], safe="/")) return _fetch_file(_FileFetch(f, bios_path, dest, url, verbose, progress)) diff --git a/installer/games.py b/installer/games.py index 3e16b209b..47bc02a7f 100644 --- a/installer/games.py +++ b/installer/games.py @@ -42,7 +42,7 @@ from installer.offline import LOCAL, _Offline, offline_words from installer.paths import shown_path from installer.platforms import entry_systems, system_title from installer.regions import WORLD_REGION, _region_comparable, region_title -from installer.remote import BASE_URL +from installer.remote import active_remote from installer.text import _plural, agree if TYPE_CHECKING: @@ -57,8 +57,14 @@ if TYPE_CHECKING: # and for an arcade set the BIOS sets its romof chain reaches. Any doubt # keeps the wider set: the game must run. -GAMES_URL = f"{BASE_URL}/install/games/{{path}}" GAMES_FORMAT = 1 + + +def games_url(path: str) -> str: + """Where install/games/ is read from in this run.""" + return f"{active_remote().base}/install/games/{path}" + + MAX_GAMES_INDEX_BYTES = 4 * 1024 * 1024 MAX_GAMES_DOC_BYTES = 32 * 1024 * 1024 @@ -119,7 +125,7 @@ class GamesData: failure = "" if raw is None and network: try: - raw = _fetch_json(GAMES_URL.format(path="index.json"), MAX_GAMES_INDEX_BYTES, + raw = _fetch_json(games_url("index.json"), MAX_GAMES_INDEX_BYTES, "games index", attempts=attempts, raw=True) except _Offline: reason = "offline" @@ -165,7 +171,7 @@ class GamesData: cached: Path | None) -> bytes | None: """A listed document downloaded and cached, None when offline.""" try: - fetched = _fetch_json(GAMES_URL.format(path=name), limit, f"games {kind}", + fetched = _fetch_json(games_url(name), limit, f"games {kind}", attempts=attempts, raw=True) except _Offline: return None diff --git a/installer/handheld_app.py b/installer/handheld_app.py index 4a5bb2bcd..757e234f8 100644 --- a/installer/handheld_app.py +++ b/installer/handheld_app.py @@ -26,7 +26,7 @@ from installer.network import _fetch_json, _read_limited, _retry_after_failure, from installer.offline import LOCAL, _Offline, _network_allowed from installer.outcome import _transfer_failure from installer.paths import _destination_path, _safe_relative_path -from installer.remote import BASE_URL, MAX_RETRIES, RAW_FILE_URL +from installer.remote import MAX_RETRIES, active_remote from installer.safe_replace import KEPT, _write_verified from installer.text import _plural @@ -36,7 +36,11 @@ from installer.text import _plural # same ref as the file lists, listed with their hashes in # install/launchers/index.json, which scripts/generate_launcher_index.py # writes from the members of the launcher archives. -LAUNCHERS_URL = f"{BASE_URL}/install/launchers/index.json" +def launchers_url() -> str: + """Where install/launchers/index.json is read from in this run.""" + return f"{active_remote().base}/install/launchers/index.json" + + MAX_LAUNCHERS_BYTES = 256 * 1024 MAX_APP_FILE_SIZE = 8 * 1024 * 1024 MAX_APP_FILES = 64 @@ -226,7 +230,7 @@ def _app_bytes(entry: dict, name: str) -> bytes: if content is not None: data = content.encode("utf-8") else: - url = RAW_FILE_URL.format(path=urllib.parse.quote(entry["repo_path"], safe="/")) + url = active_remote().raw_file_url.format(path=urllib.parse.quote(entry["repo_path"], safe="/")) data = _app_download(url, entry["size"]) if len(data) != entry["size"]: raise ValueError(f"{name} holds {len(data)} bytes, the list records {entry['size']}") @@ -279,7 +283,7 @@ def put_app(card: CardApp) -> dict: if card.place is None: return fields try: - data = _fetch_json(LAUNCHERS_URL, MAX_LAUNCHERS_BYTES, "list of the app's files") + data = _fetch_json(launchers_url(), MAX_LAUNCHERS_BYTES, "list of the app's files") targets = app_targets(data, card.place) except (urllib.error.URLError, OSError, ValueError, http.client.HTTPException) as exc: fields["reason"] = f"its list of files could not be read: {_app_failure(exc)}" diff --git a/installer/network.py b/installer/network.py index b8253bba9..3ac603fb3 100644 --- a/installer/network.py +++ b/installer/network.py @@ -23,16 +23,13 @@ from installer.platforms import TARGET_PLATFORMS, display_name from installer.remote import ( CONNECT_TIMEOUT, DEFAULT_RELEASE_REF, - MANIFEST_URL, MAX_MANIFEST_BYTES, MAX_RETRIES, MAX_STANDALONE_BYTES, MAX_TARGETS_BYTES, - RELEASE_REF, STANDALONE_DIR, - STANDALONE_URL, - TARGETS_URL, TROUBLESHOOTING_PAGE, + active_remote, ) @@ -203,17 +200,17 @@ def network_words( return code, words -def _address_lines(url: str) -> list[str]: +OVERRIDE_LINE = (" RETROBIOS_BASE_URL is set in this environment and chose that " + "address: unset it to read from the project itself.") + + +def _address_lines(url: str, overridden: bool) -> list[str]: """The address that failed, and the override that chose it if one did. A RETROBIOS_BASE_URL left from a mirror that is down read as a network fault: neither the host nor the variable was named. """ - lines = [f" Address: {url}"] - if os.environ.get("RETROBIOS_BASE_URL"): - lines.append(" RETROBIOS_BASE_URL is set in this environment and chose that " - "address: unset it to read from the project itself.") - return lines + return [f" Address: {url}", *([OVERRIDE_LINE] if overridden else [])] def _open_socket( @@ -324,7 +321,7 @@ def _fetch_json( raise AssertionError("unreachable") -def _manifest_invalid(plat: str, url: str, exc: ValueError) -> NoReturn: +def _manifest_invalid(plat: str, url: str, exc: ValueError, overridden: bool) -> NoReturn: """Stop on a file list that arrived and is not valid.""" words = f"the file list is not valid: {exc}" if isinstance(exc.__cause__, (json.JSONDecodeError, UnicodeDecodeError)): @@ -336,7 +333,7 @@ def _manifest_invalid(plat: str, url: str, exc: ValueError) -> NoReturn: message=words) print(f" For {display_name(plat)}, {words}.", file=sys.stderr) if words.startswith("what arrived"): - for line in _address_lines(url): + for line in _address_lines(url, overridden): print(line, file=sys.stderr) print(" Check the connection (sign in to the Wi-Fi if it asks), then run the " "same command again.", file=sys.stderr) @@ -346,38 +343,40 @@ def _manifest_invalid(plat: str, url: str, exc: ValueError) -> NoReturn: def missing_list_advice(plat: str, again: str) -> str: """What to do when the revision asked for has no file list for plat: the name was checked before any request, so the revision is the cause.""" - if RELEASE_REF != DEFAULT_RELEASE_REF: - return (f"RETROBIOS_REF={RELEASE_REF} has no list for {plat}: unset it, or pick a " + ref = active_remote().ref + if ref != DEFAULT_RELEASE_REF: + return (f"RETROBIOS_REF={ref} has no list for {plat}: unset it, or pick a " "newer tag from https://github.com/Abdess/retrobios/releases.") return f"The repository may be moving its files: {again} in a few minutes." -def _manifest_http_error(plat: str, url: str, exc: urllib.error.HTTPError) -> NoReturn: +def _manifest_http_error(plat: str, url: str, exc: urllib.error.HTTPError, + overridden: bool) -> NoReturn: """Stop on a file list the server answered with an HTTP error.""" EVENTS.emit( "error", stage="manifest", reason="not_found" if exc.code == 404 else "network", platform=plat, message=f"the file list could not be fetched: HTTP {exc.code}", ) - if exc.code == 404 and os.environ.get("RETROBIOS_BASE_URL"): + if exc.code == 404 and overridden: print(f" No file list for {plat} there.", file=sys.stderr) - for line in _address_lines(url): + for line in _address_lines(url, overridden): print(line, file=sys.stderr) sys.exit(1) if exc.code == 404: # Asked once, a 4xx being final. The name was checked before any # request, so the revision is what has no such list. - print(f" No file list for {plat} at {RELEASE_REF}.", file=sys.stderr) + print(f" No file list for {plat} at {active_remote().ref}.", file=sys.stderr) print(f" {missing_list_advice(plat, 'run the same command again')}", file=sys.stderr) sys.exit(1) print(f" Could not fetch the file list for {plat}: HTTP {exc.code}", file=sys.stderr) - for line in _address_lines(url): + for line in _address_lines(url, overridden): print(line, file=sys.stderr) print(NETWORK_ADVICE, file=sys.stderr) sys.exit(1) -def _manifest_unreachable(plat: str, url: str, exc: OSError) -> NoReturn: +def _manifest_unreachable(plat: str, url: str, exc: OSError, overridden: bool) -> NoReturn: """Stop on a file list the network did not bring.""" code, words = network_words(exc) EVENTS.emit("error", stage="manifest", reason=code, platform=plat, @@ -395,7 +394,7 @@ def _manifest_unreachable(plat: str, url: str, exc: OSError) -> NoReturn: tries = getattr(exc, "attempts", MAX_RETRIES) print(f" Could not fetch the file list for {plat} after {tries} " f"attempts: {words}", file=sys.stderr) - for line in _address_lines(url): + for line in _address_lines(url, overridden): print(line, file=sys.stderr) print(NETWORK_ADVICE, file=sys.stderr) sys.exit(1) @@ -412,15 +411,16 @@ def fetch_manifest(plat: str) -> dict: print(f" The file list in {LOCAL.pack.name} is not valid: {exc}", file=sys.stderr) sys.exit(1) - url = MANIFEST_URL.format(platform=plat) + remote = active_remote() + url = remote.manifest_url.format(platform=plat) try: return _validate_manifest(_fetch_json(url, MAX_MANIFEST_BYTES, "file list"), plat) except ValueError as exc: - _manifest_invalid(plat, url, exc) + _manifest_invalid(plat, url, exc, remote.overridden) except urllib.error.HTTPError as exc: - _manifest_http_error(plat, url, exc) + _manifest_http_error(plat, url, exc, remote.overridden) except (urllib.error.URLError, OSError) as exc: - _manifest_unreachable(plat, url, exc) + _manifest_unreachable(plat, url, exc, remote.overridden) def _pack_alone(plat: str) -> bool: @@ -461,7 +461,7 @@ def fetch_standalone(plat: str, manifest: dict) -> dict: invalid, the run stops on one line, code 1.""" beside = (LOCAL.manifest.parent / STANDALONE_DIR / f"{plat}.json" if LOCAL.manifest is not None else None) - url = STANDALONE_URL.format(platform=plat) + url = active_remote().standalone_url.format(platform=plat) where = str(beside) if beside is not None and _is_file(beside) else url try: if where != url: @@ -506,7 +506,8 @@ def fetch_targets(plat: str, attempts: int = MAX_RETRIES, f"install/targets/{plat}.json beside the --manifest file, or go online.", file=sys.stderr) sys.exit(2) - url = TARGETS_URL.format(platform=plat) + remote = active_remote() + url = remote.targets_url.format(platform=plat) try: return _validate_targets(_fetch_json(url, MAX_TARGETS_BYTES, "target list", attempts=attempts, timeout=timeout)) @@ -514,7 +515,7 @@ def fetch_targets(plat: str, attempts: int = MAX_RETRIES, if exc.code == 404: return {} print(f" Error: failed to fetch targets for {plat}: {exc}", file=sys.stderr) - for line in _address_lines(url): + for line in _address_lines(url, remote.overridden): print(line, file=sys.stderr) print(NETWORK_ADVICE, file=sys.stderr) return None @@ -524,7 +525,7 @@ def fetch_targets(plat: str, attempts: int = MAX_RETRIES, except (urllib.error.URLError, OSError) as exc: print(f" Error: failed to fetch targets for {plat}: " f"{network_words(exc)[1]}", file=sys.stderr) - for line in _address_lines(url): + for line in _address_lines(url, remote.overridden): print(line, file=sys.stderr) print(NETWORK_ADVICE, file=sys.stderr) return None diff --git a/installer/outcome.py b/installer/outcome.py index 355a1c7e3..e5a413717 100644 --- a/installer/outcome.py +++ b/installer/outcome.py @@ -17,12 +17,12 @@ from installer.destination import on_its_card from installer.detect_os import detected_os from installer.host_fs import DRIVE_FULL, NOT_WRITABLE, READ_ONLY, _held from installer.invocation import _INVOCATION -from installer.network import _address_lines +from installer.network import OVERRIDE_LINE from installer.offline import LOCAL, OFFLINE_WORDS, _offline_only, offline_named, offline_undo from installer.pack_source import NOT_IN_PACK from installer.paths import shown_path from installer.platforms import display_name -from installer.remote import BASE_URL, TROUBLESHOOTING_PAGE +from installer.remote import TROUBLESHOOTING_PAGE, active_remote from installer.romm import ROMM_SCAN_WORDS from installer.safe_replace import BACKUP_DIR, KEPT, NOT_KEPT, _kept_lines from installer.tally import _omission_lines, installed_words, needed_absent_words @@ -172,8 +172,8 @@ def _http_failure_lines(failures: list[tuple[str, str]]) -> list[str]: return [] more = f" (and {_plural(len(refused) - 1, 'other file')})" if len(refused) > 1 else "" lines = [f" The server answered {refused[0]} for {refused[0].url}{more}."] - if os.environ.get("RETROBIOS_BASE_URL"): - return lines + _address_lines(refused[0].url)[1:] + if active_remote().overridden: + return [*lines, OVERRIDE_LINE] return lines + [" The file list names files the server does not hold, and running " "again changes nothing until the two match.", f" More help: {TROUBLESHOOTING_PAGE}"] @@ -279,9 +279,9 @@ def _failure_advice( advice += _http_failure_lines(failures) if any(isinstance(reason, NetworkReason) for _dest, reason in failures): advice.append(NETWORK_FAILURE_ADVICE) - if os.environ.get("RETROBIOS_BASE_URL"): + if active_remote().overridden: # A mirror that is down read as this machine's connection. - advice += _address_lines(BASE_URL)[1:] + advice.append(OVERRIDE_LINE) if any(str(reason).startswith(NOT_KEPT) for _dest, reason in failures): # The same run fails the same way: "retry only those" sent a phone # user round the loop with nothing changed. diff --git a/installer/remote.py b/installer/remote.py index 3b38c08a0..5a454a957 100644 --- a/installer/remote.py +++ b/installer/remote.py @@ -1,26 +1,29 @@ """Where file lists and files come from, the pages the installer names, and bounds on what it reads.""" from __future__ import annotations +import contextlib import os -import sys import urllib.parse +from collections.abc import Iterator +from typing import NamedTuple # File lists are read from main, the newest ones, whichever commit the # installer came from. RETROBIOS_REF pins them to a tag or a commit when # reproducibility matters. DEFAULT_RELEASE_REF = "main" -RELEASE_REF = os.environ.get("RETROBIOS_REF", DEFAULT_RELEASE_REF) -DEFAULT_BASE_URL = ( - "https://raw.githubusercontent.com/Abdess/retrobios/" - + urllib.parse.quote(RELEASE_REF, safe="") -) + + +def default_base_url(ref: str) -> str: + """The project's own address for the file lists of ref.""" + return ("https://raw.githubusercontent.com/Abdess/retrobios/" + + urllib.parse.quote(ref, safe="")) _LOOPBACK_HOSTS = ("localhost", "127.0.0.1", "::1") def _checked_base_url(value: str) -> str: - """Refuse a base URL that is neither HTTPS nor loopback. + """Refuse a base URL that is neither HTTPS nor loopback, as ValueError. This base serves the manifest and the files it declares, so whoever controls it controls the expected hashes too and verification stops @@ -36,22 +39,69 @@ def _checked_base_url(value: str) -> str: host = (parsed.hostname or "").lower() if parsed.scheme == "http" and host in _LOOPBACK_HOSTS: return value - print( - f"Error: RETROBIOS_BASE_URL must use HTTPS, got {value!r}", - file=sys.stderr, - ) - sys.exit(1) + raise ValueError(f"RETROBIOS_BASE_URL must use HTTPS, got {value!r}") -BASE_URL = _checked_base_url(os.environ.get("RETROBIOS_BASE_URL", DEFAULT_BASE_URL)) -MANIFEST_URL = f"{BASE_URL}/install/{{platform}}.json" -TARGETS_URL = f"{BASE_URL}/install/targets/{{platform}}.json" # What --standalone reads, apart from the list every run downloads. STANDALONE_DIR = "standalone" -STANDALONE_URL = f"{BASE_URL}/install/standalone/{{platform}}.json" -RAW_FILE_URL = f"{BASE_URL}/{{path}}" +class Remote(NamedTuple): + """Where a run reads its lists and files: the revision, the base + address, and whether RETROBIOS_BASE_URL chose that base.""" + + ref: str + base: str + overridden: bool + + @property + def manifest_url(self) -> str: + return f"{self.base}/install/{{platform}}.json" + + @property + def targets_url(self) -> str: + return f"{self.base}/install/targets/{{platform}}.json" + + @property + def standalone_url(self) -> str: + return f"{self.base}/install/{STANDALONE_DIR}/{{platform}}.json" + + @property + def raw_file_url(self) -> str: + return f"{self.base}/{{path}}" + + +def remote_from_env() -> Remote: + """The remote RETROBIOS_REF and RETROBIOS_BASE_URL name, ValueError for + a base that is neither HTTPS nor loopback. A variable set but empty is + unset, as every other reading of them takes it.""" + ref = os.environ.get("RETROBIOS_REF") or DEFAULT_RELEASE_REF + override = os.environ.get("RETROBIOS_BASE_URL") or "" + if override: + return Remote(ref, _checked_base_url(override), True) + return Remote(ref, default_base_url(ref), False) + + +# The remote main resolved, for the length of its run. +_IN_USE: list[Remote] = [] + + +@contextlib.contextmanager +def remote_in_use(remote: Remote) -> Iterator[None]: + """remote answers active_remote() until the block ends.""" + _IN_USE.append(remote) + try: + yield + finally: + _IN_USE.pop() + + +def active_remote() -> Remote: + """The remote of this run: the one main resolved, else the one the + environment names now, for a caller that did not come through main.""" + return _IN_USE[-1] if _IN_USE else remote_from_env() + + RELEASE_URL = ( "https://github.com/Abdess/retrobios/releases/download/large-files/{asset}" ) diff --git a/installer/removal.py b/installer/removal.py index 462e0bb0f..f5463e000 100644 --- a/installer/removal.py +++ b/installer/removal.py @@ -41,7 +41,7 @@ from installer.narrowing import designated_cores from installer.network import _fetch_json, fetch_manifest from installer.paths import shown_path, spelled from installer.platforms import display_name, entry_systems, normalize_platform, refuse_name, system_title -from installer.remote import MANIFEST_URL, MAX_MANIFEST_BYTES +from installer.remote import MAX_MANIFEST_BYTES, active_remote from installer.safe_replace import ( BACKUP_DIR, KEPT, @@ -514,7 +514,7 @@ def _other_setup_list(name: str) -> tuple[dict | None, str]: if offline_requested(): return None, "this run is offline: run it again with the internet" try: - return _validate_manifest(_fetch_json(MANIFEST_URL.format(platform=name), + return _validate_manifest(_fetch_json(active_remote().manifest_url.format(platform=name), MAX_MANIFEST_BYTES, "file list"), name), "" except urllib.error.HTTPError as exc: if exc.code == 404: diff --git a/installer/tui_engine.py b/installer/tui_engine.py index 7bb334639..25c58853d 100644 --- a/installer/tui_engine.py +++ b/installer/tui_engine.py @@ -22,7 +22,7 @@ from installer.manifest import _validate_manifest from installer.network import _fetch_json, fetch_manifest, fetch_targets, missing_list_advice, network_words from installer.offline import LOCAL, offline_named, offline_undo from installer.platforms import display_name -from installer.remote import MANIFEST_URL, MAX_MANIFEST_BYTES +from installer.remote import MAX_MANIFEST_BYTES, active_remote from installer.tui_rows import TUI_OFFLINE_TITLE if TYPE_CHECKING: @@ -141,7 +141,8 @@ def _tui_fetch(plat: str, inbox: queue.Queue, log: io.StringIO) -> None: inbox.put(("manifest_failed", plat, "", log.getvalue()[mark:].splitlines(), _event_exit_code(exc.code))) return - url = MANIFEST_URL.format(platform=plat) + remote = active_remote() + url = remote.manifest_url.format(platform=plat) try: data = _fetch_json(url, MAX_MANIFEST_BYTES, "file list", attempts=1, timeout=TUI_FETCH_TIMEOUT) @@ -157,7 +158,7 @@ def _tui_fetch(plat: str, inbox: queue.Queue, log: io.StringIO) -> None: title = "No file list" lines = [f"There is no file list for {display_name(plat)} at this address." if exc.code == 404 else f"The server answered HTTP {exc.code}."] - if exc.code == 404 and not os.environ.get("RETROBIOS_BASE_URL"): + if exc.code == 404 and not remote.overridden: # Line mode named RETROBIOS_REF as the cause, the screen nothing. lines.append(missing_list_advice(plat, "choose Try again")) except (urllib.error.URLError, OSError) as exc: @@ -190,7 +191,7 @@ def _tui_fetch(plat: str, inbox: queue.Queue, log: io.StringIO) -> None: # Named, never shown: the value can hold a password. lines.append(f"{proxy} is set, so the connection goes through a proxy: " "check that it answers.") - if os.environ.get("RETROBIOS_BASE_URL"): + if remote.overridden: lines.append(f"RETROBIOS_BASE_URL chose the address: {url}") inbox.put(("manifest_failed", plat, title, lines, 1)) diff --git a/tests/test_install.py b/tests/test_install.py index cef7996e6..4ba1167dd 100644 --- a/tests/test_install.py +++ b/tests/test_install.py @@ -490,9 +490,7 @@ class TheDataTreesCountInTheFreeSpace(unittest.TestCase): with unittest.mock.patch.object( sys, "argv", ["install.py", "--platform", "retroarch", "--dest", str(repo.dest), "--no-input"]), \ - unittest.mock.patch.object(install, "MANIFEST_URL", - base + "/install/{platform}.json"), \ - unittest.mock.patch.object(install, "RAW_FILE_URL", base + "/{path}"), \ + unittest.mock.patch.dict(os.environ, {"RETROBIOS_BASE_URL": base}), \ unittest.mock.patch.object(install.shutil, "disk_usage", lambda _p, free=free: SimpleNamespace(free=free)), \ unittest.mock.patch.object( @@ -1888,13 +1886,33 @@ class TestBaseUrlScheme(unittest.TestCase): ) def test_plain_http_is_refused(self): - with self.assertRaises(SystemExit): + with self.assertRaises(ValueError): install._checked_base_url("http://example.test/repo") def test_local_file_scheme_is_refused(self): - with self.assertRaises(SystemExit): + with self.assertRaises(ValueError): install._checked_base_url("file:///etc") + def test_a_refused_base_is_said_by_main_and_ends_on_code_1(self): + with unittest.mock.patch.dict(os.environ, {"RETROBIOS_BASE_URL": "http://example.test"}), \ + unittest.mock.patch.object(sys, "argv", ["install.py", "--help"]), \ + contextlib.redirect_stderr(io.StringIO()) as err, \ + self.assertRaises(SystemExit) as stopped: + install.main() + self.assertEqual(stopped.exception.code, 1) + self.assertEqual(err.getvalue(), + "Error: RETROBIOS_BASE_URL must use HTTPS, got 'http://example.test'\n") + + def test_an_empty_variable_is_unset(self): + # Set but empty, the base killed even an import of install.py, where + # every other reading of it takes it as unset. + with unittest.mock.patch.dict(os.environ, {"RETROBIOS_BASE_URL": "", + "RETROBIOS_REF": ""}): + remote = install.remote_from_env() + self.assertEqual(remote, install.Remote( + install.DEFAULT_RELEASE_REF, install.default_base_url(install.DEFAULT_RELEASE_REF), + False)) + def test_loopback_http_is_allowed_for_end_to_end_runs(self): for url in ( "http://127.0.0.1:8080/repo", @@ -2878,8 +2896,8 @@ class ASilentServerIsBounded(unittest.TestCase): start = time.monotonic() with unittest.mock.patch.object(install, "LIST_TIMEOUT", 0.5), \ unittest.mock.patch.object(install, "_retry_delay", return_value=0), \ - unittest.mock.patch.object(install, "MANIFEST_URL", - f"http://127.0.0.1:{port}/{{platform}}.json"), \ + unittest.mock.patch.dict(os.environ, + {"RETROBIOS_BASE_URL": f"http://127.0.0.1:{port}"}), \ contextlib.redirect_stderr(err), self.assertRaises(SystemExit): install.fetch_manifest("retroarch") elapsed = time.monotonic() - start @@ -5162,7 +5180,8 @@ class AMissingFileListNamesTheRef(unittest.TestCase): def _run(self, ref: str) -> str: error = install.urllib.error.HTTPError("u", 404, "Not Found", None, None) - with unittest.mock.patch.object(install, "RELEASE_REF", ref), \ + with unittest.mock.patch.dict(os.environ, {"RETROBIOS_REF": ref, + "RETROBIOS_BASE_URL": ""}), \ unittest.mock.patch.object(install, "_fetch_json", side_effect=error), \ contextlib.redirect_stderr(io.StringIO()) as err, \ self.assertRaises(SystemExit): @@ -5693,7 +5712,7 @@ class AnOverrideIsNamedWhenItIsTheCause(unittest.TestCase): self.assertRaises(SystemExit): install.fetch_manifest("retroarch") text = err.getvalue() - self.assertIn("Address: " + install.MANIFEST_URL.format(platform="retroarch"), text) + self.assertIn("Address: https://mirror.invalid/install/retroarch.json", text) self.assertIn("RETROBIOS_BASE_URL is set", text) def test_a_pinned_fingerprint_is_named(self): diff --git a/tests/test_install_app.py b/tests/test_install_app.py index 5e87e7d86..9dc11a526 100644 --- a/tests/test_install_app.py +++ b/tests/test_install_app.py @@ -224,10 +224,8 @@ class PutTheApp(unittest.TestCase): self.repo.__enter__() self.addCleanup(self.repo.__exit__, None, None, None) install.KEPT.reset() - patcher = mock.patch.multiple( - install, LAUNCHERS_URL=f"{self.repo.env()['RETROBIOS_BASE_URL']}" - "/install/launchers/index.json", - RAW_FILE_URL=f"{self.repo.env()['RETROBIOS_BASE_URL']}/{{path}}") + patcher = mock.patch.object(install, "active_remote", return_value=install.Remote( + install.DEFAULT_RELEASE_REF, self.repo.env()["RETROBIOS_BASE_URL"], False)) patcher.start() self.addCleanup(patcher.stop) self.index = json.loads(INDEX.read_text(encoding="utf-8")) diff --git a/tests/test_install_experience.py b/tests/test_install_experience.py index 79047c73e..9cac5ddec 100644 --- a/tests/test_install_experience.py +++ b/tests/test_install_experience.py @@ -75,7 +75,8 @@ class _Server: self.httpd = http.server.ThreadingHTTPServer(("127.0.0.1", 0), _RangeHandler) threading.Thread(target=self.httpd.serve_forever, daemon=True).start() port = self.httpd.server_address[1] - self.patch = mock.patch.object(install, "RAW_FILE_URL", f"http://127.0.0.1:{port}/{{path}}") + self.patch = mock.patch.object(install, "active_remote", return_value=install.Remote( + install.DEFAULT_RELEASE_REF, f"http://127.0.0.1:{port}", False)) self.patch.start() return self diff --git a/tests/test_install_selection.py b/tests/test_install_selection.py index 9442723e1..3aba493aa 100644 --- a/tests/test_install_selection.py +++ b/tests/test_install_selection.py @@ -379,10 +379,8 @@ class DecliningTheSizePointsAtTheChoice(unittest.TestCase): with FakeRepository() as repo, mock.patch.dict(os.environ), \ mock.patch.object(sys, "argv", ["install.py", "--platform", "retroarch", "--dest", str(repo.dest), *options]), \ - mock.patch.object(install, "MANIFEST_URL", - repo.env()["RETROBIOS_BASE_URL"] + "/install/{platform}.json"), \ - mock.patch.object(install, "RAW_FILE_URL", - repo.env()["RETROBIOS_BASE_URL"] + "/{path}"), \ + mock.patch.dict(os.environ, + {"RETROBIOS_BASE_URL": repo.env()["RETROBIOS_BASE_URL"]}), \ mock.patch.object(install, "CONFIRM_FROM_BYTES", 1), \ mock.patch("sys.stdin", mock.Mock(isatty=lambda: True)), \ mock.patch.object(install, "_is_terminal", return_value=True), \ diff --git a/tests/test_install_tui.py b/tests/test_install_tui.py index 28827959b..28396cd4b 100644 --- a/tests/test_install_tui.py +++ b/tests/test_install_tui.py @@ -2228,8 +2228,8 @@ class TicksBarAndPaths(unittest.TestCase): port = probe.getsockname()[1] inbox = __import__("queue").Queue() started = time.monotonic() - with mock.patch.object(install, "MANIFEST_URL", - f"http://127.0.0.1:{port}/install/{{platform}}.json"): + with mock.patch.object(install, "active_remote", return_value=install.Remote( + install.DEFAULT_RELEASE_REF, f"http://127.0.0.1:{port}", False)): install._tui_fetch("retroarch", inbox, io.StringIO()) self.assertLess(time.monotonic() - started, 5) kind, plat, title, lines, code = inbox.get_nowait() @@ -2252,8 +2252,8 @@ class TicksBarAndPaths(unittest.TestCase): inbox = __import__("queue").Queue() missing = install.urllib.error.HTTPError("u", 404, "Not Found", {}, None) with mock.patch.object(install, "_fetch_json", side_effect=missing), \ - mock.patch.object(install, "RELEASE_REF", "v2020.01.01"), \ - mock.patch.dict(os.environ, {"RETROBIOS_BASE_URL": ""}): + mock.patch.dict(os.environ, {"RETROBIOS_REF": "v2020.01.01", + "RETROBIOS_BASE_URL": ""}): install._tui_fetch("batocera", inbox, io.StringIO()) _kind, _plat, title, lines, _code = inbox.get_nowait() self.assertEqual(title, "No file list") @@ -7462,11 +7462,8 @@ class WhatEachScreenOffers(unittest.TestCase): with SaveDirectoryRepository() as repo: argv = ["install.py", "--platform", "retroarch", "--dest", str(repo.dest), "--manifest", str(repo.root / "install" / "retroarch.json")] - # The files come from the repository on the loopback: the module - # read its base before the environment named it. - served = repo.env()["RETROBIOS_BASE_URL"] + "/{path}" + # The files come from the repository on the loopback. with mock.patch.dict(os.environ, repo.env()), \ - mock.patch.object(install, "RAW_FILE_URL", served), \ mock.patch.object(sys, "argv", argv), \ mock.patch.object(sys.stdin, "isatty", return_value=True), \ mock.patch.object(install, "_is_terminal", return_value=True), \