From d7f7d9a63fc3a93a8d57eddb4aa58224989481af Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Mon, 23 Nov 2026 21:43:37 +0100 Subject: [PATCH] refactor: share copy plan and failure causes Standalone copies: copy_sources is the one reading of a copy entry. The platform pass copies only list entries the run verified in place, never a disk scan, and --check and --dry-run report the emulator folders. Failures: failure_causes classifies each failed file once. A failures event before the summary carries the cause, and the full screen gives the remedies line mode gives, with no substring test. --- install.ps1 | 2 +- install.py | 516 ++++++++++++++++++----------- install.sh | 2 +- install/launchers/index.json | 16 +- installer/datadirs.py | 2 +- installer/download.py | 3 +- installer/events.py | 7 + installer/failure_causes.py | 172 ++++++++++ installer/outcome.py | 146 ++------ installer/run.py | 35 +- installer/run_files.py | 2 + installer/standalone.py | 146 ++++---- installer/tui_outcome.py | 51 ++- installer/tui_receive.py | 2 + installer/tui_state.py | 3 + schemas/install-events.schema.json | 23 ++ tests/test_e2e.py | 1 + tests/test_install.py | 79 ++++- tests/test_install_offline.py | 5 +- tests/test_install_tui.py | 43 ++- wiki/architecture.md | 2 +- wiki/installer.md | 7 +- 22 files changed, 853 insertions(+), 412 deletions(-) create mode 100644 installer/failure_causes.py diff --git a/install.ps1 b/install.ps1 index a2d111d25..7e04d2fed 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 = "d965c45c0fd7aa15d3376e06467644e6762f87bbc1f8f6d3e61891020bcfe9d3" + $defaultInstallSha256 = "8ae0de0e8e1601fcbc27db4f90670ca8f26b9f6c7a73f26012a0df6d8ebdc3c6" # 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 ceaa54b8d..e9fc06f33 100644 --- a/install.py +++ b/install.py @@ -1585,6 +1585,13 @@ EVENT_KEYS: dict[str, tuple[str, ...]] = { # out, empty without it. kept: [{"folder", "files", "bytes"}], the files # in place the run moved aside before replacing them (under --dry-run, # would move), one per backup folder, empty when none. + # Right before a summary whose failed is not empty: failed is the same + # files, each [{"dest", "reason", "kind", "url"}], kind its cause + # (offline, network, http, not_writable, drive_full, read_only, + # not_kept, not_in_pack or other) and url the address a server refused + # (http), "" otherwise. A kind of its own, since schema 1 never adds a + # key to summary: a screen gives the remedies line mode gives. + "failures": ("failed",), "summary": ("mode", "installed", "up_to_date", "pending", "failed", "skipped", "left_out", "kept", "interrupted"), # --add-app, or yes to its question, after the summary: the RetroBIOS @@ -11568,6 +11575,167 @@ def pack_lacks_words(count: int, total: int) -> str: f"{name}: {'it' if count == 1 else 'they'} cannot be installed from it.") +# --- installer/failure_causes.py --------------------------------------------- + +class OfflineReason(str): + """A file not fetched because the run was told to make no request.""" + + +class NetworkReason(str): + """A failure the connection caused: cut, timed out, refused by a server + or a proxy. The summary names the network instead of the folder.""" + + url = "" + + +class HttpReason(str): + """A file the server answered for with an error of its own (HTTP 404): + the summary names the address, where "HTTP 404" alone told the user + neither what failed nor that running again changes nothing.""" + + url = "" + + +# The causes a failure event names (the failures event's kind), each with +# the remedy failure_remedies gives it. other: a cause with no remedy of +# its own, the reason words saying it. +FAILURE_KINDS = ("offline", "network", "http", "not_writable", "drive_full", "read_only", + "not_kept", "not_in_pack", "other") + + +class Failure(NamedTuple): + """One failed file: where, the reason in words, its cause (FAILURE_KINDS) + and the address it was asked at, for a server's refusal.""" + + dest: str + reason: str + kind: str + url: str = "" + + +def failure_kind(reason: str) -> str: + """The cause of a failure, from the type the run gave its reason or the + words that name it.""" + if isinstance(reason, OfflineReason): + return "offline" + if isinstance(reason, HttpReason): + return "http" + if isinstance(reason, NetworkReason): + return "network" + words = str(reason) + if words == NOT_WRITABLE: + return "not_writable" + if words == DRIVE_FULL: + return "drive_full" + if words == READ_ONLY: + return "read_only" + if words.startswith(NOT_KEPT): + return "not_kept" + if words == NOT_IN_PACK: + return "not_in_pack" + return "other" + + +def failure_records(failures: Iterable[tuple[str, str]]) -> list[Failure]: + """The run's failures, each with its cause.""" + return [Failure(dest, str(reason), failure_kind(reason), getattr(reason, "url", "")) + for dest, reason in failures] + + +def failure_events(failures: Iterable[tuple[str, str]]) -> list[dict]: + """The failures event's items: what a screen needs to give the same remedies.""" + return [record._asdict() for record in failure_records(failures)] + + +def event_records(items: Iterable[dict]) -> list[Failure]: + """The failures event's items read back.""" + return [Failure(str(item.get("dest", "")), str(item.get("reason", "")), + str(item.get("kind", "other")), str(item.get("url", ""))) + for item in items] + + +def split_offline(records: list[Failure]) -> tuple[list[Failure], list[Failure]]: + """(failed, offline): a file --offline left out is missing, never failed.""" + return ([record for record in records if record.kind != "offline"], + [record for record in records if record.kind == "offline"]) + + +def _http_failure_lines(records: list[Failure]) -> list[str]: + """The address the first refused file was asked at, and what chose it: + a mirror named with RETROBIOS_BASE_URL that holds the lists and not yet + the files, or a list out of step with the files it names.""" + refused = [record for record in records if record.kind == "http"] + if not refused: + return [] + more = f" (and {_plural(len(refused) - 1, 'other file')})" if len(refused) > 1 else "" + lines = [f" The server answered {refused[0].reason} for {refused[0].url}{more}."] + if active_remote().overridden: + return [*lines, OVERRIDE_LINE] + return lines + [" The file list names files the server does not hold, and running " + "again changes nothing until the two match.", + f" More help: {TROUBLESHOOTING_PAGE}"] + + +NETWORK_FAILURE_ADVICE = ( + " The transfers were cut or refused on the way: check the connection, and " + "HTTPS_PROXY if this network needs a proxy.\n" + f" More help: {TROUBLESHOOTING_PAGE}") + + +def failure_remedies(records: list[Failure], locations: str) -> list[str]: + """What to do about each cause but a folder this user cannot write, + whose remedy each interface words with its own commands. locations + names the folders the run wrote to.""" + kinds = {record.kind for record in records} + advice: list[str] = [] + if "drive_full" in kinds: + advice.append(f" The drive holding {locations} is full: free up space, or " + "install to another drive with --dest, then run again.") + if "read_only" in kinds: + advice.append(" Files marked read-only are in the way: clear that attribute " + "(or delete them), then run again.") + advice += _http_failure_lines(records) + if "network" in kinds: + advice.append(NETWORK_FAILURE_ADVICE) + if active_remote().overridden: + # A mirror that is down read as this machine's connection. + advice.append(OVERRIDE_LINE) + if "not_kept" in kinds: + # The same run fails the same way: "retry only those" sent a phone + # user round the loop with nothing changed. + advice.append(" The files in place were left as they were, as no backup folder could " + "be made for them. Move them out of the folder, then run again to " + "install the new ones.") + return advice + + +def retry_words(records: list[Failure]) -> str: + """What to do when every failure is a file the pack does not hold: a + second run fails them the same way, and "run it again to retry only + those" sent people round. "" otherwise.""" + lacking = [record for record in records if record.kind == "not_in_pack"] + if not lacking or len(lacking) != len( + [record for record in records if record.kind != "not_kept"]): + return "" + name = LOCAL.pack.name if LOCAL.pack is not None else "The pack" + return (f"{name} does not hold {'it' if len(lacking) == 1 else 'them'}: a newer pack, " + "or a run without --from-pack, installs " + f"{'it' if len(lacking) == 1 else 'them'}.") + + +def retry_helps(records: list[Failure]) -> bool: + """Whether running again can install what failed: not when every file + failed for want of a backup folder or of space, which a second run + meets the same way.""" + return not all(record.kind in ("not_kept", "drive_full") for record in records) + + +def connection_only(records: list[Failure]) -> bool: + """Whether every file failed on the way, the folder never the problem.""" + return bool(records) and all(record.kind in ("offline", "network", "http") + for record in records) + + # --- installer/tally.py ------------------------------------------------------ def _bytes(files: list[dict]) -> int: @@ -14281,6 +14449,9 @@ class TuiState: self.network: int = 0 self.finished: list = [] self.summary: dict | None = None + # The failed files with their causes, from the failures event the + # summary follows. + self.failures: list[dict] = [] self.code: int | None = None self.stopping: bool = False self.tail: list = [] @@ -16243,41 +16414,6 @@ def _write_advice(path: Path, assumed: bool, plat: str = "", "or choose another folder with --dest.") -class OfflineReason(str): - """A file not fetched because the run was told to make no request.""" - - -class NetworkReason(str): - """A failure the connection caused: cut, timed out, refused by a server - or a proxy. The summary names the network instead of the folder.""" - - url = "" - - -class HttpReason(str): - """A file the server answered for with an error of its own (HTTP 404): - the summary names the address, where "HTTP 404" alone told the user - neither what failed nor that running again changes nothing.""" - - url = "" - - -def _http_failure_lines(failures: list[tuple[str, str]]) -> list[str]: - """The address the first refused file was asked at, and what chose it: - a mirror named with RETROBIOS_BASE_URL that holds the lists and not yet - the files, or a list out of step with the files it names.""" - refused = [reason for _dest, reason in failures if isinstance(reason, HttpReason)] - if not refused: - return [] - more = f" (and {_plural(len(refused) - 1, 'other file')})" if len(refused) > 1 else "" - lines = [f" The server answered {refused[0]} for {refused[0].url}{more}."] - if active_remote().overridden: - return [*lines, OVERRIDE_LINE] - return lines + [" The file list names files the server does not hold, and running " - "again changes nothing until the two match.", - f" More help: {TROUBLESHOOTING_PAGE}"] - - def _transfer_failure(exc: BaseException) -> bool: """Whether a download error came from the connection, not the disk.""" # urlopen raises URLError for the name lookup, the connection and TLS. @@ -16295,12 +16431,6 @@ def _transfer_failure(exc: BaseException) -> bool: ) -NETWORK_FAILURE_ADVICE = ( - " The transfers were cut or refused on the way: check the connection, and " - "HTTPS_PROXY if this network needs a proxy.\n" - f" More help: {TROUBLESHOOTING_PAGE}") - - def _status_print(term: Terminal | None) -> Callable[..., None]: """print, with the status words of what it prints in their roles when term paints (Terminal.status).""" @@ -16322,7 +16452,7 @@ class _Ending(NamedTuple): errors: int omitted: int offline: int - failures: list[tuple[str, str]] | None + failures: list[Failure] sources: str kept: list[str] advice: list[str] @@ -16336,58 +16466,40 @@ class _Ending(NamedTuple): missing: Tally | None -def _say_failures(say: Callable[..., None], failures: list[tuple[str, str]] | None) -> None: +def _say_failures(say: Callable[..., None], failures: list[Failure]) -> None: """The failed files the progress has not named, one cause said once.""" - reasons = {reason for _dest, reason in failures or []} + reasons = {record.reason for record in failures} # A failure the progress already named on its FAILED line is not named # again: line mode listed each one twice. - unsaid = [failure for failure in failures or [] if failure[0] not in SAID_FAILED] + unsaid = [record for record in failures if record.dest not in SAID_FAILED] if failures and len(failures) > 1 and len(reasons) == 1 and reasons != {""}: # One cause, said once: a read-only folder listed ten of its files # and "... and 266 more" above the advice that fixes them all. - said = f", first {unsaid[0][0]}" if unsaid else "" + said = f", first {unsaid[0].dest}" if unsaid else "" say(f" failed: {_plural(len(failures), 'file')} ({reasons.pop()}){said}") else: - for dest, reason in unsaid[:10]: + for dest, reason, _kind, _url in unsaid[:10]: say(f" failed: {dest}" + (f" ({reason})" if reason else "")) if len(unsaid) > 10: say(f" ... and {len(unsaid) - 10} more") def _failure_advice( - paths: list[Path], failures: list[tuple[str, str]], assumed: set[Path] | None, + paths: list[Path], failures: list[Failure], assumed: set[Path] | None, platform_of: dict[Path, str] | None, ) -> list[str]: """What to do about the causes of the failed files, one line each.""" - refused = any(reason == NOT_WRITABLE for dest, reason in failures - if not Path(dest).is_absolute()) + refused = any(record.kind == "not_writable" for record in failures + if not Path(record.dest).is_absolute()) advice = [ _write_advice(path, path in (assumed or set()), (platform_of or {}).get(path, "")) for path in paths ] if refused else [] advice += [_write_advice(folder, False) for folder in sorted({ - Path(dest).parent for dest, reason in failures - if Path(dest).is_absolute() and reason == NOT_WRITABLE + Path(record.dest).parent for record in failures + if Path(record.dest).is_absolute() and record.kind == "not_writable" })] - if any(reason == DRIVE_FULL for _dest, reason in failures): - advice.append(f" The drive holding {_locations(paths)} is full: free up space, or " - "install to another drive with --dest, then run again.") - if any(reason == READ_ONLY for _dest, reason in failures): - advice.append(" Files marked read-only are in the way: clear that attribute " - "(or delete them), then run again.") - advice += _http_failure_lines(failures) - if any(isinstance(reason, NetworkReason) for _dest, reason in failures): - advice.append(NETWORK_FAILURE_ADVICE) - if active_remote().overridden: - # A mirror that is down read as this machine's connection. - advice.append(OVERRIDE_LINE) - if any(str(reason).startswith(NOT_KEPT) for _dest, reason in failures): - # The same run fails the same way: "retry only those" sent a phone - # user round the loop with nothing changed. - advice.append(" The files in place were left as they were, as no backup folder could " - "be made for them. Move them out of the folder, then run again to " - "install the new ones.") - return advice + return advice + failure_remedies(failures, _locations(paths)) def _kept_and_unplaced(omitted_entries: list[dict], notes: list[str] | None, @@ -16464,19 +16576,18 @@ def _end_nothing_installed(end: _Ending) -> NoReturn: """End a run whose every file failed.""" say, paths, failures = end.say, end.paths, end.failures say(f"\nNothing was installed. {_plural(end.errors, 'file')} failed.") - if failures and all(isinstance(r, (NetworkReason, HttpReason, OfflineReason)) - for _d, r in failures): + if connection_only(failures): # The folder was never the problem: naming it as the place being # written to sent people looking at their disk. say(f"BIOS folder: {_locations(paths)}") - elif _retry_words(failures): + elif retry_words(failures): # Nothing was written: every file is one the pack lacks. say(f"BIOS folder: {_locations(paths)}") else: say(f"BIOS folder that was being written to: {_locations(paths)}") for line in end.kept + end.advice: say(line) - say(_retry_words(failures) or "Run the same command again once that is resolved. " + say(retry_words(failures) or "Run the same command again once that is resolved. " "Files already installed are kept.") for line in end.same_lines: say(line) @@ -16497,11 +16608,10 @@ def _end_with_errors(end: _Ending) -> NoReturn: say(f"BIOS folder: {_locations(end.paths)}") for line in end.kept + end.advice: say(line) - retry = _retry_words(failures) + retry = retry_words(failures) if retry: say(retry) - elif not all(str(reason).startswith(NOT_KEPT) or reason == DRIVE_FULL - for _dest, reason in failures or []): + elif retry_helps(failures): say("Run the same command again to retry only those.") for line in end.same_lines: say(line) @@ -16620,17 +16730,15 @@ def _report_outcome( # A file --offline left out is not a failure, whether the run asked or # not: without questions it was "14698 files failed", and "Run the same # command again to retry only those", which cannot fetch them. - left = [failure for failure in failures or [] if isinstance(failure[1], OfflineReason)] + records, left = split_offline(failure_records(failures or [])) if left: - failures = [failure for failure in failures or [] - if not isinstance(failure[1], OfflineReason)] errors = max(0, errors - len(left)) offline += len(left) if transferred and seconds > 0 and OUTPUT.verbose: verb = "copied from the pack" if LOCAL.pack is not None else "downloaded" say(f"\n{format_size(transferred)} {verb} in " f"{format_duration(seconds)} ({format_size(int(transferred / seconds))}/s).") - _say_failures(say, failures) + _say_failures(say, records) if declined and not downloaded and not errors and not interrupted and not offline: say(f"\nNothing installed: {_plural(declined, 'file')} not downloaded, as answered.") if up_to_date: @@ -16648,9 +16756,9 @@ def _report_outcome( # A standalone copy fails by absolute path, in an emulator's folder # rather than the BIOS folder: that folder is where the write went. - elsewhere = sorted({Path(dest).parent for dest, _reason in failures or [] - if Path(dest).is_absolute()}) - advice = _failure_advice(paths, failures or [], d.assumed, d.platform_of) + elsewhere = sorted({Path(record.dest).parent for record in records + if Path(record.dest).is_absolute()}) + advice = _failure_advice(paths, records, d.assumed, d.platform_of) paths = paths + [folder for folder in elsewhere if folder not in paths] # The kinds installed, on every end that installed some, under where @@ -16659,7 +16767,7 @@ def _report_outcome( if d.kinds and d.kinds[0].files and downloaded and OUTPUT.verbose else "") end = _Ending( say=say, paths=paths, downloaded=downloaded, up_to_date=up_to_date, errors=errors, - omitted=omitted, offline=offline, failures=failures, sources=d.sources, kept=kept, + omitted=omitted, offline=offline, failures=records, sources=d.sources, kept=kept, advice=advice, same_lines=same_lines, installed_kinds=installed_kinds, omitted_entries=d.omitted_entries or [], unplaced=unplaced, platform_of=d.platform_of or {}, hints=d.hints or [], same_choice=same_choice, @@ -16711,20 +16819,6 @@ def _offline_remedy(folders: list[str] | None = None, named: bool = False) -> st f"again with a pack (--from-pack) or {offline_undo()}.") -def _retry_words(failures: list | None) -> str: - """What to do when every failure is a file the pack does not hold: a - second run fails them the same way, and "run it again to retry only - those" sent people round. "" otherwise.""" - lacking = [dest for dest, reason in failures or [] if str(reason) == NOT_IN_PACK] - if not lacking or len(lacking) != len([ - dest for dest, reason in failures or [] if not str(reason).startswith(NOT_KEPT)]): - return "" - name = LOCAL.pack.name if LOCAL.pack is not None else "The pack" - return (f"{name} does not hold {'it' if len(lacking) == 1 else 'them'}: a newer pack, " - "or a run without --from-pack, installs " - f"{'it' if len(lacking) == 1 else 'them'}.") - - def _check_fetch_line(fetch: int, beside: str, lacking: int = 0, wrong: bool = False) -> str: """What --check says a run without it does with the files not in place: offline, those it cannot fetch are said so, not "run it to fetch them". @@ -16749,11 +16843,6 @@ def _check_fetch_line(fetch: int, beside: str, lacking: int = 0, wrong: bool = F f"beside {beside}." if OUTPUT.verbose or wrong else "")) -def _offline_failure(reason: str) -> bool: - """Whether a failure a run reported is a file --offline left out.""" - return OFFLINE_WORDS in reason or "makes no network request" in reason - - # The definitions in a few words, for a help with no room for the sentences. _SHORT_DEFINITIONS = ( ("Game data:", "Game data: what a game reads, of no use to other cores."), @@ -22210,6 +22299,8 @@ class _PlatformPass: self.record_files: list[dict] = [] self.to_download: list[dict] = [] self.up_to_date: list[dict] = [] + # The entries this run put in place, each checked as it landed. + self.landed: list[dict] = [] self.mismatched: list[dict] = [] self.data_states: list[tuple[dict, tuple[Path, dict[str, dict], int]]] = [] self.trees_missing = 0 @@ -22873,40 +22964,56 @@ def standalone_folders_here( STANDALONE_SOURCES = ("emudeck", "retroarch") +def copy_sources(manifest: dict) -> list[tuple[dict, list[tuple[dict, str]]]]: + """Each standalone copy entry of the manifest, with the entries of its + file list it carries and the name each takes in the emulator folder. + + The one reading of a copy entry: a pattern matches the names the list + gives, never whatever lies in the BIOS folder (a user's own + scph9999.bin went to DuckStation). `source` is where this list puts the + file that `file` names as the registry does for every platform: read + there, it was missing wherever the pack places it elsewhere. + """ + from fnmatch import fnmatch + + files = manifest.get("files", []) + by_dest = {entry["dest"]: entry for entry in files} + carried: list[tuple[dict, list[tuple[dict, str]]]] = [] + for copy in manifest.get("standalone_copies", []): + if "note" in copy: + continue + if "pattern" in copy: + sources = [entry for entry in files + if fnmatch(PurePosixPath(entry["dest"]).name, copy["pattern"])] + else: + held = by_dest.get(copy.get("source") or copy["file"]) + sources = [held] if held else [] + # `as`: the name the emulator reads, when it is not the + # platform's (melonDS's dsisd.bin, xemu's eeprom.bin). + carried.append((copy, [(entry, copy.get("as") or PurePosixPath(entry["dest"]).name) + for entry in sources])) + return carried + + def standalone_plan( manifests: list[dict], os_type: str, extra_dirs: dict[str, Path] | None = None, ) -> list[tuple[Path, list[dict]]]: """What each emulator folder found here receives, by its own file name. - The standalone copies of the manifests, read as do_standalone_copies - reads them, but taken from the file lists rather than from a platform - tree already installed: an ES-DE user with DuckStation and PCSX2 and no - RetroArch had no tree to copy from. The first list that holds a name for - a folder serves it. + The standalone copies of the manifests (copy_sources), each entry named + as the emulator reads it. A run with no platform fetches them from the + lists: an ES-DE user with DuckStation and PCSX2 and no RetroArch had no + tree to copy from. The first list that holds a name for a folder + serves it. """ - from fnmatch import fnmatch - plan: dict[Path, dict[str, dict]] = {} for manifest in manifests: - files = manifest.get("files", []) - by_dest = {entry["dest"]: entry for entry in files} - for copy in manifest.get("standalone_copies", []): - if "note" in copy: - continue - if "pattern" in copy: - sources = [entry for entry in files - if fnmatch(PurePosixPath(entry["dest"]).name, copy["pattern"])] - else: - held = by_dest.get(copy.get("source") or copy["file"]) - sources = [held] if held else [] + for copy, sources in copy_sources(manifest): for folder in _copy_targets(copy, os_type, extra_dirs): if not sources or not _is_dir(folder): continue chosen = plan.setdefault(folder, {}) - for entry in sources: - # `as`: the name the emulator reads, when it is not the - # platform's (melonDS's dsisd.bin, xemu's eeprom.bin). - name = copy.get("as") or PurePosixPath(entry["dest"]).name + for entry, name in sources: chosen.setdefault(name, {**entry, "dest": name}) return [(folder, list(entries.values())) for folder, entries in plan.items() if entries] @@ -22926,6 +23033,25 @@ def _check_standalone_folder(to_download: list[dict], mismatched: list[dict], print(f" {EVERYTHING_IN_PLACE}") +def preview_standalone(plan: list[tuple[Path, list[dict]]], args: argparse.Namespace, + term: Terminal) -> int: + """--check or --dry-run over the emulator folders of a standalone plan: + what each holds and lacks, or what a run would write. The count of the + files not in place.""" + pending = 0 + for folder, entries in plan: + print(f"\n{folder}:") + to_download, _up_to_date, mismatched = check_local(entries, folder, jobs=args.jobs) + to_download.extend(mismatched) + if args.check: + _check_standalone_folder(to_download, mismatched, args.verbose) + else: + _print_plan(to_download, folder, term, kept=plan_kept(mismatched, folder), + verbose=args.verbose) + pending += len(to_download) + return pending + + def _install_standalone_folders( args: argparse.Namespace, os_type: str, term: Terminal, interactive: bool, ) -> bool: @@ -22952,8 +23078,13 @@ def _install_standalone_folders( "\nInstall the BIOS files these emulators read into their folders? [Y/n] " ): return False + if args.check or args.dry_run: + pending = preview_standalone(plan, args, term) + if args.check and pending: + print("\n" + _check_fetch_line(pending, "its folder")) + sys.exit(3) + return True downloaded = up_to_date_count = errors = 0 - pending = 0 failures: list[tuple[str, str]] = [] transferred, seconds = 0, 0.0 interrupted = False @@ -22962,14 +23093,6 @@ def _install_standalone_folders( to_download, up_to_date, mismatched = check_local(entries, folder, jobs=args.jobs) to_download.extend(mismatched) up_to_date_count += len(up_to_date) - if args.check: - _check_standalone_folder(to_download, mismatched, args.verbose) - pending += len(to_download) - continue - if args.dry_run: - _print_plan(to_download, folder, term, kept=plan_kept(mismatched, folder), - verbose=args.verbose) - continue if not to_download: print(f" {EVERYTHING_IN_PLACE}") continue @@ -22987,13 +23110,6 @@ def _install_standalone_folders( seconds += progress.elapsed() if interrupted: break - if args.check: - if pending: - print("\n" + _check_fetch_line(pending, "its folder")) - sys.exit(3) - return True - if args.dry_run: - return True _report_outcome( [folder for folder, _entries in plan], downloaded, up_to_date_count, errors, 0, interrupted, @@ -23015,25 +23131,6 @@ def _print_standalone_note(entry: dict, os_type: str) -> None: break -def _standalone_sources(entry: dict, bios_path: Path) -> list[Path]: - """The files of the BIOS folder a standalone copy entry copies.""" - from fnmatch import fnmatch - - if "pattern" in entry: - # A kept file is never a source, when the backup had to go - # inside the BIOS folder. - return [ - f for f in bios_path.rglob("*") - if fnmatch(f.name, entry["pattern"]) and f.is_file() - and BACKUP_DIR not in f.relative_to(bios_path).parts - ] - # `source` is where this platform's manifest put the file, and `file` - # names it as the registry does for every platform, and laid out - # that way it was missing wherever the pack places it elsewhere. - src = _destination_path(bios_path, entry.get("source") or entry["file"]) - return [src] if _exists(src) else [] - - def _copy_standalone_file(src: Path, dest: Path, resolved_dir: Path, failures: list[tuple[str, str]] | None) -> bool: """Copy one file into an emulator folder, False when it was refused.""" @@ -23074,14 +23171,16 @@ def do_standalone_copies( manifest: dict, bios_path: Path, os_type: str, extra_dirs: dict[str, Path] | None = None, failures: list[tuple[str, str]] | None = None, + verified: list[dict] | None = None, ) -> tuple[int, int, int]: """Copy BIOS files to standalone emulator directories. - Supports: - - file: single file copy - - pattern: glob match (e.g. "scph*.bin") - - note: informational message when detect path exists - - WSL fallback to linux targets + Each copy entry carries what copy_sources names, the entries of the + file list, read in bios_path: verified holds the entries this run found + or put there with their hashes, and no other is copied. Without it, + every entry of the list present in bios_path. A note entry prints its + message when its emulator is found here, and WSL falls back to the + Linux folders. extra_dirs maps the emulator id of an entry to a root that replaces the default per-OS locations, for setups such as LaunchBox that keep their @@ -23098,18 +23197,22 @@ def do_standalone_copies( copies = manifest.get("standalone_copies", []) if not copies: return 0, 0, 0 + carried = {id(copy): sources for copy, sources in copy_sources(manifest)} + held = None if verified is None else {entry["dest"] for entry in verified} copied = 0 skipped = 0 failed = 0 for entry in copies: - # Note entries: print message if emulator detected if "note" in entry: _print_standalone_note(entry, os_type) continue - sources = _standalone_sources(entry, bios_path) + sources = [(src, name) for src, name in ( + (_destination_path(bios_path, item["dest"]), name) + for item, name in carried[id(entry)] + if held is None or item["dest"] in held) if _exists(src)] if not sources: continue @@ -23126,8 +23229,8 @@ def do_standalone_copies( skipped += len(sources) continue resolved_dir = target_dir.resolve() - for src in sources: - dest = target_dir / (entry.get("as") or src.name) + for src, name in sources: + dest = target_dir / name if _copy_standalone_file(src, dest, resolved_dir, failures): copied += 1 else: @@ -23902,6 +24005,8 @@ def _pass_make_folder(run: _InstallRun, p: _PlatformPass, written: int) -> bool: # and no summary, what was installed before it unsaid. EVENTS.emit("error", stage="dest", reason="not_writable", platform=plat_name, message=f"{bios_path} cannot be created: {exc.strerror}") + if run.failures: + EVENTS.emit("failures", failed=failure_events(run.failures)) EVENTS.emit( "summary", mode=_event_mode(args), installed=run.total_downloaded, up_to_date=run.total_up_to_date, pending=run.files_pending + len(p.to_download), @@ -23946,6 +24051,7 @@ def _pass_fetch(run: _InstallRun, p: _PlatformPass, dl_size: int, created: bool) # counted them, over the files that landed: matched by the end # of a failed path, a.bin was dropped when x/a.bin failed. run.landed.extend(progress.landed) + p.landed += progress.landed p.record_files += [record_file(entry, "copy" if id(entry) in p.copies else "pack" if LOCAL.pack is not None else "download") for entry in progress.landed] @@ -24109,8 +24215,11 @@ def _pass_standalone(run: _InstallRun, p: _PlatformPass) -> None: print("\nStandalone emulators:") lb_root = launchbox_root(os_type) extra_dirs = launchbox_bios_dirs(lb_root) if lb_root else None + # The files this run checked in place or put there, never others + # the folder holds. copied, skipped, copy_failed = do_standalone_copies( - manifest, p.bios_path, os_type, extra_dirs, run.failures + manifest, p.bios_path, os_type, extra_dirs, run.failures, + p.up_to_date + p.landed, ) if copied or skipped or copy_failed: print( @@ -24133,6 +24242,25 @@ def _pass_standalone(run: _InstallRun, p: _PlatformPass) -> None: "they read into them.") +def _pass_standalone_preview(run: _InstallRun, p: _PlatformPass) -> None: + """--check or --dry-run with --standalone-copies: the emulator folders + found here, what each holds and lacks or would receive, as a run with + no platform says them.""" + if not (p.manifest.get("standalone_copies") and run.args.standalone_copies): + return + lb_root = launchbox_root(run.os_type) + plan = standalone_plan([{**p.manifest, "files": p.files}], run.os_type, + launchbox_bios_dirs(lb_root) if lb_root else None) + if not plan: + return + print("\nStandalone emulators:") + pending = preview_standalone(plan, run.args, run.term) + if run.args.check: + run.check_pending += pending + else: + run.files_pending += pending + + def _apply_setup_files(run: _InstallRun, p: _PlatformPass) -> bool: """The setup's files packed, checked, planned or installed. True when the run stops there.""" @@ -24147,9 +24275,11 @@ def _apply_setup_files(run: _InstallRun, p: _PlatformPass) -> bool: _pass_check_existing(run, p) if args.check: _pass_check_report(run, p) + _pass_standalone_preview(run, p) return False if args.dry_run: _pass_dry_run(run, p) + _pass_standalone_preview(run, p) return False if p.to_download: @@ -24195,6 +24325,8 @@ def _finish_install(run: _InstallRun, real_stdout: TextIO) -> None: # The matches are the answer: nothing was installed. sys.exit(4 if getattr(args, "find_failed", False) else 0) if not run.listing: + if run.failures: + EVENTS.emit("failures", failed=failure_events(run.failures)) EVENTS.emit( "summary", mode=_event_mode(args), installed=run.total_downloaded, up_to_date=run.total_verified if args.check or args.dry_run else run.total_up_to_date, @@ -27530,8 +27662,8 @@ class _OutcomeCounts(NamedTuple): """What an install run reported, as its result counts it.""" summary: dict installed: int - failed: list - offline_failed: list + failed: list[Failure] + offline_failed: list[Failure] left: int up_to_date: int total: int @@ -27544,12 +27676,15 @@ def _outcome_counts(state: TuiState) -> _OutcomeCounts: # Killed by the second Ctrl-C, the child wrote no summary: what it # reported finished is what is installed. installed = summary.get("installed", sum(1 for _dest, ok, _why in state.finished if ok)) - failed = summary.get("failed") or [] + # Each with its cause, from the failures event the summary follows: + # without it, the cause its words name. + records = (event_records(state.failures) if summary.get("failed") and state.failures + else failure_records((failure["dest"], failure["reason"]) + for failure in summary.get("failed") or [])) # Left out by --offline: missing, never failed, as line mode says it. # The engine counts them in pending and no longer in failed (a file was # both): pending holds the real failures too, which are taken out. - offline_failed = [failure for failure in failed if _offline_failure(failure["reason"])] - failed = [failure for failure in failed if not _offline_failure(failure["reason"])] + failed, offline_failed = split_offline(records) left = len(offline_failed) + (max(0, summary.get("pending", 0) - len(failed)) if tui_offline_only(state) and not offline_failed else 0) up_to_date = summary.get("up_to_date", 0) @@ -27613,7 +27748,7 @@ def _outcome_counted(state: TuiState, counts: _OutcomeCounts, title: str, installed, failed, left = counts.installed, counts.failed, counts.left lines = [head] ok_dests = {dest for dest, good, _why in state.finished if good} - missing = ([failure["dest"] for failure in counts.offline_failed] + missing = ([failure.dest for failure in counts.offline_failed] or [event["dest"] for event in state.files if event["dest"] not in ok_dests][:left]) if left else [] # A wrong copy left in place is no missing file: --check counts it apart, @@ -27689,12 +27824,12 @@ def _outcome_placed(state: TuiState, counts: _OutcomeCounts, title: str) -> list return lines -def _failure_lines(failed: list) -> list[str]: +def _failure_lines(failed: list[Failure]) -> list[str]: """Each file that failed with its reason, a reason shared by many said once.""" lines: list[str] = [] causes: dict[str, list[str]] = {} for failure in failed: - causes.setdefault(failure["reason"], []).append(failure["dest"]) + causes.setdefault(failure.reason, []).append(failure.dest) shown = 0 for reason, dests in causes.items(): if len(dests) > 3: @@ -27711,14 +27846,21 @@ def _failure_lines(failed: list) -> list[str]: return lines -def _retry_lines(failed: list) -> list[str]: +def _remedy_lines(state: TuiState, failed: list[Failure]) -> list[str]: + """What to do about each cause, the words line mode gives: the screen + ended a mirror's 404 or a proxy's refusal on "Run it again".""" + where = shown_path(str(_plan_folder(state, state.dest))) if state.dest else "the folder" + return [line.strip() for advice in failure_remedies(failed, where) + for line in advice.split("\n")] + + +def _retry_lines(failed: list[Failure]) -> list[str]: # What a rerun does, as line mode and the first install page say # it: the screen never did. - pairs = [(failure["dest"], failure["reason"]) for failure in failed] - retry = _retry_words(pairs) + retry = retry_words(failed) if retry: return [retry] - if not all(str(reason).startswith(NOT_KEPT) for _dest, reason in pairs): + if retry_helps(failed): return ["Run it again to retry only those."] return [] @@ -27737,8 +27879,7 @@ def _outcome_unfinished(state: TuiState, counts: _OutcomeCounts, title: str) -> lines.append(_detail(f"{_plural(expected - landed, 'data file')} not installed" + (f": not in {LOCAL.pack.name}." if LOCAL.pack is not None else "."))) - if state.dest is not None and any(failure["reason"] == NOT_WRITABLE - for failure in failed): + if state.dest is not None and any(failure.kind == "not_writable" for failure in failed): # The plan's own advice: the result offered nothing after 22 files # failed on a read-only card. lines += _commands(state, write_remedy(state.dest, state.platform, tui_hint(state), @@ -27796,6 +27937,7 @@ def tui_outcome(state: TuiState) -> tuple[str, list[str]]: lines = _outcome_counted(state, counts, title, head) lines += _outcome_placed(state, counts, title) lines += _failure_lines(counts.failed) + lines += _remedy_lines(state, counts.failed) if title == "Finished with errors": lines += _retry_lines(counts.failed) lines += _outcome_unfinished(state, counts, title) @@ -31080,6 +31222,8 @@ def _take_install_event(state: TuiState, kind: str | None, event: dict) -> None: state.progress = event if kind == "downloaded": state.finished.append((event["dest"], event["ok"], event["reason"])) + elif kind == "failures": + state.failures = event["failed"] elif kind == "summary": state.summary = event diff --git a/install.sh b/install.sh index c2930fe5a..47f26092b 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="d965c45c0fd7aa15d3376e06467644e6762f87bbc1f8f6d3e61891020bcfe9d3" +DEFAULT_INSTALL_SHA256="8ae0de0e8e1601fcbc27db4f90670ca8f26b9f6c7a73f26012a0df6d8ebdc3c6" # 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 05e6f2498..1876bd22b 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": 1481970, - "sha256": "d965c45c0fd7aa15d3376e06467644e6762f87bbc1f8f6d3e61891020bcfe9d3", + "size": 1486791, + "sha256": "8ae0de0e8e1601fcbc27db4f90670ca8f26b9f6c7a73f26012a0df6d8ebdc3c6", "executable": false }, { @@ -71,8 +71,8 @@ "muos": { "archive": { "dest": "ARCHIVE/RetroBIOS.muxapp", - "size": 1535595, - "sha256": "34f95a5204ff52f432713a227b21443764803b340e4edde4c8ac3a1659f554eb" + "size": 1540416, + "sha256": "165edd616959944935627c4a4079ea70f4f73450c940b6dc003246b7ce709c7c" }, "members": [ { @@ -92,8 +92,8 @@ { "name": "RetroBIOS/install.py", "repo_path": "install.py", - "size": 1481970, - "sha256": "d965c45c0fd7aa15d3376e06467644e6762f87bbc1f8f6d3e61891020bcfe9d3", + "size": 1486791, + "sha256": "8ae0de0e8e1601fcbc27db4f90670ca8f26b9f6c7a73f26012a0df6d8ebdc3c6", "executable": false }, { @@ -166,8 +166,8 @@ { "dest": ".config/modules/retrobios/install.py", "repo_path": "install.py", - "size": 1481970, - "sha256": "d965c45c0fd7aa15d3376e06467644e6762f87bbc1f8f6d3e61891020bcfe9d3", + "size": 1486791, + "sha256": "8ae0de0e8e1601fcbc27db4f90670ca8f26b9f6c7a73f26012a0df6d8ebdc3c6", "executable": false }, { diff --git a/installer/datadirs.py b/installer/datadirs.py index 6a29fbe77..b70695d2f 100644 --- a/installer/datadirs.py +++ b/installer/datadirs.py @@ -32,7 +32,7 @@ from installer.local_check import _read_digests from installer.manifest import OTHER_SYSTEMS from installer.network import _retry_after_failure, _retry_delay from installer.offline import LOCAL, _Offline, _network_allowed, _offline_only -from installer.outcome import OfflineReason +from installer.failure_causes import OfflineReason from installer.paths import _destination_path from installer.platforms import entry_systems from installer.remote import MAX_DATA_ARCHIVE_SIZE, MAX_DOWNLOAD_SIZE, MAX_RETRIES diff --git a/installer/download.py b/installer/download.py index 085d33227..538af5438 100644 --- a/installer/download.py +++ b/installer/download.py @@ -38,7 +38,8 @@ from installer.invocation import offline_requested from installer.local_check import _digest_file, _digest_handle, expected_hashes, unreachable_words from installer.network import _retry_after_failure, _server_delay, network_words from installer.offline import LOCAL, offline_words -from installer.outcome import HttpReason, NetworkReason, OfflineReason, _transfer_failure +from installer.failure_causes import HttpReason, NetworkReason, OfflineReason +from installer.outcome import _transfer_failure from installer.pack_source import NOT_IN_PACK, _extract_from_pack from installer.paths import _entry_path, _entry_place from installer.remote import MAX_DOWNLOAD_SIZE, MAX_RETRIES, RELEASE_URL, RESUME_FROM_SIZE, active_remote diff --git a/installer/events.py b/installer/events.py index 7eea16bc9..a045e486e 100644 --- a/installer/events.py +++ b/installer/events.py @@ -162,6 +162,13 @@ EVENT_KEYS: dict[str, tuple[str, ...]] = { # out, empty without it. kept: [{"folder", "files", "bytes"}], the files # in place the run moved aside before replacing them (under --dry-run, # would move), one per backup folder, empty when none. + # Right before a summary whose failed is not empty: failed is the same + # files, each [{"dest", "reason", "kind", "url"}], kind its cause + # (offline, network, http, not_writable, drive_full, read_only, + # not_kept, not_in_pack or other) and url the address a server refused + # (http), "" otherwise. A kind of its own, since schema 1 never adds a + # key to summary: a screen gives the remedies line mode gives. + "failures": ("failed",), "summary": ("mode", "installed", "up_to_date", "pending", "failed", "skipped", "left_out", "kept", "interrupted"), # --add-app, or yes to its question, after the summary: the RetroBIOS diff --git a/installer/failure_causes.py b/installer/failure_causes.py new file mode 100644 index 000000000..0867b778c --- /dev/null +++ b/installer/failure_causes.py @@ -0,0 +1,172 @@ +"""The cause of each failed file and the remedy it calls for, said alike in line mode and on the screen.""" +from __future__ import annotations + +from collections.abc import Iterable +from typing import NamedTuple + +from installer.host_fs import DRIVE_FULL, NOT_WRITABLE, READ_ONLY +from installer.network import OVERRIDE_LINE +from installer.offline import LOCAL +from installer.pack_source import NOT_IN_PACK +from installer.remote import TROUBLESHOOTING_PAGE, active_remote +from installer.safe_replace import NOT_KEPT +from installer.text import _plural + + +class OfflineReason(str): + """A file not fetched because the run was told to make no request.""" + + +class NetworkReason(str): + """A failure the connection caused: cut, timed out, refused by a server + or a proxy. The summary names the network instead of the folder.""" + + url = "" + + +class HttpReason(str): + """A file the server answered for with an error of its own (HTTP 404): + the summary names the address, where "HTTP 404" alone told the user + neither what failed nor that running again changes nothing.""" + + url = "" + + +# The causes a failure event names (the failures event's kind), each with +# the remedy failure_remedies gives it. other: a cause with no remedy of +# its own, the reason words saying it. +FAILURE_KINDS = ("offline", "network", "http", "not_writable", "drive_full", "read_only", + "not_kept", "not_in_pack", "other") + + +class Failure(NamedTuple): + """One failed file: where, the reason in words, its cause (FAILURE_KINDS) + and the address it was asked at, for a server's refusal.""" + + dest: str + reason: str + kind: str + url: str = "" + + +def failure_kind(reason: str) -> str: + """The cause of a failure, from the type the run gave its reason or the + words that name it.""" + if isinstance(reason, OfflineReason): + return "offline" + if isinstance(reason, HttpReason): + return "http" + if isinstance(reason, NetworkReason): + return "network" + words = str(reason) + if words == NOT_WRITABLE: + return "not_writable" + if words == DRIVE_FULL: + return "drive_full" + if words == READ_ONLY: + return "read_only" + if words.startswith(NOT_KEPT): + return "not_kept" + if words == NOT_IN_PACK: + return "not_in_pack" + return "other" + + +def failure_records(failures: Iterable[tuple[str, str]]) -> list[Failure]: + """The run's failures, each with its cause.""" + return [Failure(dest, str(reason), failure_kind(reason), getattr(reason, "url", "")) + for dest, reason in failures] + + +def failure_events(failures: Iterable[tuple[str, str]]) -> list[dict]: + """The failures event's items: what a screen needs to give the same remedies.""" + return [record._asdict() for record in failure_records(failures)] + + +def event_records(items: Iterable[dict]) -> list[Failure]: + """The failures event's items read back.""" + return [Failure(str(item.get("dest", "")), str(item.get("reason", "")), + str(item.get("kind", "other")), str(item.get("url", ""))) + for item in items] + + +def split_offline(records: list[Failure]) -> tuple[list[Failure], list[Failure]]: + """(failed, offline): a file --offline left out is missing, never failed.""" + return ([record for record in records if record.kind != "offline"], + [record for record in records if record.kind == "offline"]) + + +def _http_failure_lines(records: list[Failure]) -> list[str]: + """The address the first refused file was asked at, and what chose it: + a mirror named with RETROBIOS_BASE_URL that holds the lists and not yet + the files, or a list out of step with the files it names.""" + refused = [record for record in records if record.kind == "http"] + if not refused: + return [] + more = f" (and {_plural(len(refused) - 1, 'other file')})" if len(refused) > 1 else "" + lines = [f" The server answered {refused[0].reason} for {refused[0].url}{more}."] + if active_remote().overridden: + return [*lines, OVERRIDE_LINE] + return lines + [" The file list names files the server does not hold, and running " + "again changes nothing until the two match.", + f" More help: {TROUBLESHOOTING_PAGE}"] + + +NETWORK_FAILURE_ADVICE = ( + " The transfers were cut or refused on the way: check the connection, and " + "HTTPS_PROXY if this network needs a proxy.\n" + f" More help: {TROUBLESHOOTING_PAGE}") + + +def failure_remedies(records: list[Failure], locations: str) -> list[str]: + """What to do about each cause but a folder this user cannot write, + whose remedy each interface words with its own commands. locations + names the folders the run wrote to.""" + kinds = {record.kind for record in records} + advice: list[str] = [] + if "drive_full" in kinds: + advice.append(f" The drive holding {locations} is full: free up space, or " + "install to another drive with --dest, then run again.") + if "read_only" in kinds: + advice.append(" Files marked read-only are in the way: clear that attribute " + "(or delete them), then run again.") + advice += _http_failure_lines(records) + if "network" in kinds: + advice.append(NETWORK_FAILURE_ADVICE) + if active_remote().overridden: + # A mirror that is down read as this machine's connection. + advice.append(OVERRIDE_LINE) + if "not_kept" in kinds: + # The same run fails the same way: "retry only those" sent a phone + # user round the loop with nothing changed. + advice.append(" The files in place were left as they were, as no backup folder could " + "be made for them. Move them out of the folder, then run again to " + "install the new ones.") + return advice + + +def retry_words(records: list[Failure]) -> str: + """What to do when every failure is a file the pack does not hold: a + second run fails them the same way, and "run it again to retry only + those" sent people round. "" otherwise.""" + lacking = [record for record in records if record.kind == "not_in_pack"] + if not lacking or len(lacking) != len( + [record for record in records if record.kind != "not_kept"]): + return "" + name = LOCAL.pack.name if LOCAL.pack is not None else "The pack" + return (f"{name} does not hold {'it' if len(lacking) == 1 else 'them'}: a newer pack, " + "or a run without --from-pack, installs " + f"{'it' if len(lacking) == 1 else 'them'}.") + + +def retry_helps(records: list[Failure]) -> bool: + """Whether running again can install what failed: not when every file + failed for want of a backup folder or of space, which a second run + meets the same way.""" + return not all(record.kind in ("not_kept", "drive_full") for record in records) + + +def connection_only(records: list[Failure]) -> bool: + """Whether every file failed on the way, the folder never the problem.""" + return bool(records) and all(record.kind in ("offline", "network", "http") + for record in records) diff --git a/installer/outcome.py b/installer/outcome.py index e5a413717..2f98c2c92 100644 --- a/installer/outcome.py +++ b/installer/outcome.py @@ -15,16 +15,22 @@ from installer.cards import _mounted_cards from installer.console import OUTPUT, SAID_FAILED from installer.destination import on_its_card from installer.detect_os import detected_os -from installer.host_fs import DRIVE_FULL, NOT_WRITABLE, READ_ONLY, _held +from installer.failure_causes import ( + Failure, + connection_only, + failure_records, + failure_remedies, + retry_helps, + retry_words, + split_offline, +) +from installer.host_fs import _held from installer.invocation import _INVOCATION -from installer.network import OVERRIDE_LINE -from installer.offline import LOCAL, OFFLINE_WORDS, _offline_only, offline_named, offline_undo -from installer.pack_source import NOT_IN_PACK +from installer.offline import LOCAL, _offline_only, offline_named, offline_undo from installer.paths import shown_path from installer.platforms import display_name -from installer.remote import TROUBLESHOOTING_PAGE, active_remote from installer.romm import ROMM_SCAN_WORDS -from installer.safe_replace import BACKUP_DIR, KEPT, NOT_KEPT, _kept_lines +from installer.safe_replace import BACKUP_DIR, KEPT, _kept_lines from installer.tally import _omission_lines, installed_words, needed_absent_words from installer.text import _plural, agree, format_duration, format_size, screen_text @@ -144,41 +150,6 @@ def _write_advice(path: Path, assumed: bool, plat: str = "", "or choose another folder with --dest.") -class OfflineReason(str): - """A file not fetched because the run was told to make no request.""" - - -class NetworkReason(str): - """A failure the connection caused: cut, timed out, refused by a server - or a proxy. The summary names the network instead of the folder.""" - - url = "" - - -class HttpReason(str): - """A file the server answered for with an error of its own (HTTP 404): - the summary names the address, where "HTTP 404" alone told the user - neither what failed nor that running again changes nothing.""" - - url = "" - - -def _http_failure_lines(failures: list[tuple[str, str]]) -> list[str]: - """The address the first refused file was asked at, and what chose it: - a mirror named with RETROBIOS_BASE_URL that holds the lists and not yet - the files, or a list out of step with the files it names.""" - refused = [reason for _dest, reason in failures if isinstance(reason, HttpReason)] - if not refused: - return [] - more = f" (and {_plural(len(refused) - 1, 'other file')})" if len(refused) > 1 else "" - lines = [f" The server answered {refused[0]} for {refused[0].url}{more}."] - if active_remote().overridden: - return [*lines, OVERRIDE_LINE] - return lines + [" The file list names files the server does not hold, and running " - "again changes nothing until the two match.", - f" More help: {TROUBLESHOOTING_PAGE}"] - - def _transfer_failure(exc: BaseException) -> bool: """Whether a download error came from the connection, not the disk.""" # urlopen raises URLError for the name lookup, the connection and TLS. @@ -196,12 +167,6 @@ def _transfer_failure(exc: BaseException) -> bool: ) -NETWORK_FAILURE_ADVICE = ( - " The transfers were cut or refused on the way: check the connection, and " - "HTTPS_PROXY if this network needs a proxy.\n" - f" More help: {TROUBLESHOOTING_PAGE}") - - def _status_print(term: Terminal | None) -> Callable[..., None]: """print, with the status words of what it prints in their roles when term paints (Terminal.status).""" @@ -223,7 +188,7 @@ class _Ending(NamedTuple): errors: int omitted: int offline: int - failures: list[tuple[str, str]] | None + failures: list[Failure] sources: str kept: list[str] advice: list[str] @@ -237,58 +202,40 @@ class _Ending(NamedTuple): missing: Tally | None -def _say_failures(say: Callable[..., None], failures: list[tuple[str, str]] | None) -> None: +def _say_failures(say: Callable[..., None], failures: list[Failure]) -> None: """The failed files the progress has not named, one cause said once.""" - reasons = {reason for _dest, reason in failures or []} + reasons = {record.reason for record in failures} # A failure the progress already named on its FAILED line is not named # again: line mode listed each one twice. - unsaid = [failure for failure in failures or [] if failure[0] not in SAID_FAILED] + unsaid = [record for record in failures if record.dest not in SAID_FAILED] if failures and len(failures) > 1 and len(reasons) == 1 and reasons != {""}: # One cause, said once: a read-only folder listed ten of its files # and "... and 266 more" above the advice that fixes them all. - said = f", first {unsaid[0][0]}" if unsaid else "" + said = f", first {unsaid[0].dest}" if unsaid else "" say(f" failed: {_plural(len(failures), 'file')} ({reasons.pop()}){said}") else: - for dest, reason in unsaid[:10]: + for dest, reason, _kind, _url in unsaid[:10]: say(f" failed: {dest}" + (f" ({reason})" if reason else "")) if len(unsaid) > 10: say(f" ... and {len(unsaid) - 10} more") def _failure_advice( - paths: list[Path], failures: list[tuple[str, str]], assumed: set[Path] | None, + paths: list[Path], failures: list[Failure], assumed: set[Path] | None, platform_of: dict[Path, str] | None, ) -> list[str]: """What to do about the causes of the failed files, one line each.""" - refused = any(reason == NOT_WRITABLE for dest, reason in failures - if not Path(dest).is_absolute()) + refused = any(record.kind == "not_writable" for record in failures + if not Path(record.dest).is_absolute()) advice = [ _write_advice(path, path in (assumed or set()), (platform_of or {}).get(path, "")) for path in paths ] if refused else [] advice += [_write_advice(folder, False) for folder in sorted({ - Path(dest).parent for dest, reason in failures - if Path(dest).is_absolute() and reason == NOT_WRITABLE + Path(record.dest).parent for record in failures + if Path(record.dest).is_absolute() and record.kind == "not_writable" })] - if any(reason == DRIVE_FULL for _dest, reason in failures): - advice.append(f" The drive holding {_locations(paths)} is full: free up space, or " - "install to another drive with --dest, then run again.") - if any(reason == READ_ONLY for _dest, reason in failures): - advice.append(" Files marked read-only are in the way: clear that attribute " - "(or delete them), then run again.") - advice += _http_failure_lines(failures) - if any(isinstance(reason, NetworkReason) for _dest, reason in failures): - advice.append(NETWORK_FAILURE_ADVICE) - if active_remote().overridden: - # A mirror that is down read as this machine's connection. - advice.append(OVERRIDE_LINE) - if any(str(reason).startswith(NOT_KEPT) for _dest, reason in failures): - # The same run fails the same way: "retry only those" sent a phone - # user round the loop with nothing changed. - advice.append(" The files in place were left as they were, as no backup folder could " - "be made for them. Move them out of the folder, then run again to " - "install the new ones.") - return advice + return advice + failure_remedies(failures, _locations(paths)) def _kept_and_unplaced(omitted_entries: list[dict], notes: list[str] | None, @@ -365,19 +312,18 @@ def _end_nothing_installed(end: _Ending) -> NoReturn: """End a run whose every file failed.""" say, paths, failures = end.say, end.paths, end.failures say(f"\nNothing was installed. {_plural(end.errors, 'file')} failed.") - if failures and all(isinstance(r, (NetworkReason, HttpReason, OfflineReason)) - for _d, r in failures): + if connection_only(failures): # The folder was never the problem: naming it as the place being # written to sent people looking at their disk. say(f"BIOS folder: {_locations(paths)}") - elif _retry_words(failures): + elif retry_words(failures): # Nothing was written: every file is one the pack lacks. say(f"BIOS folder: {_locations(paths)}") else: say(f"BIOS folder that was being written to: {_locations(paths)}") for line in end.kept + end.advice: say(line) - say(_retry_words(failures) or "Run the same command again once that is resolved. " + say(retry_words(failures) or "Run the same command again once that is resolved. " "Files already installed are kept.") for line in end.same_lines: say(line) @@ -398,11 +344,10 @@ def _end_with_errors(end: _Ending) -> NoReturn: say(f"BIOS folder: {_locations(end.paths)}") for line in end.kept + end.advice: say(line) - retry = _retry_words(failures) + retry = retry_words(failures) if retry: say(retry) - elif not all(str(reason).startswith(NOT_KEPT) or reason == DRIVE_FULL - for _dest, reason in failures or []): + elif retry_helps(failures): say("Run the same command again to retry only those.") for line in end.same_lines: say(line) @@ -521,17 +466,15 @@ def _report_outcome( # A file --offline left out is not a failure, whether the run asked or # not: without questions it was "14698 files failed", and "Run the same # command again to retry only those", which cannot fetch them. - left = [failure for failure in failures or [] if isinstance(failure[1], OfflineReason)] + records, left = split_offline(failure_records(failures or [])) if left: - failures = [failure for failure in failures or [] - if not isinstance(failure[1], OfflineReason)] errors = max(0, errors - len(left)) offline += len(left) if transferred and seconds > 0 and OUTPUT.verbose: verb = "copied from the pack" if LOCAL.pack is not None else "downloaded" say(f"\n{format_size(transferred)} {verb} in " f"{format_duration(seconds)} ({format_size(int(transferred / seconds))}/s).") - _say_failures(say, failures) + _say_failures(say, records) if declined and not downloaded and not errors and not interrupted and not offline: say(f"\nNothing installed: {_plural(declined, 'file')} not downloaded, as answered.") if up_to_date: @@ -549,9 +492,9 @@ def _report_outcome( # A standalone copy fails by absolute path, in an emulator's folder # rather than the BIOS folder: that folder is where the write went. - elsewhere = sorted({Path(dest).parent for dest, _reason in failures or [] - if Path(dest).is_absolute()}) - advice = _failure_advice(paths, failures or [], d.assumed, d.platform_of) + elsewhere = sorted({Path(record.dest).parent for record in records + if Path(record.dest).is_absolute()}) + advice = _failure_advice(paths, records, d.assumed, d.platform_of) paths = paths + [folder for folder in elsewhere if folder not in paths] # The kinds installed, on every end that installed some, under where @@ -560,7 +503,7 @@ def _report_outcome( if d.kinds and d.kinds[0].files and downloaded and OUTPUT.verbose else "") end = _Ending( say=say, paths=paths, downloaded=downloaded, up_to_date=up_to_date, errors=errors, - omitted=omitted, offline=offline, failures=failures, sources=d.sources, kept=kept, + omitted=omitted, offline=offline, failures=records, sources=d.sources, kept=kept, advice=advice, same_lines=same_lines, installed_kinds=installed_kinds, omitted_entries=d.omitted_entries or [], unplaced=unplaced, platform_of=d.platform_of or {}, hints=d.hints or [], same_choice=same_choice, @@ -612,20 +555,6 @@ def _offline_remedy(folders: list[str] | None = None, named: bool = False) -> st f"again with a pack (--from-pack) or {offline_undo()}.") -def _retry_words(failures: list | None) -> str: - """What to do when every failure is a file the pack does not hold: a - second run fails them the same way, and "run it again to retry only - those" sent people round. "" otherwise.""" - lacking = [dest for dest, reason in failures or [] if str(reason) == NOT_IN_PACK] - if not lacking or len(lacking) != len([ - dest for dest, reason in failures or [] if not str(reason).startswith(NOT_KEPT)]): - return "" - name = LOCAL.pack.name if LOCAL.pack is not None else "The pack" - return (f"{name} does not hold {'it' if len(lacking) == 1 else 'them'}: a newer pack, " - "or a run without --from-pack, installs " - f"{'it' if len(lacking) == 1 else 'them'}.") - - def _check_fetch_line(fetch: int, beside: str, lacking: int = 0, wrong: bool = False) -> str: """What --check says a run without it does with the files not in place: offline, those it cannot fetch are said so, not "run it to fetch them". @@ -650,11 +579,6 @@ def _check_fetch_line(fetch: int, beside: str, lacking: int = 0, wrong: bool = F f"beside {beside}." if OUTPUT.verbose or wrong else "")) -def _offline_failure(reason: str) -> bool: - """Whether a failure a run reported is a file --offline left out.""" - return OFFLINE_WORDS in reason or "makes no network request" in reason - - # The definitions in a few words, for a help with no room for the sentences. _SHORT_DEFINITIONS = ( ("Game data:", "Game data: what a game reads, of no use to other cores."), diff --git a/installer/run.py b/installer/run.py index c3fc2bc7f..334d76094 100644 --- a/installer/run.py +++ b/installer/run.py @@ -15,6 +15,7 @@ from installer.detect_os import detected_shown from installer.diagnosis import CheckHeld, bios_folder_index, check_lines from installer.download import download_files from installer.events import EVENTS, _event_mode +from installer.failure_causes import OfflineReason, failure_events from installer.fetch_plan import emit_fetch_plan, fetch_plan from installer.filesystems import NOMEDIA, hide_from_media_scanner from installer.from_folders import ( @@ -47,7 +48,6 @@ from installer.local_check import check_local, head_reads_done from installer.offline import LOCAL, _offline_only, offline_named from installer.outcome import ( EVERYTHING_IN_PLACE, - OfflineReason, OutcomeDetails, _check_fetch_line, _report_outcome, @@ -71,7 +71,7 @@ from installer.run_setups import ( ) from installer.safe_replace import KEPT, NOT_KEPT, plan_kept from installer.space import bytes_written -from installer.standalone import do_standalone_copies, standalone_folders_here +from installer.standalone import do_standalone_copies, preview_standalone, standalone_folders_here, standalone_plan from installer.tally import ( CheckTally, _absent_required, @@ -423,6 +423,8 @@ def _pass_make_folder(run: _InstallRun, p: _PlatformPass, written: int) -> bool: # and no summary, what was installed before it unsaid. EVENTS.emit("error", stage="dest", reason="not_writable", platform=plat_name, message=f"{bios_path} cannot be created: {exc.strerror}") + if run.failures: + EVENTS.emit("failures", failed=failure_events(run.failures)) EVENTS.emit( "summary", mode=_event_mode(args), installed=run.total_downloaded, up_to_date=run.total_up_to_date, pending=run.files_pending + len(p.to_download), @@ -467,6 +469,7 @@ def _pass_fetch(run: _InstallRun, p: _PlatformPass, dl_size: int, created: bool) # counted them, over the files that landed: matched by the end # of a failed path, a.bin was dropped when x/a.bin failed. run.landed.extend(progress.landed) + p.landed += progress.landed p.record_files += [record_file(entry, "copy" if id(entry) in p.copies else "pack" if LOCAL.pack is not None else "download") for entry in progress.landed] @@ -630,8 +633,11 @@ def _pass_standalone(run: _InstallRun, p: _PlatformPass) -> None: print("\nStandalone emulators:") lb_root = launchbox_root(os_type) extra_dirs = launchbox_bios_dirs(lb_root) if lb_root else None + # The files this run checked in place or put there, never others + # the folder holds. copied, skipped, copy_failed = do_standalone_copies( - manifest, p.bios_path, os_type, extra_dirs, run.failures + manifest, p.bios_path, os_type, extra_dirs, run.failures, + p.up_to_date + p.landed, ) if copied or skipped or copy_failed: print( @@ -654,6 +660,25 @@ def _pass_standalone(run: _InstallRun, p: _PlatformPass) -> None: "they read into them.") +def _pass_standalone_preview(run: _InstallRun, p: _PlatformPass) -> None: + """--check or --dry-run with --standalone-copies: the emulator folders + found here, what each holds and lacks or would receive, as a run with + no platform says them.""" + if not (p.manifest.get("standalone_copies") and run.args.standalone_copies): + return + lb_root = launchbox_root(run.os_type) + plan = standalone_plan([{**p.manifest, "files": p.files}], run.os_type, + launchbox_bios_dirs(lb_root) if lb_root else None) + if not plan: + return + print("\nStandalone emulators:") + pending = preview_standalone(plan, run.args, run.term) + if run.args.check: + run.check_pending += pending + else: + run.files_pending += pending + + def _apply_setup_files(run: _InstallRun, p: _PlatformPass) -> bool: """The setup's files packed, checked, planned or installed. True when the run stops there.""" @@ -668,9 +693,11 @@ def _apply_setup_files(run: _InstallRun, p: _PlatformPass) -> bool: _pass_check_existing(run, p) if args.check: _pass_check_report(run, p) + _pass_standalone_preview(run, p) return False if args.dry_run: _pass_dry_run(run, p) + _pass_standalone_preview(run, p) return False if p.to_download: @@ -716,6 +743,8 @@ def _finish_install(run: _InstallRun, real_stdout: TextIO) -> None: # The matches are the answer: nothing was installed. sys.exit(4 if getattr(args, "find_failed", False) else 0) if not run.listing: + if run.failures: + EVENTS.emit("failures", failed=failure_events(run.failures)) EVENTS.emit( "summary", mode=_event_mode(args), installed=run.total_downloaded, up_to_date=run.total_verified if args.check or args.dry_run else run.total_up_to_date, diff --git a/installer/run_files.py b/installer/run_files.py index 4a887bcf8..7d99746ad 100644 --- a/installer/run_files.py +++ b/installer/run_files.py @@ -232,6 +232,8 @@ class _PlatformPass: self.record_files: list[dict] = [] self.to_download: list[dict] = [] self.up_to_date: list[dict] = [] + # The entries this run put in place, each checked as it landed. + self.landed: list[dict] = [] self.mismatched: list[dict] = [] self.data_states: list[tuple[dict, tuple[Path, dict[str, dict], int]]] = [] self.trees_missing = 0 diff --git a/installer/standalone.py b/installer/standalone.py index b8207f20d..7de481dbf 100644 --- a/installer/standalone.py +++ b/installer/standalone.py @@ -19,7 +19,7 @@ from installer.outcome import EVERYTHING_IN_PLACE, OutcomeDetails, _check_fetch_ from installer.paths import _destination_path, _within from installer.plan import _check_free_space, _print_plan from installer.plan_words import _sized -from installer.safe_replace import BACKUP_DIR, KEPT, NOT_KEPT, _NotKept, plan_kept +from installer.safe_replace import KEPT, NOT_KEPT, _NotKept, plan_kept if TYPE_CHECKING: from installer.terminal import Terminal @@ -67,40 +67,56 @@ def standalone_folders_here( STANDALONE_SOURCES = ("emudeck", "retroarch") +def copy_sources(manifest: dict) -> list[tuple[dict, list[tuple[dict, str]]]]: + """Each standalone copy entry of the manifest, with the entries of its + file list it carries and the name each takes in the emulator folder. + + The one reading of a copy entry: a pattern matches the names the list + gives, never whatever lies in the BIOS folder (a user's own + scph9999.bin went to DuckStation). `source` is where this list puts the + file that `file` names as the registry does for every platform: read + there, it was missing wherever the pack places it elsewhere. + """ + from fnmatch import fnmatch + + files = manifest.get("files", []) + by_dest = {entry["dest"]: entry for entry in files} + carried: list[tuple[dict, list[tuple[dict, str]]]] = [] + for copy in manifest.get("standalone_copies", []): + if "note" in copy: + continue + if "pattern" in copy: + sources = [entry for entry in files + if fnmatch(PurePosixPath(entry["dest"]).name, copy["pattern"])] + else: + held = by_dest.get(copy.get("source") or copy["file"]) + sources = [held] if held else [] + # `as`: the name the emulator reads, when it is not the + # platform's (melonDS's dsisd.bin, xemu's eeprom.bin). + carried.append((copy, [(entry, copy.get("as") or PurePosixPath(entry["dest"]).name) + for entry in sources])) + return carried + + def standalone_plan( manifests: list[dict], os_type: str, extra_dirs: dict[str, Path] | None = None, ) -> list[tuple[Path, list[dict]]]: """What each emulator folder found here receives, by its own file name. - The standalone copies of the manifests, read as do_standalone_copies - reads them, but taken from the file lists rather than from a platform - tree already installed: an ES-DE user with DuckStation and PCSX2 and no - RetroArch had no tree to copy from. The first list that holds a name for - a folder serves it. + The standalone copies of the manifests (copy_sources), each entry named + as the emulator reads it. A run with no platform fetches them from the + lists: an ES-DE user with DuckStation and PCSX2 and no RetroArch had no + tree to copy from. The first list that holds a name for a folder + serves it. """ - from fnmatch import fnmatch - plan: dict[Path, dict[str, dict]] = {} for manifest in manifests: - files = manifest.get("files", []) - by_dest = {entry["dest"]: entry for entry in files} - for copy in manifest.get("standalone_copies", []): - if "note" in copy: - continue - if "pattern" in copy: - sources = [entry for entry in files - if fnmatch(PurePosixPath(entry["dest"]).name, copy["pattern"])] - else: - held = by_dest.get(copy.get("source") or copy["file"]) - sources = [held] if held else [] + for copy, sources in copy_sources(manifest): for folder in _copy_targets(copy, os_type, extra_dirs): if not sources or not _is_dir(folder): continue chosen = plan.setdefault(folder, {}) - for entry in sources: - # `as`: the name the emulator reads, when it is not the - # platform's (melonDS's dsisd.bin, xemu's eeprom.bin). - name = copy.get("as") or PurePosixPath(entry["dest"]).name + for entry, name in sources: chosen.setdefault(name, {**entry, "dest": name}) return [(folder, list(entries.values())) for folder, entries in plan.items() if entries] @@ -120,6 +136,25 @@ def _check_standalone_folder(to_download: list[dict], mismatched: list[dict], print(f" {EVERYTHING_IN_PLACE}") +def preview_standalone(plan: list[tuple[Path, list[dict]]], args: argparse.Namespace, + term: Terminal) -> int: + """--check or --dry-run over the emulator folders of a standalone plan: + what each holds and lacks, or what a run would write. The count of the + files not in place.""" + pending = 0 + for folder, entries in plan: + print(f"\n{folder}:") + to_download, _up_to_date, mismatched = check_local(entries, folder, jobs=args.jobs) + to_download.extend(mismatched) + if args.check: + _check_standalone_folder(to_download, mismatched, args.verbose) + else: + _print_plan(to_download, folder, term, kept=plan_kept(mismatched, folder), + verbose=args.verbose) + pending += len(to_download) + return pending + + def _install_standalone_folders( args: argparse.Namespace, os_type: str, term: Terminal, interactive: bool, ) -> bool: @@ -146,8 +181,13 @@ def _install_standalone_folders( "\nInstall the BIOS files these emulators read into their folders? [Y/n] " ): return False + if args.check or args.dry_run: + pending = preview_standalone(plan, args, term) + if args.check and pending: + print("\n" + _check_fetch_line(pending, "its folder")) + sys.exit(3) + return True downloaded = up_to_date_count = errors = 0 - pending = 0 failures: list[tuple[str, str]] = [] transferred, seconds = 0, 0.0 interrupted = False @@ -156,14 +196,6 @@ def _install_standalone_folders( to_download, up_to_date, mismatched = check_local(entries, folder, jobs=args.jobs) to_download.extend(mismatched) up_to_date_count += len(up_to_date) - if args.check: - _check_standalone_folder(to_download, mismatched, args.verbose) - pending += len(to_download) - continue - if args.dry_run: - _print_plan(to_download, folder, term, kept=plan_kept(mismatched, folder), - verbose=args.verbose) - continue if not to_download: print(f" {EVERYTHING_IN_PLACE}") continue @@ -181,13 +213,6 @@ def _install_standalone_folders( seconds += progress.elapsed() if interrupted: break - if args.check: - if pending: - print("\n" + _check_fetch_line(pending, "its folder")) - sys.exit(3) - return True - if args.dry_run: - return True _report_outcome( [folder for folder, _entries in plan], downloaded, up_to_date_count, errors, 0, interrupted, @@ -209,25 +234,6 @@ def _print_standalone_note(entry: dict, os_type: str) -> None: break -def _standalone_sources(entry: dict, bios_path: Path) -> list[Path]: - """The files of the BIOS folder a standalone copy entry copies.""" - from fnmatch import fnmatch - - if "pattern" in entry: - # A kept file is never a source, when the backup had to go - # inside the BIOS folder. - return [ - f for f in bios_path.rglob("*") - if fnmatch(f.name, entry["pattern"]) and f.is_file() - and BACKUP_DIR not in f.relative_to(bios_path).parts - ] - # `source` is where this platform's manifest put the file, and `file` - # names it as the registry does for every platform, and laid out - # that way it was missing wherever the pack places it elsewhere. - src = _destination_path(bios_path, entry.get("source") or entry["file"]) - return [src] if _exists(src) else [] - - def _copy_standalone_file(src: Path, dest: Path, resolved_dir: Path, failures: list[tuple[str, str]] | None) -> bool: """Copy one file into an emulator folder, False when it was refused.""" @@ -268,14 +274,16 @@ def do_standalone_copies( manifest: dict, bios_path: Path, os_type: str, extra_dirs: dict[str, Path] | None = None, failures: list[tuple[str, str]] | None = None, + verified: list[dict] | None = None, ) -> tuple[int, int, int]: """Copy BIOS files to standalone emulator directories. - Supports: - - file: single file copy - - pattern: glob match (e.g. "scph*.bin") - - note: informational message when detect path exists - - WSL fallback to linux targets + Each copy entry carries what copy_sources names, the entries of the + file list, read in bios_path: verified holds the entries this run found + or put there with their hashes, and no other is copied. Without it, + every entry of the list present in bios_path. A note entry prints its + message when its emulator is found here, and WSL falls back to the + Linux folders. extra_dirs maps the emulator id of an entry to a root that replaces the default per-OS locations, for setups such as LaunchBox that keep their @@ -292,18 +300,22 @@ def do_standalone_copies( copies = manifest.get("standalone_copies", []) if not copies: return 0, 0, 0 + carried = {id(copy): sources for copy, sources in copy_sources(manifest)} + held = None if verified is None else {entry["dest"] for entry in verified} copied = 0 skipped = 0 failed = 0 for entry in copies: - # Note entries: print message if emulator detected if "note" in entry: _print_standalone_note(entry, os_type) continue - sources = _standalone_sources(entry, bios_path) + sources = [(src, name) for src, name in ( + (_destination_path(bios_path, item["dest"]), name) + for item, name in carried[id(entry)] + if held is None or item["dest"] in held) if _exists(src)] if not sources: continue @@ -320,8 +332,8 @@ def do_standalone_copies( skipped += len(sources) continue resolved_dir = target_dir.resolve() - for src in sources: - dest = target_dir / (entry.get("as") or src.name) + for src, name in sources: + dest = target_dir / name if _copy_standalone_file(src, dest, resolved_dir, failures): copied += 1 else: diff --git a/installer/tui_outcome.py b/installer/tui_outcome.py index 20ea4643c..6c1eb856c 100644 --- a/installer/tui_outcome.py +++ b/installer/tui_outcome.py @@ -7,25 +7,30 @@ from typing import TYPE_CHECKING, NamedTuple from installer.cards import _mounted_cards, card_system from installer.destination import _last_name from installer.detect_os import detected_os +from installer.failure_causes import ( + Failure, + event_records, + failure_records, + failure_remedies, + retry_helps, + retry_words, + split_offline, +) from installer.from_folders import sources_line from installer.handheld_app import NO_PYTHON_CARDS, app_lines, no_python_words -from installer.host_fs import NOT_WRITABLE from installer.invocation import Invocation from installer.offline import LOCAL, offline_named from installer.outcome import ( EVERYTHING_IN_PLACE, NEXT_ON_CARD, NEXT_ON_DEVICE, - _offline_failure, _offline_remedy, - _retry_words, write_remedy, ) from installer.paths import shown_path from installer.platforms import display_name from installer.removal import _kept_words, backup_words, kept_line from installer.romm import ROMM_SCAN_WORDS -from installer.safe_replace import NOT_KEPT from installer.tally import installed_words, left_out_words from installer.text import _plural, _wrap, agree, cell_width, format_size from installer.tui_choice import _on_its_card, _plan_folder, _tui_categories, _tui_tally @@ -77,8 +82,8 @@ class _OutcomeCounts(NamedTuple): """What an install run reported, as its result counts it.""" summary: dict installed: int - failed: list - offline_failed: list + failed: list[Failure] + offline_failed: list[Failure] left: int up_to_date: int total: int @@ -91,12 +96,15 @@ def _outcome_counts(state: TuiState) -> _OutcomeCounts: # Killed by the second Ctrl-C, the child wrote no summary: what it # reported finished is what is installed. installed = summary.get("installed", sum(1 for _dest, ok, _why in state.finished if ok)) - failed = summary.get("failed") or [] + # Each with its cause, from the failures event the summary follows: + # without it, the cause its words name. + records = (event_records(state.failures) if summary.get("failed") and state.failures + else failure_records((failure["dest"], failure["reason"]) + for failure in summary.get("failed") or [])) # Left out by --offline: missing, never failed, as line mode says it. # The engine counts them in pending and no longer in failed (a file was # both): pending holds the real failures too, which are taken out. - offline_failed = [failure for failure in failed if _offline_failure(failure["reason"])] - failed = [failure for failure in failed if not _offline_failure(failure["reason"])] + failed, offline_failed = split_offline(records) left = len(offline_failed) + (max(0, summary.get("pending", 0) - len(failed)) if tui_offline_only(state) and not offline_failed else 0) up_to_date = summary.get("up_to_date", 0) @@ -160,7 +168,7 @@ def _outcome_counted(state: TuiState, counts: _OutcomeCounts, title: str, installed, failed, left = counts.installed, counts.failed, counts.left lines = [head] ok_dests = {dest for dest, good, _why in state.finished if good} - missing = ([failure["dest"] for failure in counts.offline_failed] + missing = ([failure.dest for failure in counts.offline_failed] or [event["dest"] for event in state.files if event["dest"] not in ok_dests][:left]) if left else [] # A wrong copy left in place is no missing file: --check counts it apart, @@ -236,12 +244,12 @@ def _outcome_placed(state: TuiState, counts: _OutcomeCounts, title: str) -> list return lines -def _failure_lines(failed: list) -> list[str]: +def _failure_lines(failed: list[Failure]) -> list[str]: """Each file that failed with its reason, a reason shared by many said once.""" lines: list[str] = [] causes: dict[str, list[str]] = {} for failure in failed: - causes.setdefault(failure["reason"], []).append(failure["dest"]) + causes.setdefault(failure.reason, []).append(failure.dest) shown = 0 for reason, dests in causes.items(): if len(dests) > 3: @@ -258,14 +266,21 @@ def _failure_lines(failed: list) -> list[str]: return lines -def _retry_lines(failed: list) -> list[str]: +def _remedy_lines(state: TuiState, failed: list[Failure]) -> list[str]: + """What to do about each cause, the words line mode gives: the screen + ended a mirror's 404 or a proxy's refusal on "Run it again".""" + where = shown_path(str(_plan_folder(state, state.dest))) if state.dest else "the folder" + return [line.strip() for advice in failure_remedies(failed, where) + for line in advice.split("\n")] + + +def _retry_lines(failed: list[Failure]) -> list[str]: # What a rerun does, as line mode and the first install page say # it: the screen never did. - pairs = [(failure["dest"], failure["reason"]) for failure in failed] - retry = _retry_words(pairs) + retry = retry_words(failed) if retry: return [retry] - if not all(str(reason).startswith(NOT_KEPT) for _dest, reason in pairs): + if retry_helps(failed): return ["Run it again to retry only those."] return [] @@ -284,8 +299,7 @@ def _outcome_unfinished(state: TuiState, counts: _OutcomeCounts, title: str) -> lines.append(_detail(f"{_plural(expected - landed, 'data file')} not installed" + (f": not in {LOCAL.pack.name}." if LOCAL.pack is not None else "."))) - if state.dest is not None and any(failure["reason"] == NOT_WRITABLE - for failure in failed): + if state.dest is not None and any(failure.kind == "not_writable" for failure in failed): # The plan's own advice: the result offered nothing after 22 files # failed on a read-only card. lines += _commands(state, write_remedy(state.dest, state.platform, tui_hint(state), @@ -343,6 +357,7 @@ def tui_outcome(state: TuiState) -> tuple[str, list[str]]: lines = _outcome_counted(state, counts, title, head) lines += _outcome_placed(state, counts, title) lines += _failure_lines(counts.failed) + lines += _remedy_lines(state, counts.failed) if title == "Finished with errors": lines += _retry_lines(counts.failed) lines += _outcome_unfinished(state, counts, title) diff --git a/installer/tui_receive.py b/installer/tui_receive.py index c3e9b0f6e..b52da53ae 100644 --- a/installer/tui_receive.py +++ b/installer/tui_receive.py @@ -173,6 +173,8 @@ def _take_install_event(state: TuiState, kind: str | None, event: dict) -> None: state.progress = event if kind == "downloaded": state.finished.append((event["dest"], event["ok"], event["reason"])) + elif kind == "failures": + state.failures = event["failed"] elif kind == "summary": state.summary = event diff --git a/installer/tui_state.py b/installer/tui_state.py index 4abc24345..577c68770 100644 --- a/installer/tui_state.py +++ b/installer/tui_state.py @@ -283,6 +283,9 @@ class TuiState: self.network: int = 0 self.finished: list = [] self.summary: dict | None = None + # The failed files with their causes, from the failures event the + # summary follows. + self.failures: list[dict] = [] self.code: int | None = None self.stopping: bool = False self.tail: list = [] diff --git a/schemas/install-events.schema.json b/schemas/install-events.schema.json index fec94487e..410ee4811 100644 --- a/schemas/install-events.schema.json +++ b/schemas/install-events.schema.json @@ -39,6 +39,7 @@ "progress", "transfer", "downloaded", + "failures", "summary", "app", "record", @@ -140,6 +141,9 @@ { "$ref": "#/$defs/downloaded" }, + { + "$ref": "#/$defs/failures" + }, { "$ref": "#/$defs/summary" }, @@ -1118,6 +1122,25 @@ } } }, + "failures": { + "type": "object", + "additionalProperties": false, + "required": [ + "event", + "failed" + ], + "properties": { + "event": { + "const": "failures" + }, + "failed": { + "type": "array", + "items": { + "type": "object" + } + } + } + }, "summary": { "type": "object", "additionalProperties": false, diff --git a/tests/test_e2e.py b/tests/test_e2e.py index 5951f0b47..331d3fc98 100644 --- a/tests/test_e2e.py +++ b/tests/test_e2e.py @@ -4087,6 +4087,7 @@ class TestE2E(unittest.TestCase): missing_dir = Path(self.root) / "nonexistent" manifest = { "base_destination": "bios", + "files": [{"dest": "prod.keys"}], "standalone_copies": [ { "file": "prod.keys", diff --git a/tests/test_install.py b/tests/test_install.py index 001196ab0..5d2a972d0 100644 --- a/tests/test_install.py +++ b/tests/test_install.py @@ -1179,6 +1179,7 @@ class TestStandaloneCopiesExtraDirs(unittest.TestCase): def _manifest(self) -> dict: return { + "files": [{"dest": "ps2-0230a.bin"}, {"dest": "GC/USA/IPL.bin"}], "standalone_copies": [ { "pattern": "ps2-*.bin", @@ -1272,7 +1273,7 @@ class StandaloneCopiesReadWhereThePackPutTheFile(unittest.TestCase): (bios / "aes_keys.txt").write_text("keys") sysdata = scratch_dir(self) / "sysdata" sysdata.mkdir() - manifest = {"standalone_copies": [ + manifest = {"files": [{"dest": "aes_keys.txt"}], "standalone_copies": [ {**entry, "emulator": "azahar", "targets": {"linux": [str(sysdata)]}}, ]} return sysdata, install.do_standalone_copies(manifest, bios, "linux") @@ -1300,6 +1301,36 @@ class StandaloneCopiesReadWhereThePackPutTheFile(unittest.TestCase): install._validate_manifest(manifest, "emudeck") +class StandaloneCopiesFollowTheList(unittest.TestCase): + """The platform pass scanned the BIOS folder for each pattern: a user's + own bios/old/scph9999.bin went to DuckStation, while the plan of a run + with no platform named scph5501.bin alone.""" + + def setUp(self) -> None: + self.bios = scratch_dir(self) + (self.bios / "scph5501.bin").write_bytes(b"rom") + (self.bios / "old").mkdir() + (self.bios / "old" / "scph9999.bin").write_bytes(b"other") + self.emu = scratch_dir(self) / "duckstation" + self.emu.mkdir() + self.manifest = {"files": [{"dest": "scph5501.bin"}], "standalone_copies": [ + {"pattern": "scph*.bin", "emulator": "duckstation", + "targets": {"linux": [str(self.emu)]}}]} + + def test_the_copy_and_the_plan_name_the_same_files(self): + plan = install.standalone_plan([self.manifest], "linux") + self.assertEqual([(folder, [entry["dest"] for entry in entries]) + for folder, entries in plan], [(self.emu, ["scph5501.bin"])]) + self.assertEqual(install.do_standalone_copies(self.manifest, self.bios, "linux"), + (1, 0, 0)) + self.assertEqual(sorted(path.name for path in self.emu.iterdir()), ["scph5501.bin"]) + + def test_only_a_file_the_run_verified_is_copied(self): + self.assertEqual(install.do_standalone_copies(self.manifest, self.bios, "linux", + verified=[]), (0, 0, 0)) + self.assertEqual(list(self.emu.iterdir()), []) + + class OuterRootsAreUntrusted(unittest.TestCase): """roms_directory and emulators_directory come from a downloaded list: each path in them meets the rules a BIOS destination meets, and each folder @@ -1870,7 +1901,7 @@ class ARefusedCopyIsAnError(unittest.TestCase): (bios / "prod.keys").write_bytes(b"k") target = Path(tmp, "keys") target.mkdir() - manifest = {"standalone_copies": [ + manifest = {"files": [{"dest": "prod.keys"}], "standalone_copies": [ {"file": "prod.keys", "targets": {"linux": [str(target)]}} ]} with unittest.mock.patch("shutil.copy2", side_effect=PermissionError(13, "denied")): @@ -2054,6 +2085,7 @@ class TestStandaloneCopyTargetsAreUntrusted(unittest.TestCase): def _manifest(self, target: str) -> dict: return { + "files": [{"dest": "boot.bin"}], "standalone_copies": [ {"file": "boot.bin", "targets": {"linux": [target]}} ] @@ -2481,8 +2513,10 @@ class TestLaunchboxDetectionPowershell(unittest.TestCase): (pcsx2 / "inis").mkdir() (pcsx2 / "inis" / "PCSX2.ini").write_text("[Folders]\nBios = bios\n") + # In place with its hash: only a file the run verified is copied. manifest = { - "files": [], + "files": [{"dest": "ps2-0230a.bin", "size": 3, "repo_path": "bios/ps2-0230a.bin", + "sha1": "a1e17a20e93e5da710685444df3ad038ac66e2c9"}], "standalone_copies": [ { "pattern": "ps2-*.bin", @@ -4842,7 +4876,7 @@ class ARefusedStandaloneCopyIsNamed(unittest.TestCase): target.mkdir() target.chmod(0o500) self.addCleanup(target.chmod, 0o700) - manifest = {"standalone_copies": [ + manifest = {"files": [{"dest": "scph5501.bin"}], "standalone_copies": [ {"file": "scph5501.bin", "emulator": "pcsx2", "targets": {"linux": [str(target)]}}, ]} @@ -5131,9 +5165,10 @@ class StandaloneCopiesUnderTheirOwnName(unittest.TestCase): bios = scratch_dir(self) (bios / "xbox_eeprom.bin").write_bytes(b"eeprom") folder = scratch_dir(self) - manifest = {"standalone_copies": [ + manifest = {"files": [{"dest": "xbox_eeprom.bin"}], "standalone_copies": [ {"file": "xbox_eeprom.bin", "as": "eeprom.bin", "targets": {"linux": [str(folder)]}}]} - install._validate_manifest({**self._published(), **manifest}, "emudeck") + install._validate_manifest( + {**self._published(), "standalone_copies": manifest["standalone_copies"]}, "emudeck") self.assertEqual(install.do_standalone_copies(manifest, bios, "linux"), (1, 0, 0)) self.assertEqual((folder / "eeprom.bin").read_bytes(), b"eeprom") self.assertFalse((folder / "xbox_eeprom.bin").exists()) @@ -6302,6 +6337,34 @@ class StandaloneFoldersAreNamedWhenThereAreAny(unittest.TestCase, _LoopbackRun): self.assertIn("--standalone-copies", out) +class StandaloneCopiesAreChecked(unittest.TestCase, _LoopbackRun): + """--check and --dry-run with --standalone-copies said nothing of the + emulator folders: the flag was taken and never applied.""" + + def setUp(self) -> None: + self.env = self.serve(self) + self.duckstation = self.home / ".local" / "share" / "duckstation" / "bios" + self.duckstation.mkdir(parents=True) + + def _run(self, *argv: str) -> subprocess.CompletedProcess: + return _install_run(self.env, "--platform", "retroarch", "--dest", + str(self.home / "system"), "--system", "sony-playstation", + "--standalone-copies", "--no-input", *argv) + + def test_check_names_what_the_folder_lacks(self): + proc = self._run("--check") + self.assertEqual(proc.returncode, 3, proc.stdout + proc.stderr) + self.assertIn("Standalone emulators:", proc.stdout) + self.assertIn(f"{self.duckstation}:", proc.stdout) + self.assertIn("missing: scph1001.bin", proc.stdout) + + def test_dry_run_plans_the_copies(self): + proc = self._run("--dry-run") + self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr) + self.assertIn(f"{self.duckstation}:", proc.stdout) + self.assertEqual(list(self.duckstation.iterdir()), []) + + class StandaloneEmulatorsWithoutAPlatformAreServed(unittest.TestCase, _LoopbackRun): """ES-DE with DuckStation and PCSX2 and no RetroArch: the run said 'No supported platform detected' and offered RetroArch's folder, which no @@ -7718,7 +7781,7 @@ class AFileYouHadIsKept(unittest.TestCase): pcsx2 = self.home / "PCSX2" / "bios" pcsx2.mkdir(parents=True) (pcsx2 / "ps2-0230a.bin").write_bytes(self.OLD) - manifest = {"standalone_copies": [ + manifest = {"files": [{"dest": "ps2-0230a.bin"}], "standalone_copies": [ {"pattern": "ps2-*.bin", "emulator": "pcsx2", "targets": {"linux": [str(pcsx2)]}}]} self.assertEqual(install.do_standalone_copies(manifest, self.bios, "linux"), (1, 0, 0)) self.assertEqual((pcsx2 / "ps2-0230a.bin").read_bytes(), self.NEW) @@ -7734,7 +7797,7 @@ class AFileYouHadIsKept(unittest.TestCase): (inside / "ps2-old.bin").write_bytes(self.OLD) pcsx2 = self.home / "PCSX2" / "bios" pcsx2.mkdir(parents=True) - manifest = {"standalone_copies": [ + manifest = {"files": [{"dest": "ps2-0230a.bin"}], "standalone_copies": [ {"pattern": "ps2-*.bin", "emulator": "pcsx2", "targets": {"linux": [str(pcsx2)]}}]} self.assertEqual(install.do_standalone_copies(manifest, self.bios, "linux"), (0, 0, 0)) diff --git a/tests/test_install_offline.py b/tests/test_install_offline.py index 29264388b..59187f8f1 100644 --- a/tests/test_install_offline.py +++ b/tests/test_install_offline.py @@ -1049,8 +1049,9 @@ class OneOfflineVocabulary(Scratch): from tests import test_install_tui as tui reason = f"not fetched: {install.OFFLINE_WORDS}" - state = tui._installed_state(self.dest, 1, [{"dest": f"f{n}.bin", "reason": reason} - for n in range(20)]) + left = [{"dest": f"f{n}.bin", "reason": reason} for n in range(20)] + state = tui._installed_state(self.dest, 1, left) + state.failures = [{**failure, "kind": "offline", "url": ""} for failure in left] state.summary["installed"] = 2 state.from_folders = [self.root / "from1"] title, lines = install.tui_outcome(state) diff --git a/tests/test_install_tui.py b/tests/test_install_tui.py index 36f8de0b9..e9e3430a1 100644 --- a/tests/test_install_tui.py +++ b/tests/test_install_tui.py @@ -1354,12 +1354,14 @@ def result_states() -> dict: "left_out": [], "kept": [], "interrupted": False, **summary} return state + left = [{"dest": name, "reason": install.OFFLINE_WORDS} + for name in ("scph5500.bin", "scph5501.bin", "pcsx/extra.bin")] + offline = ended(1, installed=1, pending=3, failed=left) + offline.failures = [{**failure, "kind": "offline", "url": ""} for failure in left] return { "done": ended(0), "partial": golden_states()["result"], - "offline": ended(1, installed=1, pending=3, failed=[ - {"dest": name, "reason": install.OFFLINE_WORDS} - for name in ("scph5500.bin", "scph5501.bin", "pcsx/extra.bin")]), + "offline": offline, "stopped": ended(130, installed=2, interrupted=True), } @@ -5286,6 +5288,41 @@ def _installed_state(dest: Path, code: int = 0, failed: list | None = None) -> i return state +class TheResultGivesTheRemediesOfLineMode(unittest.TestCase): + """The screen ended a mirror's 404 and a cut connection on "Run it again + to retry only those", where line mode named the address, the proxy and + that running again changes nothing: the cause did not reach it.""" + + def _state(self, *failures: tuple) -> install.TuiState: + failed = [{"dest": dest, "reason": reason} for dest, reason, _kind, _url in failures] + state = _installed_state(SYSTEM_DIR, 1, failed) + state.failures = [{"dest": dest, "reason": reason, "kind": kind, "url": url} + for dest, reason, kind, url in failures] + return state + + def test_each_cause_gets_the_line_mode_remedy(self): + url = "https://example.invalid/bios/a.bin" + state = self._state(("a.bin", "HTTP 404", "http", url), + ("b.bin", "timed out", "network", "")) + text = "\n".join(str(line) for line in install.tui_outcome(state)[1]) + records = install.event_records(state.failures) + for advice in install.failure_remedies(records, "x"): + for line in advice.split("\n"): + self.assertIn(line.strip(), text) + self.assertIn(f"The server answered HTTP 404 for {url}.", text) + self.assertIn("HTTPS_PROXY", text) + + def test_the_cause_comes_from_the_event_not_the_words(self): + state = self._state(("a.bin", "not fetched: no request", "offline", "")) + title, _lines = install.tui_outcome(state) + self.assertEqual(title, "Finished with files missing") + + def test_a_full_drive_offers_no_retry(self): + state = self._state(("a.bin", install.DRIVE_FULL, "drive_full", "")) + lines = [str(line) for line in install.tui_outcome(state)[1]] + self.assertNotIn("Run it again to retry only those.", lines) + + class TheRomMResultNamesTheScan(unittest.TestCase): """RomM's player sees firmware its scan recorded: the result said "installed" and left the scan unsaid.""" diff --git a/wiki/architecture.md b/wiki/architecture.md index 50c87c78e..6c71cb292 100644 --- a/wiki/architecture.md +++ b/wiki/architecture.md @@ -504,7 +504,7 @@ those it imports: | This machine | `detection_notes`, `detect_os`, `detect_frontends`, `cards`, `device`, `cores`, `frontend_folders`, `setups` | | Sources of files | `offline`, `network`, `lists`, `pack_source`, `from_folders`, `diagnosis`, `download`, `datadirs`, `standalone` | | What a run keeps | `narrowing`, `choices`, `romm`, `install_record`, `game_files`, `games`, `tally`, `space`, `fetch_plan` | -| Line mode | `destination`, `line_folder`, `line_menu`, `plan_words`, `plan`, `outcome` | +| Line mode | `destination`, `line_folder`, `line_menu`, `plan_words`, `plan`, `failure_causes`, `outcome` | | Runs and actions | `arguments`, `run_setups`, `run_files`, `run`, `pack`, `removal`, `handheld_app`, `cli` | | Full screen | `tui_state`, `tui_routes`, `tui_commands`, `tui_keys`, `tui_paint`, `tui_choice`, `tui_folder_scan`, `tui_rows`, `tui_frame`, `tui_plan_view`, `tui_outcome`, `tui_screens`, `tui_actions`, `tui_input`, `tui_receive`, `tui_list_words`, `tui_engine`, `tui_session` | diff --git a/wiki/installer.md b/wiki/installer.md index eaa023d33..e99cabe45 100644 --- a/wiki/installer.md +++ b/wiki/installer.md @@ -1729,7 +1729,11 @@ executable, picked in the app) is not a target, nor is a place the registry already gives for the same file. A file the emulator finds by its contents in a folder the user sets (Amiberry's ROMs) is left out. -An entry names one file or a glob, and one entry carries no file at all: when +An entry names one file or a glob, matched against the names of the file list, +never against whatever else the BIOS folder holds: only a file this run found +in place with its hash, or put there, is copied. With `--check` or +`--dry-run`, each emulator folder found says what it holds and lacks, or what +the run would write to it. One entry carries no file at all: when an RPCS3 configuration directory is present it prints that `PS3UPDAT.PUP` is installed through RPCS3's own File menu, since that firmware is an installer to run rather than a file to copy. @@ -2251,6 +2255,7 @@ other schemas under `api/v1/schemas/`. | `progress` | `files_done`, `files_total`, `bytes_done`, `bytes_total` | At most every half second while bytes arrive | | `transfer` | `bytes_local`, `bytes_network` | Right after each `progress` event, and once when the files of a `download` event are done. It splits `bytes_done`: `bytes_local` came from this machine (a copy found by `--from` or in the BIOS folder, the pack, a partial copy resumed), `bytes_network` from the network. A download speed is `bytes_network` over the time elapsed | | `downloaded` | `dest`, `ok`, `reason`, `size`, `files_done`, `files_total`, `bytes_done`, `bytes_total` | Each finished file, downloaded or copied from where a `found` event named it. `reason` says why one failed, and is empty otherwise. `bytes_done` counts every byte arrived, as `progress` does, a file still in transfer included: it never runs back | +| `failures` | `failed` | Right before a `summary` whose `failed` is not empty: the same files, each `{dest, reason, kind, url}`. `kind` is the cause (`offline`, `network`, `http`, `not_writable`, `drive_full`, `read_only`, `not_kept`, `not_in_pack` or `other`), `url` the address a server refused (`http`), empty otherwise. A screen reads the cause here to give the remedy line mode gives | | `summary` | `mode`, `installed`, `up_to_date`, `pending`, `failed`, `skipped`, `left_out`, `kept`, `interrupted` | The outcome. `pending` counts what a next run would still fetch, `failed` lists `{dest, reason}`, `skipped` lists `{reason, label, files, required}` for the files the collection cannot supply, `left_out` lists `{category, label, files, dests}` for what `--no-game-data` left out, and is empty without it. `kept` lists `{folder, files, bytes}`, one per backup folder, for the files in place the run moved aside before replacing them (with `--dry-run`, would move), and is empty when none. Not written for a listing | | `app` | `system`, `folder`, `ok`, `reason`, `dests`, `written`, `kept` | After `summary`, with `--add-app` or a yes to its question: the RetroBIOS app on the card of `system` whose root is `folder`. `dests` lists the app's files below that root, `written` the ones this run wrote (empty when each was in place), `kept` the backup folders as in `summary`. `ok` is false, with `reason`, when the card takes no app (before anything is written, code 2), when the install did not finish, or when a file could not be fetched, verified or written (code 1) | | `record` | `platform`, `folder`, `path`, `status`, `choice`, `date`, `files`, `message` | The [install record](#the-install-record) of `folder`, kept at `path`. `status` is `applied` before `choices` when the run took its choice, nothing on the command line having chosen, `written` before `summary` once an install placed files, `unreadable` when it cannot be read (said once, ignored), or `not_written` when it could not be saved, the install itself unharmed. `choice` is the recorded options as words, `date` when it was written (UTC), `files` how many files it holds for the platform |