From 665e2ebb52ddfd2bf8d0f2a333b0cd45e4a963df Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Sat, 21 Nov 2026 20:46:18 +0100 Subject: [PATCH] fix: send every refusal as an error event --romm-firmware, --pack without a platform, an option the list does not record, a board list the run cannot go on without, a full drive and the --dest a named platform needs printed and exited on their own: --events got end and no error. Each now raises Refusal where it is decided, and refuse_name, --find and the space check stop formatting their own copy. --- install.ps1 | 2 +- install.py | 649 +++++++++++++++++------------------ install.sh | 2 +- install/launchers/index.json | 16 +- installer/plan.py | 36 +- installer/platforms.py | 12 +- installer/romm.py | 14 +- installer/run_files.py | 64 ++-- installer/run_setups.py | 66 ++-- tests/test_install.py | 17 +- tests/test_install_cores.py | 6 +- tests/test_install_tui.py | 2 +- wiki/installer.md | 2 +- 13 files changed, 418 insertions(+), 470 deletions(-) diff --git a/install.ps1 b/install.ps1 index 5cb14cbdb..d87148530 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 = "7eb5c3718dc892a8cc773493724757cd2de45793475e96082a09fbb535aae769" + $defaultInstallSha256 = "13b42cf02602fe7cfee80ce9ed25544c6e8ff1c51feb0d62e4dc07e81eeaf951" # 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 66073937b..1ca123d06 100644 --- a/install.py +++ b/install.py @@ -3790,6 +3790,38 @@ def _validate_targets(data: object) -> dict[str, dict]: return normalized +# --- installer/refusal.py ---------------------------------------------------- + +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) + + # --- installer/platforms.py -------------------------------------------------- # The platforms that publish a core list per board, install/targets/ in the @@ -3979,14 +4011,7 @@ def refuse_name(platform: str, *lines: str) -> NoReturn: 2, as for an option argparse refuses: 1 also means --check found files to fetch, and a script reading it reran the install on a typo forever. """ - message = " ".join(line.strip() for line in lines) - if message.startswith("Error: "): - message = message[len("Error: "):] - EVENTS.emit("error", stage="option", reason="unknown", platform=platform, - message=message) - for line in lines: - print(line, file=sys.stderr) - sys.exit(2) + raise Refusal("option", "unknown", platform, *lines, code=2) # Frontends and systems that keep no BIOS folder of their own: each @@ -7368,6 +7393,210 @@ def not_in_place(bios_path: Path, files: list[dict]) -> list[dict]: if verdict != "up_to_date"] +# --- installer/cores.py ------------------------------------------------------ + +# A libretro core as RetroArch loads it: _libretro.so|dll|dylib, and +# _libretro_android.so on Android. +_CORE_FILE_RE = re.compile( + r"^(?P.+?)_libretro(?:_android)?\.(?:so|dll|dylib)$", re.IGNORECASE +) +CORE_PLATFORMS = ("retroarch", "lakka", "retropie") +# Where these systems install cores whatever retroarch.cfg says: RetroPie +# gives each package its own folder, Lakka keeps the image's cores and the +# ones the online updater fetches apart. +_FIXED_CORE_DIRS = { + "retropie": (Path("/opt/retropie/libretrocores"),), + "lakka": (Path("/usr/lib/libretro"), Path("/storage/cores"), Path("/tmp/cores")), +} + + +def _config_beside(bios_path: Path) -> tuple[Path, Path] | None: + """The retroarch.cfg detection read for bios_path and the directory ':' + expands to, else a portable one beside the system directory.""" + found = _retroarch_config_for(bios_path) + if found is None and _is_file(bios_path.parent / "retroarch.cfg"): + found = (bios_path.parent / "retroarch.cfg", bios_path.parent) + return found + + +def core_dirs(plat: str, bios_path: Path) -> list[Path]: + """The directories the RetroArch writing to bios_path loads cores from. + + The config detection read for this system directory names them in + libretro_directory, read here when the run was given --dest, as the + interface's runs all are. Without one, a retroarch.cfg beside the system + directory is the portable layout. Unset, the setting is cores/ under + RetroArch's own directory. + """ + found = _config_beside(bios_path) + dirs: list[Path] = [] + if found is not None: + cfg, app_dir = found + dirs.append( + _retroarch_cfg_dir(cfg, "libretro_directory", app_dir, "cores") + or app_dir / "cores" + ) + dirs.extend(_FIXED_CORE_DIRS.get(plat, ())) + return list(dict.fromkeys(dirs)) + + +def installed_cores(dirs: list[Path]) -> list[str]: + """The cores present in these directories, by the name the buildbot uses. + + A folder inside is looked into once, which is how RetroPie installs + each package. An unreadable directory holds nothing that can be seen. + """ + names: set[str] = set() + for directory in dirs: + try: + children = list(directory.iterdir()) + except OSError: + continue + for child in children: + candidates = [child] + if child.is_dir(): + try: + candidates = list(child.iterdir()) + except OSError: + continue + for path in candidates: + match = _CORE_FILE_RE.match(path.name) + if match and path.is_file(): + names.add(match.group("name")) + return sorted(names) + + +def info_dirs(plat: str, bios_path: Path, searched: list[Path]) -> list[Path]: + """The directories RetroArch reads core .info files from. + + libretro_info_path in retroarch.cfg, info/ beside RetroArch by default, + then the cores folders: Linux builds and Lakka keep each .info beside + its core. + """ + found = _config_beside(bios_path) + dirs: list[Path] = [] + if found is not None: + cfg, app_dir = found + dirs.append(_retroarch_cfg_dir(cfg, "libretro_info_path", app_dir, "info") + or app_dir / "info") + dirs.extend(searched) + return list(dict.fromkeys(dirs)) + + +_INFO_FIRMWARE_RE = re.compile(r'^\s*firmware\d+_path\s*=\s*"?([^"\r\n]*?)"?\s*$') + + +def info_firmware(dirs: list[Path], core: str) -> list[str] | None: + """The firmware paths a core's .info declares, None without a .info. + + RetroArch reads firmware_path, relative to the system directory + (core_info.c), and so does this. + """ + for directory in dirs: + info = directory / f"{core}_libretro.info" + try: + text = info.read_text(encoding="utf-8", errors="replace") + except OSError: + continue + paths = (m.group(1).strip().replace("\\", "/") + for m in map(_INFO_FIRMWARE_RE.match, text.splitlines()) if m) + return list(dict.fromkeys(p for p in paths if p)) + return None + + +def known_core_names(manifest: dict) -> set[str]: + """Every core name a file list answers for: profiles and their other names.""" + names: set[str] = set() + for profile, aliases in (manifest.get("core_names") or {}).items(): + names.add(profile) + names.update(aliases) + for cores in (manifest.get("system_cores") or {}).values(): + names.update(cores) + for entry in [*manifest.get("files", []), *manifest.get("omitted_files", [])]: + for copy in entry_copies(entry): + names.update(copy.get("cores") or []) + return names + + +def unknown_cores(manifest: dict, names: list[str]) -> list[str]: + """The installed cores the file list has no profile for, in name order.""" + known = known_core_names(manifest) + return sorted(name for name in names if name not in known) + + +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.""" + try: + with os.scandir(folder): + return + except FileNotFoundError: + reason, why = "not_found", "does not exist" + except NotADirectoryError: + 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: + 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( + plat: str, bios_path: Path, manifest: dict, found: list[str], searched: list[Path], +) -> list[str]: + """What the installed cores the list has no profile for declare, each said. + + Such a core reads systems the list cannot name, and narrowing to the + installed cores dropped its BIOS without a word (issue 87, parallel_dc + before its profile). Its .info is what RetroArch itself checks, so the + files it declares are kept. A core without one is named. + """ + unknown = unknown_cores(manifest, found) + if not unknown: + return [] + dirs = info_dirs(plat, bios_path, searched) + dests: list[str] = [] + for core in unknown: + declared = info_firmware(dirs, core) + if declared is None: + message = (f"{core}: a core this list does not know, with no .info to read: " + "its files may be missing. Run without --installed-cores " + "to install every file.") + else: + message = (f"{core}: a core this list does not know, " + f"{_plural(len(declared), 'file')} its .info declares kept") + print(f" {message}") + EVENTS.emit("unknown_core", platform=plat, core=core, + info=declared is not None, dests=declared or [], message=message) + dests.extend(declared or []) + return dests + + +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 + none beside it, nothing names the cores folder: the run stopped on "no + known directory" with no way forward. + """ + where = (f"none in {', '.join(map(str, searched))}" if searched + else f"no retroarch.cfg was found for {bios_path} to name their folder") + command = _INVOCATION.command(plat, bios_path, without=("--installed-cores", "--cores-dir")) + 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 ", + " Or run it without --installed-cores to install every file.") + + # --- installer/network.py ---------------------------------------------------- def _read_limited(response: http.client.HTTPResponse, limit: int, label: str) -> bytes: @@ -8397,242 +8626,6 @@ def read_game(facts: GameFacts, system_id: str, system: SystemData, readers: set _read_game_headers(facts, system, wanted, packed) -# --- installer/refusal.py ---------------------------------------------------- - -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) - - -# --- installer/cores.py ------------------------------------------------------ - -# A libretro core as RetroArch loads it: _libretro.so|dll|dylib, and -# _libretro_android.so on Android. -_CORE_FILE_RE = re.compile( - r"^(?P.+?)_libretro(?:_android)?\.(?:so|dll|dylib)$", re.IGNORECASE -) -CORE_PLATFORMS = ("retroarch", "lakka", "retropie") -# Where these systems install cores whatever retroarch.cfg says: RetroPie -# gives each package its own folder, Lakka keeps the image's cores and the -# ones the online updater fetches apart. -_FIXED_CORE_DIRS = { - "retropie": (Path("/opt/retropie/libretrocores"),), - "lakka": (Path("/usr/lib/libretro"), Path("/storage/cores"), Path("/tmp/cores")), -} - - -def _config_beside(bios_path: Path) -> tuple[Path, Path] | None: - """The retroarch.cfg detection read for bios_path and the directory ':' - expands to, else a portable one beside the system directory.""" - found = _retroarch_config_for(bios_path) - if found is None and _is_file(bios_path.parent / "retroarch.cfg"): - found = (bios_path.parent / "retroarch.cfg", bios_path.parent) - return found - - -def core_dirs(plat: str, bios_path: Path) -> list[Path]: - """The directories the RetroArch writing to bios_path loads cores from. - - The config detection read for this system directory names them in - libretro_directory, read here when the run was given --dest, as the - interface's runs all are. Without one, a retroarch.cfg beside the system - directory is the portable layout. Unset, the setting is cores/ under - RetroArch's own directory. - """ - found = _config_beside(bios_path) - dirs: list[Path] = [] - if found is not None: - cfg, app_dir = found - dirs.append( - _retroarch_cfg_dir(cfg, "libretro_directory", app_dir, "cores") - or app_dir / "cores" - ) - dirs.extend(_FIXED_CORE_DIRS.get(plat, ())) - return list(dict.fromkeys(dirs)) - - -def installed_cores(dirs: list[Path]) -> list[str]: - """The cores present in these directories, by the name the buildbot uses. - - A folder inside is looked into once, which is how RetroPie installs - each package. An unreadable directory holds nothing that can be seen. - """ - names: set[str] = set() - for directory in dirs: - try: - children = list(directory.iterdir()) - except OSError: - continue - for child in children: - candidates = [child] - if child.is_dir(): - try: - candidates = list(child.iterdir()) - except OSError: - continue - for path in candidates: - match = _CORE_FILE_RE.match(path.name) - if match and path.is_file(): - names.add(match.group("name")) - return sorted(names) - - -def info_dirs(plat: str, bios_path: Path, searched: list[Path]) -> list[Path]: - """The directories RetroArch reads core .info files from. - - libretro_info_path in retroarch.cfg, info/ beside RetroArch by default, - then the cores folders: Linux builds and Lakka keep each .info beside - its core. - """ - found = _config_beside(bios_path) - dirs: list[Path] = [] - if found is not None: - cfg, app_dir = found - dirs.append(_retroarch_cfg_dir(cfg, "libretro_info_path", app_dir, "info") - or app_dir / "info") - dirs.extend(searched) - return list(dict.fromkeys(dirs)) - - -_INFO_FIRMWARE_RE = re.compile(r'^\s*firmware\d+_path\s*=\s*"?([^"\r\n]*?)"?\s*$') - - -def info_firmware(dirs: list[Path], core: str) -> list[str] | None: - """The firmware paths a core's .info declares, None without a .info. - - RetroArch reads firmware_path, relative to the system directory - (core_info.c), and so does this. - """ - for directory in dirs: - info = directory / f"{core}_libretro.info" - try: - text = info.read_text(encoding="utf-8", errors="replace") - except OSError: - continue - paths = (m.group(1).strip().replace("\\", "/") - for m in map(_INFO_FIRMWARE_RE.match, text.splitlines()) if m) - return list(dict.fromkeys(p for p in paths if p)) - return None - - -def known_core_names(manifest: dict) -> set[str]: - """Every core name a file list answers for: profiles and their other names.""" - names: set[str] = set() - for profile, aliases in (manifest.get("core_names") or {}).items(): - names.add(profile) - names.update(aliases) - for cores in (manifest.get("system_cores") or {}).values(): - names.update(cores) - for entry in [*manifest.get("files", []), *manifest.get("omitted_files", [])]: - for copy in entry_copies(entry): - names.update(copy.get("cores") or []) - return names - - -def unknown_cores(manifest: dict, names: list[str]) -> list[str]: - """The installed cores the file list has no profile for, in name order.""" - known = known_core_names(manifest) - return sorted(name for name in names if name not in known) - - -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.""" - try: - with os.scandir(folder): - return - except FileNotFoundError: - reason, why = "not_found", "does not exist" - except NotADirectoryError: - 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: - 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( - plat: str, bios_path: Path, manifest: dict, found: list[str], searched: list[Path], -) -> list[str]: - """What the installed cores the list has no profile for declare, each said. - - Such a core reads systems the list cannot name, and narrowing to the - installed cores dropped its BIOS without a word (issue 87, parallel_dc - before its profile). Its .info is what RetroArch itself checks, so the - files it declares are kept. A core without one is named. - """ - unknown = unknown_cores(manifest, found) - if not unknown: - return [] - dirs = info_dirs(plat, bios_path, searched) - dests: list[str] = [] - for core in unknown: - declared = info_firmware(dirs, core) - if declared is None: - message = (f"{core}: a core this list does not know, with no .info to read: " - "its files may be missing. Run without --installed-cores " - "to install every file.") - else: - message = (f"{core}: a core this list does not know, " - f"{_plural(len(declared), 'file')} its .info declares kept") - print(f" {message}") - EVENTS.emit("unknown_core", platform=plat, core=core, - info=declared is not None, dests=declared or [], message=message) - dests.extend(declared or []) - return dests - - -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 - none beside it, nothing names the cores folder: the run stopped on "no - known directory" with no way forward. - """ - where = (f"none in {', '.join(map(str, searched))}" if searched - else f"no retroarch.cfg was found for {bios_path} to name their folder") - command = _INVOCATION.command(plat, bios_path, without=("--installed-cores", "--cores-dir")) - 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 ", - " Or run it without --installed-cores to install every file.") - - # --- installer/lists.py ------------------------------------------------------ NETWORK_ADVICE = (" Check the connection, and HTTPS_PROXY if this network needs a " @@ -9082,14 +9075,13 @@ def _check_run_romm(run: _InstallRun) -> None: return # Applied or refused, never ignored. if not any(name == "romm" for name, _path in run.platforms): - print("Error: --romm-firmware applies to RomM, which this run does not " - "install for.", file=sys.stderr) - sys.exit(1) + raise Refusal("option", "not_applicable", "romm", + "Error: --romm-firmware applies to RomM, which this run does not " + "install for.") try: parse_romm_firmware(args.romm_firmware) except ValueError as exc: - print(f"Error: {exc}", file=sys.stderr) - sys.exit(1) + raise Refusal("option", "invalid", "romm", f"Error: {exc}") from None def _pass_romm_layout(run: _InstallRun, p: _PlatformPass) -> None: @@ -9098,8 +9090,7 @@ def _pass_romm_layout(run: _InstallRun, p: _PlatformPass) -> None: try: layout = romm_firmware_layout(bios_path, run.args.romm_firmware) except ValueError as exc: - print(f"Error: {exc}", file=sys.stderr) - sys.exit(1) + raise Refusal("option", "invalid", "romm", f"Error: {exc}") from None if layout is not None: p.files, library = romm_relayout(p.files, bios_path, *layout) if library != bios_path: @@ -21782,28 +21773,24 @@ def _check_free_space(bios_path: Path, needed: int, plat: str = "", code: int = free = shortfall[1] EVENTS.emit("no_space", platform=plat, folder=str(bios_path), bytes_needed=needed, bytes_free=free) - EVENTS.emit("error", stage="space", reason="drive_full", platform=plat, - message=f"Not enough space on the drive holding {bios_path}: " - f"{format_size(needed)} needed, {format_size(free)} free.") - print(f"\nNot enough space on the drive holding {bios_path}.", file=sys.stderr) - print(f" Needed: {format_size(needed)}. Free: {format_size(free)}.", - file=sys.stderr) + lines = [f"\nNot enough space on the drive holding {bios_path}.", + f" Needed: {format_size(needed)}. Free: {format_size(free)}."] if card: # Its system reads this card alone: another drive, with RetroArch's # list, was offered for an Onion card. - print(f" Free up {format_size(needed - free)} on the card, then run it again: " - "its system reads its BIOS files there only.", file=sys.stderr) - sys.exit(code) - if not plat: - print(f" Free up {format_size(needed - free)}, or use --dest to install " - "to another drive.", file=sys.stderr) - sys.exit(code) - # --dest alone used to mean RetroArch's list: the platform is named, so - # a Batocera install moved to a USB drive stays Batocera's. - print(f" Free up {format_size(needed - free)}, or install to another drive:\n" - f" {_INVOCATION.command(plat, '')}", - file=sys.stderr) - sys.exit(code) + lines.append(f" Free up {format_size(needed - free)} on the card, then run it " + "again: its system reads its BIOS files there only.") + elif not plat: + lines.append(f" Free up {format_size(needed - free)}, or use --dest to install " + "to another drive.") + else: + # --dest alone used to mean RetroArch's list: the platform is named, so + # a Batocera install moved to a USB drive stays Batocera's. + lines.append(f" Free up {format_size(needed - free)}, or install to another " + f"drive:\n {_INVOCATION.command(plat, '')}") + raise Refusal("space", "drive_full", plat, *lines, code=code, + message=f"Not enough space on the drive holding {bios_path}: " + f"{format_size(needed)} needed, {format_size(free)} free.") # --- installer/run_files.py -------------------------------------------------- @@ -21886,13 +21873,10 @@ def _found_files(args: argparse.Namespace, plat: str, *(f" {match['dest']} {match.get('sha1', '')}" for match in matches)], }.get(result) if lines is not None: - EVENTS.emit("error", stage="option", reason="unknown", platform=plat, - message=lines[0][len("Error: "):]) - for line in lines: - print(line, file=sys.stderr) # 4: the hash was read and the list holds no one file for it, neither # a failure (1) nor an option refused (2). - sys.exit(4) + raise Refusal("option", "unknown", plat, *lines, code=4, + message=lines[0][len("Error: "):]) for match in matches: print(f" {value} is {match['dest']}") return matches, [] @@ -21970,10 +21954,10 @@ def _pass_files(run: _InstallRun, plat_name: str, bios_path: Path) -> _PlatformP p = _PlatformPass(plat_name, bios_path, manifest) if run.args.source == "truth": if manifest.get("truth_files") is None: - print(f"Error: the {plat_name} file list does not say what the emulator " - "profiles prove is read, which --source truth needs.", file=sys.stderr) - print(_older_list_advice(plat_name), file=sys.stderr) - sys.exit(1) + raise Refusal("option", "not_recorded", plat_name, + f"Error: the {plat_name} file list does not say what the emulator " + "profiles prove is read, which --source truth needs.", + _older_list_advice(plat_name)) before = len(p.files) p.files, p.omitted_files = truth_lists(manifest, p.files, p.omitted_files) detail(f" What the emulator profiles prove is read: {before} to " @@ -22034,10 +22018,9 @@ def _pass_options(run: _InstallRun, p: _PlatformPass) -> bool: if args.no_game_data and not p.manifest.get("categorized"): # Without the field nothing is marked, and the run would # install the game data it was asked to leave out. - print(f"Error: the {plat_name} file list records no file category, " - "which --no-game-data needs.", file=sys.stderr) - print(_older_list_advice(plat_name), file=sys.stderr) - sys.exit(1) + raise Refusal("option", "not_recorded", plat_name, + f"Error: the {plat_name} file list records no file category, " + "which --no-game-data needs.", _older_list_advice(plat_name)) if args.declared_only: before = len(p.files) @@ -22046,9 +22029,7 @@ def _pass_options(run: _InstallRun, p: _PlatformPass) -> bool: "(--declared-only)") if args.list_targets: - targets = fetch_targets(plat_name) - if targets is None: - sys.exit(1) + targets = needed_targets(plat_name) if not targets: print(f" No targets available for {plat_name}") else: @@ -22102,13 +22083,23 @@ def _pass_target(run: _InstallRun, p: _PlatformPass) -> None: _pass_target_cores(run, p, target) +def needed_targets(plat: str) -> dict: + """The board list a run cannot go on without, its failure the run's refusal.""" + try: + return load_targets(plat) + except ListFailure as stopped: + # A list the run would carry on without stops this one all the same: + # it said why on stderr and ended with code 1, no error event sent. + problem = stopped.problem + raise Refusal("targets", problem.code, problem.plat, + *targets_failure_lines(problem), code=problem.fatal or 1) from None + + def _pass_target_cores(run: _InstallRun, p: _PlatformPass, target: str) -> None: """The files narrowed to the cores the board's list names.""" targets = run.target_lists.get(p.plat_name) if targets is None: - targets = fetch_targets(p.plat_name) - if targets is None: - sys.exit(1) + targets = needed_targets(p.plat_name) target_info = targets.get(target) if target_info is None: # Carrying on would install every file, which is the opposite @@ -22145,13 +22136,10 @@ def _pass_installed_cores(run: _InstallRun, p: _PlatformPass) -> None: if not args.installed_cores: return if "system_cores" not in manifest: - print( - f"Error: the {plat_name} file list does not say which cores " - "read which systems, which --installed-cores needs.", - file=sys.stderr, - ) - print(_older_list_advice(plat_name), file=sys.stderr) - sys.exit(1) + raise Refusal("option", "not_recorded", plat_name, + f"Error: the {plat_name} file list does not say which cores " + "read which systems, which --installed-cores needs.", + _older_list_advice(plat_name)) before = len(p.files) info_dests = _unprofiled_cores_firmware( plat_name, bios_path, manifest, found_cores, @@ -22409,10 +22397,10 @@ def _pass_narrow(run: _InstallRun, p: _PlatformPass) -> None: detail(f" Narrowed {before} to {len(p.files)} files") if args.one_per_slot: if not p.manifest.get("slot_fields"): - print(f"Error: the {plat_name} file list does not say which files a " - "slot holds, which --one-per-slot needs.", file=sys.stderr) - print(_older_list_advice(plat_name), file=sys.stderr) - sys.exit(1) + raise Refusal("option", "not_recorded", plat_name, + f"Error: the {plat_name} file list does not say which files a " + "slot holds, which --one-per-slot needs.", + _older_list_advice(plat_name)) before = len(p.files) p.files, p.omitted_files = one_per_slot(p.files, p.omitted_files, p.slot_reach) detail(f" One BIOS per console and region: {before} to {len(p.files)} files") @@ -22972,9 +22960,9 @@ def _start_install(args: argparse.Namespace, real_stdout: TextIO) -> _InstallRun if args.platform is None: spelled = pack_name_platforms(Path(os.path.expanduser(str(args.pack))).name) if len(spelled) != 1: - print("Error: name the platform the pack is for with --platform.", - file=sys.stderr) - sys.exit(2) + raise Refusal("pack", "no_platform", "", + "Error: name the platform the pack is for with --platform.", + code=2) args.platform = spelled[0] return _InstallRun(args, term, os_type, interactive, listing, packing) @@ -23014,9 +23002,6 @@ def _named_by_list_only(run: _InstallRun) -> NoReturn: else "the file list") message = (f"No supported platform detected: {display_name(args.platform)} was " f"not found here, and {source} does not say where it goes") - EVENTS.emit("error", stage="detect", reason="not_found", platform=args.platform, - message=message) - print(f" {message}.", file=sys.stderr) hint = Invocation() hint.os_type, hint.options = run.os_type, _INVOCATION.options example = _default_dest(run.os_type, args.platform) @@ -23024,10 +23009,11 @@ def _named_by_list_only(run: _InstallRun) -> NoReturn: # example stopped at a question. answered = "".join(f" {flag}" for flag, on in ( ("--yes", args.yes), ("--no-input", args.no_input)) if on) - print(" Name its folder with --dest, for example:\n " - + hint.command(args.platform, example if example is not None - else "") + answered, file=sys.stderr) - sys.exit(1) + raise Refusal("detect", "not_found", args.platform, f" {message}.", + " Name its folder with --dest, for example:\n " + + hint.command(args.platform, example if example is not None + else "") + answered, + message=message) def _named_setup_default(run: _InstallRun) -> list[tuple[str, Path]]: @@ -23039,42 +23025,32 @@ def _named_setup_default(run: _InstallRun) -> list[tuple[str, Path]]: if args.platform in PORTABLE_ONLY: # A portable emulator reads the folder beside its executable: # any default would be a folder it never opens. - EVENTS.emit("error", stage="detect", reason="not_found", platform=args.platform, - message=f"Platform '{args.platform}' not found. " - f"{PORTABLE_ONLY[args.platform]}") - print( + raise Refusal( + "detect", "not_found", args.platform, f" Platform '{args.platform}' not found. {PORTABLE_ONLY[args.platform]} " f"Name it with --dest, for example: --platform {args.platform} " f"--dest '{os.sep}Firmware'", - file=sys.stderr, - ) - sys.exit(1) + message=f"Platform '{args.platform}' not found. {PORTABLE_ONLY[args.platform]}") if args.platform in _SHARE_FOLDERS: # Its own folder exists on the Batocera machine alone, which # detection would have found: here /userdata/bios was taken, and # the run ended on "Cannot create" with no event saying why. message = (f"Platform '{args.platform}' not found here. " f"{share_words(args.platform)}") - EVENTS.emit("error", stage="detect", reason="not_found", platform=args.platform, - message=message) example = drive_example(run.os_type, "SHARE", "bios", args.platform) - print(f" {message} Name it with --dest, for example: --platform " - f"{args.platform} --dest {example}", file=sys.stderr) - sys.exit(1) + raise Refusal("detect", "not_found", args.platform, + f" {message} Name it with --dest, for example: --platform " + f"{args.platform} --dest {example}", message=message) default_dest = _default_dest(run.os_type, args.platform) if default_dest is None: where = ("where this user can look, and its default folder may not be " "the one it reads" if _default_set_aside(run.os_type, args.platform) else "and no folder on this system is one it reads") message = f"Platform '{args.platform}' not found {where}" - EVENTS.emit("error", stage="detect", reason="not_found", - platform=args.platform, message=message) - print( - f" {message}. Name it with --dest, for example: " - f"--platform {args.platform} --dest ", - file=sys.stderr, - ) - sys.exit(1) + raise Refusal("detect", "not_found", args.platform, + f" {message}. Name it with --dest, for example: " + f"--platform {args.platform} --dest ", + message=message) print( f" Platform '{args.platform}' not detected, " f"using default path: {default_dest}" @@ -23273,9 +23249,7 @@ def _check_run_target(run: _InstallRun) -> None: drop_recorded(args, plat, "--target", "the board list does not name it") if args.target: for plat_name, _bios_path in platforms: - targets = fetch_targets(plat_name) - if targets is None: - sys.exit(1) + targets = needed_targets(plat_name) run.target_lists[plat_name] = targets if args.target not in targets: _unknown_target(args.target, plat_name, targets, *( @@ -23299,12 +23273,9 @@ def _check_run_cores(run: _InstallRun) -> None: drop_recorded(args, plat_name, "--installed-cores", f"{plat_name} ships its cores with the system") elif args.installed_cores: - print( - f"Error: {plat_name} ships its cores with the system. " - f"--installed-cores applies to {', '.join(CORE_PLATFORMS)}", - file=sys.stderr, - ) - sys.exit(1) + raise Refusal("option", "not_applicable", plat_name, + f"Error: {plat_name} ships its cores with the system. " + f"--installed-cores applies to {', '.join(CORE_PLATFORMS)}") if args.installed_cores and not run.cores_found[(plat_name, bios_path)]: if by_record(args): drop_recorded(args, plat_name, "--installed-cores", "no core is installed") diff --git a/install.sh b/install.sh index 99ab4ec88..ecfa87a89 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="7eb5c3718dc892a8cc773493724757cd2de45793475e96082a09fbb535aae769" +DEFAULT_INSTALL_SHA256="13b42cf02602fe7cfee80ce9ed25544c6e8ff1c51feb0d62e4dc07e81eeaf951" # 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 735d50caa..f3dcebd1d 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": 1470376, - "sha256": "7eb5c3718dc892a8cc773493724757cd2de45793475e96082a09fbb535aae769", + "size": 1469751, + "sha256": "13b42cf02602fe7cfee80ce9ed25544c6e8ff1c51feb0d62e4dc07e81eeaf951", "executable": false }, { @@ -71,8 +71,8 @@ "muos": { "archive": { "dest": "ARCHIVE/RetroBIOS.muxapp", - "size": 1524001, - "sha256": "a6e6da27de83262e39da7e4b5128cfdfcf046ac3d054c9e878ab9be51f0929c5" + "size": 1523376, + "sha256": "6b2cc39e6a0e6df85c758c31a63c0d24e77a3a5894e95fac4f6047894306b092" }, "members": [ { @@ -92,8 +92,8 @@ { "name": "RetroBIOS/install.py", "repo_path": "install.py", - "size": 1470376, - "sha256": "7eb5c3718dc892a8cc773493724757cd2de45793475e96082a09fbb535aae769", + "size": 1469751, + "sha256": "13b42cf02602fe7cfee80ce9ed25544c6e8ff1c51feb0d62e4dc07e81eeaf951", "executable": false }, { @@ -166,8 +166,8 @@ { "dest": ".config/modules/retrobios/install.py", "repo_path": "install.py", - "size": 1470376, - "sha256": "7eb5c3718dc892a8cc773493724757cd2de45793475e96082a09fbb535aae769", + "size": 1469751, + "sha256": "13b42cf02602fe7cfee80ce9ed25544c6e8ff1c51feb0d62e4dc07e81eeaf951", "executable": false }, { diff --git a/installer/plan.py b/installer/plan.py index 0c228d9c9..9e5ce9978 100644 --- a/installer/plan.py +++ b/installer/plan.py @@ -1,7 +1,6 @@ """The plan shown before a download: what comes, its size and the space it needs.""" from __future__ import annotations -import sys from collections.abc import Collection from pathlib import Path from typing import TYPE_CHECKING @@ -15,6 +14,7 @@ from installer.outcome import EVERYTHING_IN_PLACE from installer.paths import shown_path from installer.plan_words import _sized from installer.platforms import OTHER_TITLE, entry_systems, system_title +from installer.refusal import Refusal from installer.space import space_shortfall from installer.tally import _bytes, parts_words, tally from installer.terminal import terminal_size @@ -249,25 +249,21 @@ def _check_free_space(bios_path: Path, needed: int, plat: str = "", code: int = free = shortfall[1] EVENTS.emit("no_space", platform=plat, folder=str(bios_path), bytes_needed=needed, bytes_free=free) - EVENTS.emit("error", stage="space", reason="drive_full", platform=plat, - message=f"Not enough space on the drive holding {bios_path}: " - f"{format_size(needed)} needed, {format_size(free)} free.") - print(f"\nNot enough space on the drive holding {bios_path}.", file=sys.stderr) - print(f" Needed: {format_size(needed)}. Free: {format_size(free)}.", - file=sys.stderr) + lines = [f"\nNot enough space on the drive holding {bios_path}.", + f" Needed: {format_size(needed)}. Free: {format_size(free)}."] if card: # Its system reads this card alone: another drive, with RetroArch's # list, was offered for an Onion card. - print(f" Free up {format_size(needed - free)} on the card, then run it again: " - "its system reads its BIOS files there only.", file=sys.stderr) - sys.exit(code) - if not plat: - print(f" Free up {format_size(needed - free)}, or use --dest to install " - "to another drive.", file=sys.stderr) - sys.exit(code) - # --dest alone used to mean RetroArch's list: the platform is named, so - # a Batocera install moved to a USB drive stays Batocera's. - print(f" Free up {format_size(needed - free)}, or install to another drive:\n" - f" {_INVOCATION.command(plat, '')}", - file=sys.stderr) - sys.exit(code) + lines.append(f" Free up {format_size(needed - free)} on the card, then run it " + "again: its system reads its BIOS files there only.") + elif not plat: + lines.append(f" Free up {format_size(needed - free)}, or use --dest to install " + "to another drive.") + else: + # --dest alone used to mean RetroArch's list: the platform is named, so + # a Batocera install moved to a USB drive stays Batocera's. + lines.append(f" Free up {format_size(needed - free)}, or install to another " + f"drive:\n {_INVOCATION.command(plat, '')}") + raise Refusal("space", "drive_full", plat, *lines, code=code, + message=f"Not enough space on the drive holding {bios_path}: " + f"{format_size(needed)} needed, {format_size(free)} free.") diff --git a/installer/platforms.py b/installer/platforms.py index a26bd21ea..b7eb3e725 100644 --- a/installer/platforms.py +++ b/installer/platforms.py @@ -2,13 +2,12 @@ from __future__ import annotations import re -import sys from pathlib import Path, PurePosixPath from typing import NoReturn from installer.embedded import _EMBEDDED_RULES, _NO_FOLDER -from installer.events import EVENTS from installer.manifest import OTHER_SYSTEMS +from installer.refusal import Refusal # The platforms that publish a core list per board, install/targets/ in the # repository: a test holds the two equal. Offline, a platform outside it @@ -197,14 +196,7 @@ def refuse_name(platform: str, *lines: str) -> NoReturn: 2, as for an option argparse refuses: 1 also means --check found files to fetch, and a script reading it reran the install on a typo forever. """ - message = " ".join(line.strip() for line in lines) - if message.startswith("Error: "): - message = message[len("Error: "):] - EVENTS.emit("error", stage="option", reason="unknown", platform=platform, - message=message) - for line in lines: - print(line, file=sys.stderr) - sys.exit(2) + raise Refusal("option", "unknown", platform, *lines, code=2) # Frontends and systems that keep no BIOS folder of their own: each diff --git a/installer/romm.py b/installer/romm.py index 881ac3074..4245eb530 100644 --- a/installer/romm.py +++ b/installer/romm.py @@ -1,12 +1,12 @@ """RomM: where it reads each platform's firmware, and the list laid out under its library.""" from __future__ import annotations -import sys from pathlib import Path from typing import TYPE_CHECKING from installer.console import detail from installer.host_fs import _is_dir +from installer.refusal import Refusal if TYPE_CHECKING: from installer.run_files import _PlatformPass @@ -133,14 +133,13 @@ def _check_run_romm(run: _InstallRun) -> None: return # Applied or refused, never ignored. if not any(name == "romm" for name, _path in run.platforms): - print("Error: --romm-firmware applies to RomM, which this run does not " - "install for.", file=sys.stderr) - sys.exit(1) + raise Refusal("option", "not_applicable", "romm", + "Error: --romm-firmware applies to RomM, which this run does not " + "install for.") try: parse_romm_firmware(args.romm_firmware) except ValueError as exc: - print(f"Error: {exc}", file=sys.stderr) - sys.exit(1) + raise Refusal("option", "invalid", "romm", f"Error: {exc}") from None def _pass_romm_layout(run: _InstallRun, p: _PlatformPass) -> None: @@ -149,8 +148,7 @@ def _pass_romm_layout(run: _InstallRun, p: _PlatformPass) -> None: try: layout = romm_firmware_layout(bios_path, run.args.romm_firmware) except ValueError as exc: - print(f"Error: {exc}", file=sys.stderr) - sys.exit(1) + raise Refusal("option", "invalid", "romm", f"Error: {exc}") from None if layout is not None: p.files, library = romm_relayout(p.files, bios_path, *layout) if library != bios_path: diff --git a/installer/run_files.py b/installer/run_files.py index 7acebf002..c70c26347 100644 --- a/installer/run_files.py +++ b/installer/run_files.py @@ -49,7 +49,7 @@ from installer.games import fallback_lines, read_games from installer.install_record import _RECORD_TAKEN, by_record, drop_recorded, record_menu_words from installer.invocation import _INVOCATION from installer.line_menu import MenuContext, _prompt_custom_selection -from installer.lists import fetch_manifest, fetch_targets, local_targets +from installer.lists import ListFailure, fetch_manifest, fetch_targets, load_targets, local_targets, targets_failure_lines from installer.manifest import GAME_DATA from installer.narrowing import ( _chosen, @@ -78,6 +78,7 @@ from installer.plan_words import ( unlisted_saves_words, ) from installer.platforms import PLATFORM_NAMES, display_name, system_title +from installer.refusal import Refusal from installer.tally import ( _bytes, _left_out_lines, @@ -174,13 +175,10 @@ def _found_files(args: argparse.Namespace, plat: str, *(f" {match['dest']} {match.get('sha1', '')}" for match in matches)], }.get(result) if lines is not None: - EVENTS.emit("error", stage="option", reason="unknown", platform=plat, - message=lines[0][len("Error: "):]) - for line in lines: - print(line, file=sys.stderr) # 4: the hash was read and the list holds no one file for it, neither # a failure (1) nor an option refused (2). - sys.exit(4) + raise Refusal("option", "unknown", plat, *lines, code=4, + message=lines[0][len("Error: "):]) for match in matches: print(f" {value} is {match['dest']}") return matches, [] @@ -258,10 +256,10 @@ def _pass_files(run: _InstallRun, plat_name: str, bios_path: Path) -> _PlatformP p = _PlatformPass(plat_name, bios_path, manifest) if run.args.source == "truth": if manifest.get("truth_files") is None: - print(f"Error: the {plat_name} file list does not say what the emulator " - "profiles prove is read, which --source truth needs.", file=sys.stderr) - print(_older_list_advice(plat_name), file=sys.stderr) - sys.exit(1) + raise Refusal("option", "not_recorded", plat_name, + f"Error: the {plat_name} file list does not say what the emulator " + "profiles prove is read, which --source truth needs.", + _older_list_advice(plat_name)) before = len(p.files) p.files, p.omitted_files = truth_lists(manifest, p.files, p.omitted_files) detail(f" What the emulator profiles prove is read: {before} to " @@ -322,10 +320,9 @@ def _pass_options(run: _InstallRun, p: _PlatformPass) -> bool: if args.no_game_data and not p.manifest.get("categorized"): # Without the field nothing is marked, and the run would # install the game data it was asked to leave out. - print(f"Error: the {plat_name} file list records no file category, " - "which --no-game-data needs.", file=sys.stderr) - print(_older_list_advice(plat_name), file=sys.stderr) - sys.exit(1) + raise Refusal("option", "not_recorded", plat_name, + f"Error: the {plat_name} file list records no file category, " + "which --no-game-data needs.", _older_list_advice(plat_name)) if args.declared_only: before = len(p.files) @@ -334,9 +331,7 @@ def _pass_options(run: _InstallRun, p: _PlatformPass) -> bool: "(--declared-only)") if args.list_targets: - targets = fetch_targets(plat_name) - if targets is None: - sys.exit(1) + targets = needed_targets(plat_name) if not targets: print(f" No targets available for {plat_name}") else: @@ -390,13 +385,23 @@ def _pass_target(run: _InstallRun, p: _PlatformPass) -> None: _pass_target_cores(run, p, target) +def needed_targets(plat: str) -> dict: + """The board list a run cannot go on without, its failure the run's refusal.""" + try: + return load_targets(plat) + except ListFailure as stopped: + # A list the run would carry on without stops this one all the same: + # it said why on stderr and ended with code 1, no error event sent. + problem = stopped.problem + raise Refusal("targets", problem.code, problem.plat, + *targets_failure_lines(problem), code=problem.fatal or 1) from None + + def _pass_target_cores(run: _InstallRun, p: _PlatformPass, target: str) -> None: """The files narrowed to the cores the board's list names.""" targets = run.target_lists.get(p.plat_name) if targets is None: - targets = fetch_targets(p.plat_name) - if targets is None: - sys.exit(1) + targets = needed_targets(p.plat_name) target_info = targets.get(target) if target_info is None: # Carrying on would install every file, which is the opposite @@ -433,13 +438,10 @@ def _pass_installed_cores(run: _InstallRun, p: _PlatformPass) -> None: if not args.installed_cores: return if "system_cores" not in manifest: - print( - f"Error: the {plat_name} file list does not say which cores " - "read which systems, which --installed-cores needs.", - file=sys.stderr, - ) - print(_older_list_advice(plat_name), file=sys.stderr) - sys.exit(1) + raise Refusal("option", "not_recorded", plat_name, + f"Error: the {plat_name} file list does not say which cores " + "read which systems, which --installed-cores needs.", + _older_list_advice(plat_name)) before = len(p.files) info_dests = _unprofiled_cores_firmware( plat_name, bios_path, manifest, found_cores, @@ -697,10 +699,10 @@ def _pass_narrow(run: _InstallRun, p: _PlatformPass) -> None: detail(f" Narrowed {before} to {len(p.files)} files") if args.one_per_slot: if not p.manifest.get("slot_fields"): - print(f"Error: the {plat_name} file list does not say which files a " - "slot holds, which --one-per-slot needs.", file=sys.stderr) - print(_older_list_advice(plat_name), file=sys.stderr) - sys.exit(1) + raise Refusal("option", "not_recorded", plat_name, + f"Error: the {plat_name} file list does not say which files a " + "slot holds, which --one-per-slot needs.", + _older_list_advice(plat_name)) before = len(p.files) p.files, p.omitted_files = one_per_slot(p.files, p.omitted_files, p.slot_reach) detail(f" One BIOS per console and region: {before} to {len(p.files)} files") diff --git a/installer/run_setups.py b/installer/run_setups.py index de28ab38b..9d62466a1 100644 --- a/installer/run_setups.py +++ b/installer/run_setups.py @@ -26,12 +26,13 @@ from installer.line_folder import ( ask_platform_folder, share_words, ) -from installer.lists import ListFailure, fetch_targets, load_targets +from installer.lists import ListFailure, load_targets from installer.offline import LOCAL from installer.pack import pack_path from installer.pack_source import pack_name_platforms from installer.platforms import AVAILABLE_PLATFORMS, _NO_BIOS_FOLDER, display_name, normalize_platform -from installer.run_files import _output_kind +from installer.refusal import Refusal +from installer.run_files import _output_kind, needed_targets from installer.safe_replace import KEPT from installer.setups import PORTABLE_ONLY, _default_dest, _line_setups, drive_example, found_setups from installer.standalone import _install_standalone_folders @@ -145,9 +146,9 @@ def _start_install(args: argparse.Namespace, real_stdout: TextIO) -> _InstallRun if args.platform is None: spelled = pack_name_platforms(Path(os.path.expanduser(str(args.pack))).name) if len(spelled) != 1: - print("Error: name the platform the pack is for with --platform.", - file=sys.stderr) - sys.exit(2) + raise Refusal("pack", "no_platform", "", + "Error: name the platform the pack is for with --platform.", + code=2) args.platform = spelled[0] return _InstallRun(args, term, os_type, interactive, listing, packing) @@ -187,9 +188,6 @@ def _named_by_list_only(run: _InstallRun) -> NoReturn: else "the file list") message = (f"No supported platform detected: {display_name(args.platform)} was " f"not found here, and {source} does not say where it goes") - EVENTS.emit("error", stage="detect", reason="not_found", platform=args.platform, - message=message) - print(f" {message}.", file=sys.stderr) hint = Invocation() hint.os_type, hint.options = run.os_type, _INVOCATION.options example = _default_dest(run.os_type, args.platform) @@ -197,10 +195,11 @@ def _named_by_list_only(run: _InstallRun) -> NoReturn: # example stopped at a question. answered = "".join(f" {flag}" for flag, on in ( ("--yes", args.yes), ("--no-input", args.no_input)) if on) - print(" Name its folder with --dest, for example:\n " - + hint.command(args.platform, example if example is not None - else "") + answered, file=sys.stderr) - sys.exit(1) + raise Refusal("detect", "not_found", args.platform, f" {message}.", + " Name its folder with --dest, for example:\n " + + hint.command(args.platform, example if example is not None + else "") + answered, + message=message) def _named_setup_default(run: _InstallRun) -> list[tuple[str, Path]]: @@ -212,42 +211,32 @@ def _named_setup_default(run: _InstallRun) -> list[tuple[str, Path]]: if args.platform in PORTABLE_ONLY: # A portable emulator reads the folder beside its executable: # any default would be a folder it never opens. - EVENTS.emit("error", stage="detect", reason="not_found", platform=args.platform, - message=f"Platform '{args.platform}' not found. " - f"{PORTABLE_ONLY[args.platform]}") - print( + raise Refusal( + "detect", "not_found", args.platform, f" Platform '{args.platform}' not found. {PORTABLE_ONLY[args.platform]} " f"Name it with --dest, for example: --platform {args.platform} " f"--dest '{os.sep}Firmware'", - file=sys.stderr, - ) - sys.exit(1) + message=f"Platform '{args.platform}' not found. {PORTABLE_ONLY[args.platform]}") if args.platform in _SHARE_FOLDERS: # Its own folder exists on the Batocera machine alone, which # detection would have found: here /userdata/bios was taken, and # the run ended on "Cannot create" with no event saying why. message = (f"Platform '{args.platform}' not found here. " f"{share_words(args.platform)}") - EVENTS.emit("error", stage="detect", reason="not_found", platform=args.platform, - message=message) example = drive_example(run.os_type, "SHARE", "bios", args.platform) - print(f" {message} Name it with --dest, for example: --platform " - f"{args.platform} --dest {example}", file=sys.stderr) - sys.exit(1) + raise Refusal("detect", "not_found", args.platform, + f" {message} Name it with --dest, for example: --platform " + f"{args.platform} --dest {example}", message=message) default_dest = _default_dest(run.os_type, args.platform) if default_dest is None: where = ("where this user can look, and its default folder may not be " "the one it reads" if _default_set_aside(run.os_type, args.platform) else "and no folder on this system is one it reads") message = f"Platform '{args.platform}' not found {where}" - EVENTS.emit("error", stage="detect", reason="not_found", - platform=args.platform, message=message) - print( - f" {message}. Name it with --dest, for example: " - f"--platform {args.platform} --dest ", - file=sys.stderr, - ) - sys.exit(1) + raise Refusal("detect", "not_found", args.platform, + f" {message}. Name it with --dest, for example: " + f"--platform {args.platform} --dest ", + message=message) print( f" Platform '{args.platform}' not detected, " f"using default path: {default_dest}" @@ -446,9 +435,7 @@ def _check_run_target(run: _InstallRun) -> None: drop_recorded(args, plat, "--target", "the board list does not name it") if args.target: for plat_name, _bios_path in platforms: - targets = fetch_targets(plat_name) - if targets is None: - sys.exit(1) + targets = needed_targets(plat_name) run.target_lists[plat_name] = targets if args.target not in targets: _unknown_target(args.target, plat_name, targets, *( @@ -472,12 +459,9 @@ def _check_run_cores(run: _InstallRun) -> None: drop_recorded(args, plat_name, "--installed-cores", f"{plat_name} ships its cores with the system") elif args.installed_cores: - print( - f"Error: {plat_name} ships its cores with the system. " - f"--installed-cores applies to {', '.join(CORE_PLATFORMS)}", - file=sys.stderr, - ) - sys.exit(1) + raise Refusal("option", "not_applicable", plat_name, + f"Error: {plat_name} ships its cores with the system. " + f"--installed-cores applies to {', '.join(CORE_PLATFORMS)}") if args.installed_cores and not run.cores_found[(plat_name, bios_path)]: if by_record(args): drop_recorded(args, plat_name, "--installed-cores", "no core is installed") diff --git a/tests/test_install.py b/tests/test_install.py index fd12bc025..2636ba09d 100644 --- a/tests/test_install.py +++ b/tests/test_install.py @@ -436,7 +436,7 @@ class TestFreeSpaceGuard(unittest.TestCase): code = 0 with contextlib.redirect_stderr(buf): try: - install._check_free_space(path or self.root, needed) + reported(install._check_free_space, path or self.root, needed) except SystemExit as exc: code = exc.code return buf.getvalue(), code @@ -460,7 +460,7 @@ class TestFreeSpaceGuard(unittest.TestCase): events = io.StringIO() with unittest.mock.patch.object(install.EVENTS, "stream", events), \ contextlib.redirect_stderr(io.StringIO()), self.assertRaises(SystemExit): - install._check_free_space(self.root, 5_000, "batocera") + reported(install._check_free_space, self.root, 5_000, "batocera") said = [json.loads(line) for line in events.getvalue().splitlines()] self.assertEqual(said[0], {"event": "no_space", "platform": "batocera", "folder": str(self.root), "bytes_needed": 5_000, @@ -5573,7 +5573,7 @@ class ATypoGetsTheClosestName(unittest.TestCase): platform" with no way forward.""" err = io.StringIO() with contextlib.redirect_stderr(err), self.assertRaises(SystemExit): - install.normalize_platform("TrimUI") + reported(install.normalize_platform, "TrimUI") self.assertNotIn("Unknown platform", err.getvalue()) self.assertIn("--platform retroarch --dest FOLDER", err.getvalue()) @@ -5585,7 +5585,7 @@ class ATypoGetsTheClosestName(unittest.TestCase): err = io.StringIO() with self.subTest(typed=typed), contextlib.redirect_stderr(err), \ self.assertRaises(SystemExit) as raised: - install.normalize_platform(typed) + reported(install.normalize_platform, typed) self.assertEqual(raised.exception.code, 2) self.assertIn(f"{said} has no BIOS folder of its own: run again without " "--platform", err.getvalue()) @@ -5593,7 +5593,7 @@ class ATypoGetsTheClosestName(unittest.TestCase): def test_a_system_name_is_suggested(self): err = io.StringIO() with contextlib.redirect_stderr(err), self.assertRaises(SystemExit): - install.normalize_platform("spruce") + reported(install.normalize_platform, "spruce") self.assertIn("Close matches: spruceOS.", err.getvalue()) # The distinct names --list-platforms prints: Batocera is both a # platform and a system it recognises. @@ -5606,7 +5606,7 @@ class ATypoGetsTheClosestName(unittest.TestCase): def test_a_platform_typo_is_answered_with_one_name(self): err = io.StringIO() with contextlib.redirect_stderr(err), self.assertRaises(SystemExit) as raised: - install.normalize_platform("batocra") + reported(install.normalize_platform, "batocra") self.assertEqual(raised.exception.code, 2) self.assertIn("Close matches: batocera.", err.getvalue()) self.assertNotIn("recalbox", err.getvalue()) @@ -5640,7 +5640,8 @@ class ATypoGetsTheClosestName(unittest.TestCase): def test_a_target_typo(self): err = io.StringIO() with contextlib.redirect_stderr(err), self.assertRaises(SystemExit): - install._unknown_target("swich", "retroarch", {"switch": {}, "desktop": {}}) + reported(install._unknown_target, "swich", "retroarch", + {"switch": {}, "desktop": {}}) self.assertIn("Close matches: switch.", err.getvalue()) self.assertIn("--list-targets", err.getvalue()) @@ -5751,7 +5752,7 @@ class HintsGiveTheUsersOwnCommandBack(unittest.TestCase): with unittest.mock.patch.object(install.shutil, "disk_usage", return_value=SimpleNamespace(free=1)), \ contextlib.redirect_stderr(err), self.assertRaises(SystemExit): - install._check_free_space(scratch_dir(self), 10, "batocera") + reported(install._check_free_space, scratch_dir(self), 10, "batocera") self.assertIn("--platform batocera --dest ", err.getvalue()) def test_the_one_liner_tells_the_installer_how_it_was_started(self): diff --git a/tests/test_install_cores.py b/tests/test_install_cores.py index 8c83b1c0a..fe9b5f5e2 100644 --- a/tests/test_install_cores.py +++ b/tests/test_install_cores.py @@ -579,7 +579,11 @@ class APlatformWithoutTargetsSaysSo(unittest.TestCase): def test_the_way_forward_is_named(self): with contextlib.redirect_stderr(io.StringIO()) as err, \ self.assertRaises(SystemExit): - install._unknown_target("switch", "misterfpga", {}) + try: + install._unknown_target("switch", "misterfpga", {}) + except install.Refusal as refusal: + refusal.report() + raise said = err.getvalue() self.assertIn("MiSTer FPGA has no hardware targets: run again without --target.", said) self.assertNotIn("unknown target", said) diff --git a/tests/test_install_tui.py b/tests/test_install_tui.py index 7ac68d4f0..47d7392fe 100644 --- a/tests/test_install_tui.py +++ b/tests/test_install_tui.py @@ -7949,7 +7949,7 @@ class _LineModeFindings(_CardFixtures): return_value=mock.Mock(free=10)), \ contextlib.redirect_stderr(io.StringIO()) as err, \ self.assertRaises(SystemExit): - install._check_free_space(self.root, 1000, "retroarch", card=True) + reported(install._check_free_space, self.root, 1000, "retroarch", card=True) said = err.getvalue() self.assertIn("on the card, then run it again", said) self.assertNotIn("--platform", said) diff --git a/wiki/installer.md b/wiki/installer.md index 6d19e9667..ef4ce1261 100644 --- a/wiki/installer.md +++ b/wiki/installer.md @@ -2225,7 +2225,7 @@ other schemas under `api/v1/schemas/`. | `start` | `schema`, `installer`, `mode` | First line. `schema` is 1, `installer` the identity `--version` prints, `mode` one of `install`, `check`, `dry-run`, `list` (also `--backups`), `remove` (`--remove`, `--delete-backup`), `restore`, `pack` (`--pack`, with `--dry-run` too) | | `unsearched` | `folder`, `reason`, `message` | Before `detect`, once for each folder the search for setups could not look in, this user being refused it or a read failing there (a failing card, a link that loops), or under WSL the Windows side when Windows did not answer (`folder` is then the drive mount, `/mnt`). What it would hold counts as absent, and the other places are still searched: `detect` then lists what they hold, and an empty `platforms` after an `unsearched` line means nothing was found where the installer could look. `reason` says why in words (`Permission denied`), `message` says it in a sentence | | `detect` | `os`, `os_name`, `platforms` | Once the platforms are known. `os_name` comes from `/etc/os-release`. `platforms` lists `{platform, name, bios_dir}`, and is empty when nothing supported was found | -| `error` | `stage`, `reason`, `platform`, `message` | The file list could not be read (`stage` is `manifest`): `reason` is `network`, `not_found` or `invalid`, `clock` when the server's certificate was refused and the system clock reads a date before the installer was written, `no_ca` when the machine holds no list of trusted certificates (`SSL_CERT_FILE` names one), `no_ssl` when this Python was built without its `ssl` module and cannot use HTTPS, or `offline` when `--offline` forbids the request. A `--manifest` file that cannot be read carries `reason` `unreadable`, and the standalone layout `--standalone` needs `unavailable`. A folder named with `--from` cannot be read (`stage` is `from`, `reason` `not_found`, `not_a_folder` for a file that is no ZIP, `unreadable`, or `system` for the root of the system, `/proc`, `/sys` or `/dev`). The BIOS folder sits under a folder this user cannot open (`stage` is `dest`, `reason` `unreadable`), or is a file or lies under one (`reason` `not_a_folder`), and the run ends with code 1 before anything is written. A platform, target, system, core or emulator named on the command line is unknown or cannot be used here (`stage` is `option`, `reason` `unknown`, `platform` the platform it was checked against or the name typed), refused before any download with code 2. The list does not record what `--system`, `--core`, `--region`, `--emulator` or `--standalone` reads (`stage` is `option`, `reason` `not_recorded`, code 1). `--installed-cores` finds no core (`stage` is `cores`, `reason` `none`), or its `--cores-dir` does not exist, is not a folder or cannot be read (`reason` `not_found`, `not_a_folder` or `unreadable`). The board list a run needs cannot be had (`stage` is `targets`, `reason` as for the file list, `http` for a refused answer). The `--from-pack` file is no pack, is a pack of another platform, or names no platform and none is given (`stage` is `pack`, `reason` `invalid`, `other_platform` or `no_platform`). The BIOS folder cannot be created (`stage` is `dest`, `reason` `not_writable`): a `summary` follows with what the run installed before it. Two systems are detected on one machine and no `--dest` names the folder, or a `--dest` given alone finds several here (`stage` is `detect`, `reason` `conflict`). The platform named with `--platform` is found nowhere and no folder can be assumed for it: a card system with no card named, a portable emulator, Batocera or Recalbox named on a computer (their folder is the `bios` folder of their SHARE drive), or no usual folder on this system or one set aside behind a folder this user cannot open (`stage` is `detect`, `reason` `not_found`). So is a platform named by a file list or a pack, in a run without questions where it is found nowhere here. A `--dest` refused as the card of the system named carries the same `stage` and `reason`: another system's card, a folder inside a card, a drive with none of the files its card always has, or a folder that does not exist. The drive holding the BIOS folder cannot hold the download (`stage` is `space`, `reason` `drive_full`), right after `no_space`, before any file of the setup is written. `message` says it in words, and is the only thing that tells these cases apart | +| `error` | `stage`, `reason`, `platform`, `message` | The file list could not be read (`stage` is `manifest`): `reason` is `network`, `not_found` or `invalid`, `clock` when the server's certificate was refused and the system clock reads a date before the installer was written, `no_ca` when the machine holds no list of trusted certificates (`SSL_CERT_FILE` names one), `no_ssl` when this Python was built without its `ssl` module and cannot use HTTPS, or `offline` when `--offline` forbids the request. A `--manifest` file that cannot be read carries `reason` `unreadable`, and the standalone layout `--standalone` needs `unavailable`. A folder named with `--from` cannot be read (`stage` is `from`, `reason` `not_found`, `not_a_folder` for a file that is no ZIP, `unreadable`, or `system` for the root of the system, `/proc`, `/sys` or `/dev`). The BIOS folder sits under a folder this user cannot open (`stage` is `dest`, `reason` `unreadable`), or is a file or lies under one (`reason` `not_a_folder`), and the run ends with code 1 before anything is written. A platform, target, system, core or emulator named on the command line is unknown or cannot be used here (`stage` is `option`, `reason` `unknown`, `platform` the platform it was checked against or the name typed), refused before any download with code 2, or a `--find` hash no one file of the list holds (code 4). An option that does not apply to the run, `--romm-firmware` without RomM or `--installed-cores` for a system that ships its cores (`stage` is `option`, `reason` `not_applicable`), or a `--romm-firmware` value it cannot read (`reason` `invalid`), code 1. The list does not record what `--system`, `--core`, `--region`, `--emulator`, `--standalone`, `--source truth`, `--no-game-data`, `--installed-cores` or `--one-per-slot` reads (`stage` is `option`, `reason` `not_recorded`, code 1). `--installed-cores` finds no core (`stage` is `cores`, `reason` `none`), or its `--cores-dir` does not exist, is not a folder or cannot be read (`reason` `not_found`, `not_a_folder` or `unreadable`). The board list a run needs cannot be had (`stage` is `targets`, `reason` as for the file list, `http` for a refused answer). The `--from-pack` file is no pack, is a pack of another platform, or names no platform and none is given (`stage` is `pack`, `reason` `invalid`, `other_platform` or `no_platform`), as for a `--pack` whose name gives no platform (code 2). The BIOS folder cannot be created (`stage` is `dest`, `reason` `not_writable`): a `summary` follows with what the run installed before it. Two systems are detected on one machine and no `--dest` names the folder, or a `--dest` given alone finds several here (`stage` is `detect`, `reason` `conflict`). The platform named with `--platform` is found nowhere and no folder can be assumed for it: a card system with no card named, a portable emulator, Batocera or Recalbox named on a computer (their folder is the `bios` folder of their SHARE drive), or no usual folder on this system or one set aside behind a folder this user cannot open (`stage` is `detect`, `reason` `not_found`). So is a platform named by a file list or a pack, in a run without questions where it is found nowhere here. A `--dest` refused as the card of the system named carries the same `stage` and `reason`: another system's card, a folder inside a card, a drive with none of the files its card always has, or a folder that does not exist. The drive holding the BIOS folder cannot hold the download (`stage` is `space`, `reason` `drive_full`), right after `no_space`, before any file of the setup is written. `message` says it in words, and is the only thing that tells these cases apart | | `no_space` | `platform`, `folder`, `bytes_needed`, `bytes_free` | Right before the `error` of `stage` `space`: the BIOS folder, the bytes the run writes there and the bytes free on its drive. `platform` is empty for a standalone build's folder | | `scanned` | `folder`, `files`, `truncated`, `other_drives` | Each folder named with `--from`, once read and before `detect`. `files` counts the files found, `truncated` is true when the search stopped at 200,000 of them, and `other_drives` lists the folders below it on another drive, which were not entered | | `version` | `platform`, `list_version`, `installed_version`, `message` | Before `choices`, when the system here runs another version than the one the list was built for: `list_version` is the list's, `installed_version` the one the system's version file states, and `message` says it and what it means. Not written when either version is unknown. The run goes on |