refactor: one refusal path to stderr and events

Library functions printed their refusal and exited, each deciding on its
own whether --events got an error event. --cores-dir, --installed-cores
with no core, a list without system_cores or standalone_builds, a pack
that cannot be used, a board list a run needs and --dest alone beside
two setups ended on code 1 with no reason in the stream.

They now raise Refusal (installer/refusal.py), carrying the stage, the
reason, the platform, the lines and the code. The install, an action
framed by events and main report it once: the error event, then the
same lines on stderr, so the text and exit codes stay as they were.
This commit is contained in:
Abdessamad Derraz committed 2026-11-21 19:50:46 +01:00
1 parent ced68a9135
commit eba627aa89
20 files changed
+542 -402

No files matched your search

+10 -13
View File
@@ -2,7 +2,6 @@
from __future__ import annotations
import argparse
import sys
from collections.abc import Collection, Iterable
from typing import TYPE_CHECKING
@@ -22,6 +21,7 @@ from installer.platforms import (
key_file_holders,
refuse_name,
)
from installer.refusal import Refusal
from installer.regions import WORLD_REGION, resolve_regions
from installer.remote import DEFAULT_RELEASE_REF, active_remote
from installer.text import _plural
@@ -347,10 +347,9 @@ def _narrow_to_emulators(
does not run is refused rather than read as nothing to install.
"""
if "system_cores" not in manifest:
print(f"Error: the {plat} file list does not say which emulators read "
"which systems, which --emulator needs.", file=sys.stderr)
print(_older_list_advice(plat), file=sys.stderr)
sys.exit(1)
raise Refusal("option", "not_recorded", plat,
f"Error: the {plat} file list does not say which emulators read "
"which systems, which --emulator needs.", _older_list_advice(plat))
known = sorted(emulator_names(manifest, files, omitted))
try:
chosen = resolve_choices(names, known, "emulator")
@@ -383,10 +382,9 @@ def _standalone_builds(
place of the files its core reads. An emulator with no standalone
build is refused, as `generate_pack.py --standalone` refuses it."""
if "standalone_builds" not in manifest:
print(f"Error: the {plat} file list does not say which emulators have a "
"standalone build, which --standalone needs.", file=sys.stderr)
print(_older_list_advice(plat), file=sys.stderr)
sys.exit(1)
raise Refusal("option", "not_recorded", plat,
f"Error: the {plat} file list does not say which emulators have a "
"standalone build, which --standalone needs.", _older_list_advice(plat))
profiles = sorted({names[name] for name in resolve_choices(values, sorted(names),
"emulator")})
lacking = [p for p in profiles if p not in manifest["standalone_builds"]]
@@ -490,10 +488,9 @@ def _requested_narrowing(
# lacks, with what works on it.
source = (LOCAL.pack.name if pack_alone and LOCAL.pack is not None
else f"the {plat} file list")
print(f"Error: {source} records no {axis}, so {flag} cannot narrow it.",
file=sys.stderr)
print(_narrowing_advice(plat, axis, flag, recorded, pack_alone), file=sys.stderr)
sys.exit(1)
raise Refusal("option", "not_recorded", plat,
f"Error: {source} records no {axis}, so {flag} cannot narrow it.",
_narrowing_advice(plat, axis, flag, recorded, pack_alone))
choices = available_choices(files, omitted)
try:
systems = resolve_systems(args.system or [], manifest, files, omitted)
+10 -1
View File
@@ -30,6 +30,7 @@ from installer.narrowing import FIND_KINDS
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.refusal import Refusal
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
@@ -311,7 +312,13 @@ def main() -> None:
print(f"Error: {exc}", file=sys.stderr)
sys.exit(1)
with remote_in_use(remote):
_main_run()
try:
_main_run()
except Refusal as refusal:
# Raised outside an install, which reports its own: the full
# screen's start, an action and the sources opened before it.
refusal.report()
raise
def _main_run() -> None:
@@ -438,6 +445,8 @@ def _run_action(args: argparse.Namespace,
try:
code = action(args)
except SystemExit as exc:
if isinstance(exc, Refusal):
exc.report()
EVENTS.emit("end", code=_event_exit_code(exc.code))
raise
except KeyboardInterrupt:
+17 -17
View File
@@ -3,8 +3,8 @@ from __future__ import annotations
import os
import re
import sys
from pathlib import Path
from typing import NoReturn
from installer.config_values import _retroarch_cfg_dir
from installer.events import EVENTS
@@ -14,6 +14,7 @@ from installer.invocation import _INVOCATION
from installer.local_check import closed_folder_words
from installer.manifest import entry_copies
from installer.platforms import display_name
from installer.refusal import Refusal
from installer.text import _plural, screen_text
# A libretro core as RetroArch loads it: <name>_libretro.so|dll|dylib, and
@@ -145,7 +146,7 @@ def unknown_cores(manifest: dict, names: list[str]) -> list[str]:
return sorted(name for name in names if name not in known)
def _check_cores_dir(folder: Path) -> None:
def _check_cores_dir(folder: Path, plat: str) -> None:
"""Refuse a --cores-dir that cannot be listed, saying why: a typo
(core/ for cores/) or a closed folder read as an empty one, and the
run said "none in" and asked for the --cores-dir it was given."""
@@ -153,20 +154,20 @@ def _check_cores_dir(folder: Path) -> None:
with os.scandir(folder):
return
except FileNotFoundError:
why = "does not exist"
reason, why = "not_found", "does not exist"
except NotADirectoryError:
why = "is not a folder"
reason, why = "not_a_folder", "is not a folder"
except PermissionError as exc:
closed = closed_folder(folder)
reason = "unreadable"
why = (f"cannot be opened by this user ({exc.strerror or exc})"
if closed is None or closed[0] == folder
else f"cannot be opened: {closed_folder_words(folder, closed)}")
except OSError as exc:
why = f"could not be read ({exc.strerror or exc})"
print(f"Error: --cores-dir {screen_text(str(folder))} {why}.", file=sys.stderr)
print(" Name the folder RetroArch loads cores from (libretro_directory in "
"retroarch.cfg, cores/ beside RetroArch by default).", file=sys.stderr)
sys.exit(1)
reason, why = "unreadable", f"could not be read ({exc.strerror or exc})"
raise Refusal("cores", reason, plat, f"Error: --cores-dir {screen_text(str(folder))} {why}.",
" Name the folder RetroArch loads cores from (libretro_directory in "
"retroarch.cfg, cores/ beside RetroArch by default).")
def _unprofiled_cores_firmware(
@@ -200,7 +201,7 @@ def _unprofiled_cores_firmware(
return dests
def _no_core_found(plat: str, bios_path: Path, searched: list[Path]) -> None:
def _no_core_found(plat: str, bios_path: Path, searched: list[Path]) -> NoReturn:
"""Refuse --installed-cores with no core, and say how to point at them.
With no retroarch.cfg naming the folder as its system_directory, and
@@ -209,11 +210,10 @@ def _no_core_found(plat: str, bios_path: Path, searched: list[Path]) -> None:
"""
where = (f"none in {', '.join(map(str, searched))}" if searched
else f"no retroarch.cfg was found for {bios_path} to name their folder")
print(f"Error: no installed core found for {display_name(plat)}: {where}.",
file=sys.stderr)
print(" Name the folder RetroArch loads cores from (libretro_directory in "
"retroarch.cfg, cores/ beside RetroArch by default):", file=sys.stderr)
command = _INVOCATION.command(plat, bios_path, without=("--installed-cores", "--cores-dir"))
print(f" {command} --cores-dir <cores folder>", file=sys.stderr)
print(" Or run it without --installed-cores to install every file.", file=sys.stderr)
sys.exit(1)
raise Refusal("cores", "none", plat,
f"Error: no installed core found for {display_name(plat)}: {where}.",
" Name the folder RetroArch loads cores from (libretro_directory in "
"retroarch.cfg, cores/ beside RetroArch by default):",
f" {command} --cores-dir <cores folder>",
" Or run it without --installed-cores to install every file.")
+22 -30
View File
@@ -26,11 +26,11 @@ from installer.cards import (
from installer.console import _answer_yes, _folder_answer, _numbers_hint, _typed_folder, detail
from installer.detect_os import _DETECTED_OS, card_title, detect_os, detected_os, os_conflict
from installer.embedded import CARD_MARKER, CARD_PLATFORMS, _EMBEDDED_RULES, _a, _built_on
from installer.events import EVENTS
from installer.host_fs import _exists, _is_dir, closed_folder
from installer.local_check import closed_folder_words
from installer.paths import shown_path
from installer.platforms import _name_key, did_you_mean, display_name, normalize_platform, refuse_name
from installer.refusal import Refusal
from installer.setups import _choose_platform, _setup_label, drive_example, found_setups
from installer.text import _names_and, _plural, screen_text
@@ -42,11 +42,10 @@ def _refuse_closed(dest: Path, named: str) -> None:
if closed is None:
return
message = closed_folder_words(dest, closed)
EVENTS.emit("error", stage="dest", reason="unreadable", platform="", message=message)
print(f"Error: {screen_text(message)}. Give this user access to it, run as "
f"its owner, or choose another folder than the one {named}.",
file=sys.stderr)
sys.exit(1)
raise Refusal("dest", "unreadable", "",
f"Error: {screen_text(message)}. Give this user access to it, run as "
f"its owner, or choose another folder than the one {named}.",
message=message)
def _refuse_file(dest: Path, named: str) -> None:
@@ -64,10 +63,9 @@ def _refuse_file(dest: Path, named: str) -> None:
return
where = (f"{shown_path(dest)} is a file, not a folder" if folder == dest
else f"{shown_path(dest)} cannot be a folder: {shown_path(folder)} is a file")
EVENTS.emit("error", stage="dest", reason="not_a_folder", platform="", message=where)
print(f"Error: {screen_text(where)}. Name the folder the BIOS files go in, not "
f"the file {named}.", file=sys.stderr)
sys.exit(1)
raise Refusal("dest", "not_a_folder", "",
f"Error: {screen_text(where)}. Name the folder the BIOS files go in, not "
f"the file {named}.", message=where)
def _missing_dest(dest: Path, ask: bool, named: str = "named with --dest",
@@ -434,11 +432,8 @@ def card_dest(named: str, plat: str, dest: Path) -> tuple[str, Path]:
choice = card_choice(named, plat, dest)
if choice.refused:
message = _dest_refusal_words(choice, card_setup(named, plat))
# A script reading the stream learned code 1 and no reason.
EVENTS.emit("error", stage="detect", reason="not_found", platform=choice.plat,
message=message)
print(f"Error: {message}", file=sys.stderr)
sys.exit(1)
raise Refusal("detect", "not_found", choice.plat, f"Error: {message}",
message=message)
for line in (choice.found, choice.note):
if line:
print(f" {line}")
@@ -523,12 +518,11 @@ def card_install_dest(named: str, plat: str, interactive: bool, ask: bool = True
print(f" {len(cards)} {system} cards are mounted: "
+ ", ".join(_mount_name(card) for card in cards) + ".", file=sys.stderr)
if not interactive:
EVENTS.emit("error", stage="detect", reason="not_found", platform=plat,
message=f"{system} keeps its BIOS files on its SD card, and no "
"card was named with --dest")
print(f" {system} keeps its BIOS files on its SD card, not on this machine. "
f"Mount it and give its root with --dest: {example}", file=sys.stderr)
sys.exit(1)
raise Refusal("detect", "not_found", plat,
f" {system} keeps its BIOS files on its SD card, not on this machine. "
f"Mount it and give its root with --dest: {example}",
message=f"{system} keeps its BIOS files on its SD card, and no "
"card was named with --dest")
print(f" {system} keeps its BIOS files {card_where(system, setup.below)}, not on "
"this machine. "
+ ("" if setup.known() else
@@ -633,16 +627,16 @@ def _platform_for_dest(os_type: str, dest: Path, interactive: bool) -> tuple[str
found = list(dict.fromkeys(name for name, _path, _label in found_setups(os_type)[0]))
default = found[0] if len(found) == 1 else "" if found else "retroarch"
if not default:
print(f"Error: {' and '.join(display_name(n) for n in found)} found here. "
f"Name the platform {dest} is for with --platform.", file=sys.stderr)
sys.exit(1)
raise Refusal("detect", "conflict", "",
f"Error: {' and '.join(display_name(n) for n in found)} found here. "
f"Name the platform {dest} is for with --platform.")
why = "the platform found here" if found else "nothing was detected here"
print(f" File list: {display_name(default)} ({why}). For another platform's "
"list, add --platform (--list-platforms names them).")
return default, dest
def _several_found(platforms: list[tuple[str, Path]], setups: list) -> None:
def _several_found(platforms: list[tuple[str, Path]], setups: list) -> NoReturn:
"""Stop a run without questions that found more than one setup, each
named with the options that choose it."""
labels = {(name, path): label for name, path, label in setups}
@@ -653,11 +647,9 @@ def _several_found(platforms: list[tuple[str, Path]], setups: list) -> None:
if conflict else f"{len(shown)} setups were found here")
message = (f"{lead}, and a run without questions installs for one: "
+ ", ".join(label for label, _n, _p in shown))
EVENTS.emit("error", stage="detect", reason="conflict", platform="", message=message)
print(f"Error: {message}. Name the one to install for:", file=sys.stderr)
for label, name, path in shown:
print(f" {label}: --platform {name} --dest {shown_path(path)}", file=sys.stderr)
sys.exit(1)
raise Refusal("detect", "conflict", "", f"Error: {message}. Name the one to install for:",
*(f" {label}: --platform {name} --dest {shown_path(path)}"
for label, name, path in shown), message=message)
def _unknown_target(target: str, plat: str, targets: dict, *after: str) -> NoReturn:
+11 -2
View File
@@ -23,7 +23,9 @@ EVENT_KEYS: dict[str, tuple[str, ...]] = {
# stage: manifest (reason: network, not_found, invalid, clock for a
# refused certificate under a clock set in the past, no_ca for no
# trusted certificates on the machine, or no_ssl for a Python built
# without ssl) or detect (reason: conflict, two
# without ssl, unreadable for a --manifest file that cannot be read,
# unavailable for the standalone layout --standalone needs) or detect
# (reason: conflict, two
# systems found on one machine, or not_found, the platform named with
# --platform, or by a file list or a pack in a run without questions,
# found nowhere and no folder to assume) or from (a folder named with --from,
@@ -33,7 +35,14 @@ EVENT_KEYS: dict[str, tuple[str, ...]] = {
# is a file or lies under one, or not_writable, the BIOS folder cannot
# be created, a summary following) or option (reason:
# unknown, a platform, target, system, core or emulator the run cannot
# use, refused before any download).
# use, refused before any download, or not_recorded, the list does not
# record what --system, --core, --region, --emulator or --standalone
# reads) or cores (--installed-cores, reason: not_found, not_a_folder
# or unreadable for the --cores-dir, none for no core installed) or
# targets (the board list a run cannot go on without, reason: the
# manifest's codes, http for a refused answer) or pack (--from-pack,
# reason: invalid, other_platform for a pack of another platform, or
# no_platform when none is named and the pack does not say).
"error": ("stage", "reason", "platform", "message"),
# A folder named with --from, once read: the files it holds (counted
# up to MAX_SCANNED_FILES, truncated past them), and the folders below
+11 -13
View File
@@ -4,7 +4,6 @@ from __future__ import annotations
import argparse
import contextlib
import os
import sys
import threading
import zipfile
from collections.abc import Callable, Collection, Iterator
@@ -19,6 +18,7 @@ from installer.offline import LOCAL, local_manifest_platform
from installer.pack_source import _PART_FILE, PackSource
from installer.paths import _entry_path, _safe_relative_path, shown_path
from installer.platforms import display_name, normalize_platform
from installer.refusal import Refusal
from installer.safe_replace import BACKUP_DIR, _MEMBER_ERRORS, _write_verified, unreadable_words
from installer.tally import _bytes
from installer.text import _plural, format_size, screen_text, shown_lines
@@ -821,8 +821,7 @@ def _open_local_sources(args: argparse.Namespace) -> None:
try:
LOCAL.pack = PackSource(args.from_pack)
except ValueError as exc:
print(f"Error: {exc}", file=sys.stderr)
sys.exit(1)
raise Refusal("pack", "invalid", args.platform or "", f"Error: {exc}") from None
pack = LOCAL.pack
parts = len(pack.files)
print(f" Pack: {pack.name}"
@@ -831,10 +830,10 @@ def _open_local_sources(args: argparse.Namespace) -> None:
if args.platform is not None:
plat = normalize_platform(args.platform, say=False)
if spelled and plat not in spelled:
print(f"Error: {pack.name} is a pack for "
f"{' and '.join(display_name(n) for n in spelled)}, not "
f"{display_name(plat)}.", file=sys.stderr)
sys.exit(1)
raise Refusal("pack", "other_platform", plat,
f"Error: {pack.name} is a pack for "
f"{' and '.join(display_name(n) for n in spelled)}, not "
f"{display_name(plat)}.")
elif len(spelled) == 1:
# Named by the pack, not by the user: the setups that read its list
# are offered, as for a --manifest.
@@ -842,9 +841,9 @@ def _open_local_sources(args: argparse.Namespace) -> None:
args.platform_from_list = True
else:
among = (" (" + ", ".join(spelled) + ")") if spelled else ""
print(f"Error: name the platform {pack.name} is installed for with "
f"--platform{among}.", file=sys.stderr)
sys.exit(1)
raise Refusal("pack", "no_platform", "",
f"Error: name the platform {pack.name} is installed for with "
f"--platform{among}.")
def _system_folder(folder: Path) -> str:
@@ -898,9 +897,8 @@ def _open_from_folders(folders: list[Path]) -> None:
if problem is not None:
reason, what = problem
message = f"{label} {what}: --from names the folder to copy BIOS files from"
EVENTS.emit("error", stage="from", reason=reason, platform="", message=message)
print(f"Error: {screen_text(message)}.", file=sys.stderr)
sys.exit(1)
raise Refusal("from", reason, "", f"Error: {screen_text(message)}.",
message=message)
_read_from_folder(label)
+20 -16
View File
@@ -7,12 +7,12 @@ import urllib.error
from pathlib import Path
from typing import NamedTuple
from installer.events import EVENTS
from installer.host_fs import _is_file, read_local_json
from installer.manifest import _check_standalone_layouts, _validate_manifest, _validate_targets
from installer.network import _address_lines, _fetch_json, network_words, request_proxy
from installer.offline import LOCAL, _Offline, offline_named, offline_undo, offline_words
from installer.platforms import TARGET_PLATFORMS, display_name
from installer.refusal import Refusal
from installer.remote import (
DEFAULT_RELEASE_REF,
MAX_MANIFEST_BYTES,
@@ -197,12 +197,13 @@ def fetch_manifest(plat: str) -> dict:
return load_manifest(plat)
except ListFailure as stopped:
failure = stopped.problem
event = _manifest_event(failure)
if event is not None:
EVENTS.emit("error", stage="manifest", reason=event[0], platform=plat,
message=event[1])
_say(manifest_failure_lines(failure))
sys.exit(failure.fatal)
lines = manifest_failure_lines(failure)
# A list given as a file or in a pack that cannot be used ended the
# run on code 1 with no event: its words are the message.
reason, message = _manifest_event(failure) or (
failure.code, " ".join(line.strip() for line in lines))
raise Refusal("manifest", reason, plat, *lines, code=failure.fatal,
message=message) from None
def _say(lines: list[str]) -> None:
@@ -240,11 +241,9 @@ def fetch_standalone(plat: str, manifest: dict) -> dict:
else network_words(exc)[1])
except ValueError as exc:
problem = f"not valid: {exc}"
EVENTS.emit("error", stage="manifest", reason="unavailable", platform=plat,
message=f"--standalone needs {where}: {problem}")
print(f"Error: --standalone needs {where}, which could not be read ({problem}).",
file=sys.stderr)
sys.exit(1)
raise Refusal("manifest", "unavailable", plat,
f"Error: --standalone needs {where}, which could not be read ({problem}).",
message=f"--standalone needs {where}: {problem}")
def held_targets(plat: str) -> dict | None:
@@ -275,8 +274,7 @@ def local_targets(plat: str) -> dict | None:
try:
return held_targets(plat)
except ListFailure as stopped:
_say(targets_failure_lines(stopped.problem))
sys.exit(stopped.problem.fatal)
raise _targets_refusal(stopped.problem) from None
def load_targets(plat: str, attempts: int = MAX_RETRIES,
@@ -327,6 +325,12 @@ def targets_failure_lines(failure: ListProblem) -> list[str]:
*_address_lines(where, failure.overridden), NETWORK_ADVICE]
def _targets_refusal(failure: ListProblem) -> Refusal:
"""A board list the run cannot go on without, as the run's refusal."""
return Refusal("targets", failure.code, failure.plat, *targets_failure_lines(failure),
code=failure.fatal)
def fetch_targets(plat: str, attempts: int = MAX_RETRIES,
timeout: float | None = None) -> dict | None:
"""load_targets in line mode: what went wrong said, None when the run
@@ -334,7 +338,7 @@ def fetch_targets(plat: str, attempts: int = MAX_RETRIES,
try:
return load_targets(plat, attempts, timeout)
except ListFailure as stopped:
_say(targets_failure_lines(stopped.problem))
if stopped.problem.fatal:
sys.exit(stopped.problem.fatal)
raise _targets_refusal(stopped.problem) from None
_say(targets_failure_lines(stopped.problem))
return None
+36
View File
@@ -0,0 +1,36 @@
"""A refusal that ends the run, raised where it is decided and reported once by the command."""
from __future__ import annotations
import sys
from installer.events import EVENTS
class Refusal(SystemExit):
"""The run refused, with the error event a script reads and the lines a
person reads. Each site printed its lines and chose on its own whether
--events got the reason, and several did not: a script learned code 1
and nothing else. message is the event's, by default the lines joined
without their leading "Error: "."""
def __init__(self, stage: str, reason: str, platform: str, *lines: str,
code: int = 1, message: str | None = None) -> None:
super().__init__(code)
self.stage, self.reason, self.platform = stage, reason, platform
self.lines = lines
if message is None:
message = " ".join(line.strip() for line in lines)
if message.startswith("Error: "):
message = message[len("Error: "):]
self.message = message
self.reported = False
def report(self) -> None:
"""The error event, then the lines on stderr, once."""
if self.reported:
return
self.reported = True
EVENTS.emit("error", stage=self.stage, reason=self.reason, platform=self.platform,
message=self.message)
for line in self.lines:
print(line, file=sys.stderr)
+12 -1
View File
@@ -57,6 +57,7 @@ from installer.pack_source import NOT_IN_PACK, pack_holds_trees, pack_lacks, pac
from installer.paths import _entry_path, shown_path
from installer.plan import CONFIRM_FROM_BYTES, _check_free_space, _print_plan, bulk_hint
from installer.platforms import display_name
from installer.refusal import Refusal
from installer.romm import ROMM_SCAN_WORDS, _check_run_romm, _pass_romm_layout
from installer.run_files import _select_setup_files
from installer.run_setups import (
@@ -762,7 +763,17 @@ def _finish_install(run: _InstallRun, real_stdout: TextIO) -> None:
def _install(args: argparse.Namespace, real_stdout: TextIO) -> None:
"""One run of the installer, once the options are read."""
"""One run of the installer, once the options are read, a refusal
reported where it ends the run: its error event before end, its lines
before what the unwinding run says."""
try:
_install_run(args, real_stdout)
except Refusal as refusal:
refusal.report()
raise
def _install_run(args: argparse.Namespace, real_stdout: TextIO) -> None:
run = _start_install(args, real_stdout)
# Early exit for listing
+1 -1
View File
@@ -465,7 +465,7 @@ def _check_run_cores(run: _InstallRun) -> None:
for plat_name, bios_path in [] if run.packing else run.platforms:
if plat_name in CORE_PLATFORMS:
if args.cores_dir:
_check_cores_dir(args.cores_dir)
_check_cores_dir(args.cores_dir, plat_name)
searched = [args.cores_dir] if args.cores_dir else core_dirs(plat_name, bios_path)
run.cores_found[(plat_name, bios_path)] = installed_cores(searched)
run.cores_searched[(plat_name, bios_path)] = searched