From 4c8e9077c56cc0904eb61b5ff928cb198c10ad87 Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Tue, 24 Nov 2026 05:57:21 +0100 Subject: [PATCH] refactor: split the install run passes --- install.ps1 | 2 +- install.py | 860 ++++++++++++++++++----------------- install.sh | 2 +- install/launchers/index.json | 16 +- installer/run.py | 479 +------------------ installer/run_check.py | 225 +++++++++ installer/run_download.py | 286 ++++++++++++ wiki/architecture.md | 2 +- 8 files changed, 965 insertions(+), 907 deletions(-) create mode 100644 installer/run_check.py create mode 100644 installer/run_download.py diff --git a/install.ps1 b/install.ps1 index f634e6761..772b0e635 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 = "d91de8c232409f6c324a86354f21a62972fbf629c088b68fdcc295233263b409" + $defaultInstallSha256 = "bbc5e1c6597873856565869e1a7f8ef376bc698b9d04e7301a3ae56635cfafbd" # 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 b027ae2ff..a5eacd263 100644 --- a/install.py +++ b/install.py @@ -22408,6 +22408,438 @@ def _check_free_space(bios_path: Path, needed: int, plat: str = "", code: int = f"{format_size(needed)} needed, {format_size(free)} free.") +# --- installer/run_check.py -------------------------------------------------- + +def _drop_stale_parts(bios_path: Path, entries: list[dict]) -> None: + """Remove the partial copy left beside each file now in place.""" + for entry in entries: + try: + stale = _entry_path(bios_path, entry) + except ValueError: + continue + stale = stale.parent / f".{stale.name}.part" + if stale.is_file(): + stale.unlink() + + +def _pass_check_existing(run: _InstallRun, p: _PlatformPass) -> None: + """The setup's folder checked, and where each missing file comes from.""" + args, bios_path, files = run.args, p.bios_path, p.files + detail("\nChecking existing files...") + to_download, up_to_date, mismatched = check_local( + files, bios_path, jobs=args.jobs, term=run.term + ) + present = len(up_to_date) + len(mismatched) + # The screen's words: "0/22 present (0 verified, 0 wrong hash)" + # beside its "0 in place, 22 missing, 0 wrong copies". The data files + # the head counts are among them, as the screen counts them. + wrong = len(mismatched) + # Each data tree read and hashed once in the run: the count here, + # the check, the events, the plan and the install read this. + p.data_states = data_states = [(entry, data_directory_state(entry, bios_path)) + for entry in p.data_dirs] + head_reads_done() + p.trees_missing = trees_missing = sum(len(state[1]) for _entry, state in data_states) + trees_held = p.head_data - trees_missing + detail(f" {len(up_to_date) + trees_held} in place, " + f"{p.run_counts.files - present + trees_missing} missing, " + f"{_plural(wrong, 'wrong copy')}") + + # A partial copy left by an interrupted run is useless once the file + # is in place: it goes. + _drop_stale_parts(bios_path, up_to_date) + + # Mismatched files need re-download + to_download.extend(mismatched) + p.to_download, p.up_to_date, p.mismatched = to_download, up_to_date, mismatched + # The files this machine already holds: misplaced in the BIOS folder + # (bios/bios/, a pack extracted into a folder of its own, a name in + # capitals, still zipped), or in a folder named with --from. + p.bios_index = bios_index = (bios_folder_index(bios_path, files, up_to_date) + if to_download else None) + if bios_index is not None: + run.bios_indexes.append(bios_index) + p.copies = copies = plan_local_copies(to_download, bios_path, bios_index, LOCAL.folders) + p.plan = plan = fetch_plan(to_download, copies, data_states) + p.unread = unread = unreadable_copies(to_download, copies, LOCAL.folders) + selection = p.selection + p.hint = [] if LOCAL.pack is not None else bulk_hint( + to_download, p.manifest, + systems_chosen=bool(selection and selection[0]), + cores_chosen=bool((selection and selection[1]) or args.emulator + or args.installed_cores or p.target), + accepted=p.core_choices, + ) + + if EVENTS.on: + # What the run would write, as _pass_download holds it against the + # free space: the screen's plan warns on this number. + _emit_check( + p.plat_name, p.manifest, bios_path, + CheckTally(files, up_to_date, mismatched, + sum(len(state[1]) for _entry, state in data_states), + len(p.omitted_files), + sum(data_fetch_bytes(entry, state[1]) for entry, state in data_states), + bytes_written(plan.without_lacking(to_download), data_states)), + chosen=selection[0] if selection else None, + ) + emit_fetch_plan(p.plat_name, plan) + emit_copies(p.plat_name, to_download, copies, bios_index, bios_path, files) + emit_unreadable(p.plat_name, unread) + run.total_verified += len(up_to_date) + + +def _pass_check_missing(run: _InstallRun, p: _PlatformPass) -> None: + """--check: the files not in place named, and how to get them.""" + args, bios_path = run.args, p.bios_path + to_download, mismatched, copies, plan = p.to_download, p.mismatched, p.copies, p.plan + # Named, not only counted: a user looking for the one bad + # BIOS learned "1 files need downloading" and nothing else. + # A wrong hash comes first and always in full: listed after + # 8000 missing files, it hid behind "... and 8059 more". + wrong = {id(entry) for entry in mismatched} + missing = [entry for entry in to_download if id(entry) not in wrong] + # A pack extracted from some of its parts: the part is named + # before the hundreds of files it holds. + for line in split_pack_lines(bios_path): + print(line) + offline = _offline_only() + # What the pack lacks is said before the count, as the + # screen says it. + if plan.lacking: + print(f"\n {pack_lacks_words(len(plan.lacking), len(plan.fetched))}") + # One total with the count above it, the data files among + # them as the screen counts them: "0 in place, 10805 missing" + # stood over "8164 files to download". + # The count and the folder by default, each file with + # --verbose: 20 paths hid the line saying what to do. + print(f"\n {_plural(len(to_download) + p.trees_missing, 'file')} " + + ("not in place." if offline or LOCAL.pack is not None + else "to download.")) + for line in check_lines(missing, mismatched, p.files, p.manifest, bios_path, + args.verbose, CheckHeld(p.up_to_date, p.bios_index, copies)): + print(line) + for line in unreadable_lines(p.unread, args.verbose): + print(line) + print(f" BIOS folder: {shown_path(bios_path)}") + # The data files need the internet too: offline, "8164 files + # need the internet" stood under "10805 files not in place". + print(_check_fetch_line(len(plan.fetched) + plan.data_files, + "the BIOS folder", len(plan.lacking), bool(mismatched))) + run.check_pending += len(to_download) + + +def _pass_check_report(run: _InstallRun, p: _PlatformPass) -> None: + """--check: what the setup's folder holds and lacks.""" + args, plat_name, bios_path = run.args, p.plat_name, p.bios_path + if p.to_download: + _pass_check_missing(run, p) + elif p.trees_missing: + # The screen's headline: "Everything is in place." stood + # above "0/169 data files present" and exit code 1. + print(f"\n {_plural(p.trees_missing, 'data file')} to fetch") + else: + print(f"\n {EVERYTHING_IN_PLACE}") + print(f" BIOS folder: {shown_path(bios_path)}") + if plat_name in _RECORD_TAKEN: + # The files counted are the recorded choice's, not the list's. + print(f" {record_menu_words(_RECORD_TAKEN[plat_name])} " + "--all-files checks every file.") + absent = _absent_required(p.omitted_files, bios_path) + # The collection cannot supply these, so they leave the exit + # code alone, but a user asking why a game will not start needs + # their count, and with --verbose their names, and which system + # and emulator each one is for. + if absent and not OUTPUT.verbose: + print(f" {needed_absent_words(len(absent), '--verbose')}") + for line in _needed_lines( + absent, "Not in the collection and absent here, needed to start an emulator", + every=args.verbose, + ): + detail(line) + for entry, (_root, needed, present) in p.data_states: + if needed: + detail(f" {entry['ref']}: {present}/{len(entry['files'])} data files " + f"present, {len(needed)} to fetch") + run.check_pending += len(needed) + + +def _pass_dry_run(run: _InstallRun, p: _PlatformPass) -> None: + """--dry-run: the plan of what an install would write.""" + args, bios_path, to_download, copies = run.args, p.bios_path, p.to_download, p.copies + run.files_pending += len(to_download) + trees = [(entry, state[1]) for entry, state in p.data_states] + # A data file in place with other contents is kept like a BIOS file. + kept = plan_kept(p.mismatched + [ + {"dest": f"{entry['dest']}/{rel}" if entry.get("dest") else rel} + for entry, needed in trees for rel in needed + ], bios_path) + plan = p.plan + # Said before the plan promises a count and a size, as an + # install says it: the dry run promised 23 files where the pack + # held 20. + if plan.lacking: + print(f"\n {pack_lacks_words(len(plan.lacking), len(plan.fetched))}") + _print_plan(plan.coming, bios_path, run.term, + trees, kept, copy_plan_lines(to_download, copies, p.bios_index, + bios_path, p.files, args.verbose, True), + verbose=args.verbose, manifest=p.manifest) + if p.plat_name in _RECORD_TAKEN: + print(f" {record_menu_words(_RECORD_TAKEN[p.plat_name])} " + "--all-files lists every file.") + for line in unreadable_lines(p.unread, args.verbose): + print(line) + for line in p.hint: + print(line) + + +# --- installer/run_download.py ----------------------------------------------- + +def _remember_install(args: argparse.Namespace, plat: str, folder: Path, manifest: dict, + written: list[dict], games: bool) -> None: + """Record what this install placed in folder and the choice it made, + games being the card's games applied with no --for-games.""" + if not written and setup_record(plat, folder)[0] is None: + # Nothing of ours is there to record, and no choice to keep. + return + # A games folder is kept only where the next run reads it from a + # record (games_folder_kept): elsewhere the card's own games are. + options = [(flag, value if flag != "--for-games" or not value + else os.path.abspath(value) + if games_folder_kept(os.path.abspath(value), folder) else None) + for flag, value in _INVOCATION.flags(plat)] + if games: + options += [("--for-games", None), + *([("--required-only", None)] if args.required_only else [])] + choice = record_argv(options) + path, setup, problem = write_record(folder, plat, manifest, choice, written) + if problem: + detail(f" {problem}.") + count = len(setup["files"]) + EVENTS.emit("record", platform=plat, folder=str(folder), + path=str(path or record_paths(folder)[0]), + status="not_written" if problem else "written", choice=choice, + date=setup["written"], files=count, + message=f"{problem}." if problem else + f"Recorded {_plural(count, 'file')} and this choice in {path}.") + + +def _pass_offline_left(run: _InstallRun, p: _PlatformPass, fetched: list[dict]) -> None: + """--offline: the files to fetch counted missing, the copies kept to do.""" + # The screen offers no Install for these: the question asked + # to download 6.6 GB that --offline never fetches. With --yes, + # the screen's own install, each one was "downloading", then + # FAILED, and the summary listed it pending and failed at once. + # Counted, never said here: the summary says it once. + # Not done: the summary counts them as missing. + run.files_pending += len(fetched) + run.total_offline += len(fetched) + wrong_ids = {id(entry) for entry in p.mismatched} + run.total_wrong_left += sum(1 for f in fetched if id(f) in wrong_ids) + run.offline_left += [f for f in fetched if id(f) not in wrong_ids] + p.to_download = [f for f in p.to_download if id(f) in p.copies] + + +def _pass_declined(run: _InstallRun, p: _PlatformPass, fetch_size: int) -> bool: + """The size question, where one is asked. True when it was declined.""" + args = run.args + if ( + run.interactive + and not args.yes + and fetch_size >= CONFIRM_FROM_BYTES + and not _confirm( + f"\nCopy {format_size(fetch_size)} from the pack to " + f"{shown_path(p.bios_path)}? [Y/n] " if LOCAL.pack is not None + else f"\nDownload {format_size(fetch_size)} to " + f"{shown_path(p.bios_path)}? [Y/n] " + ) + ): + # A beginner who just passed the c entry was sent to a + # 91-line --help. + print(p.smaller or " Nothing downloaded. --system, --core and --region " + "install less (see --help).") + run.total_up_to_date += len(p.up_to_date) + run.total_declined += len(p.to_download) + run.files_pending += len(p.to_download) + return True + return False + + +def _pass_copy_line(run: _InstallRun, p: _PlatformPass, fetched: list[dict], + lacking: set[int], dl_size: int) -> None: + """The copies from this machine planned, and the line that opens them.""" + copies, bios_index = p.copies, p.bios_index + detail() + for line in copy_plan_lines(p.to_download, copies, bios_index, p.bios_path, + p.files, run.args.verbose, False): + detail(line) + held = len(fetched) - len(lacking) + rest = (f" and {'copying' if LOCAL.pack is not None else 'downloading'} " + f"{held}" if held else "") + where = f" from {LOCAL.pack.name}" if fetched and LOCAL.pack is not None else "" + # Named by the folder they come from, as the line above + # names it: "found on this machine" followed "from E:\". + sources = list(dict.fromkeys(copy.index.label for copy in copies.values())) + named = ", ".join(screen_text(shown_path(label)) for label in sources) + origin = (f"from {named}" if all( + copy.index is not bios_index for copy in copies.values()) + else "found on this machine") + # The size beside what it weighs: after "and downloading + # 19" it read as theirs alone. + sized = f" ({format_size(dl_size)})" + detail(f"\nCopying {_plural(len(copies), 'file')}{'' if rest else sized} " + f"{origin}{rest}{where}{sized if rest else ''}...") + + +def _pass_download_head(run: _InstallRun, p: _PlatformPass, fetched: list[dict], + lacking: set[int], dl_size: int) -> None: + """The lines an install opens on: what comes, from where, to where.""" + args, plat_name, bios_path = run.args, p.plat_name, p.bios_path + if not p.menu: + # What happens and where, the two lines a run without questions + # opens on: the menu's head said them where it was asked. + coming = len(p.to_download) - len(lacking) + p.plan.data_files + weight = dl_size + p.plan.data_bytes + taken = _RECORD_TAKEN.get(plat_name) + print(f"\nInstalling {_plural(coming, 'file')} ({format_size(weight)}) for " + f"{detected_shown(plat_name, bios_path) or p.display}" + + (", what the games need" if p.games_applied else "") + + (f", same choice as on {record_day(taken)}" if taken else "") + ".") + print(f"BIOS folder: {shown_path(bios_path)}") + OUTPUT.where_said = True + if p.unread: + # A file of the user's that could not be read is said in + # every mode: it was expected to be copied. + print() + for line in unreadable_lines(p.unread, args.verbose): + print(line) + if p.copies: + _pass_copy_line(run, p, fetched, lacking, dl_size) + elif LOCAL.pack is not None: + # The files the pack holds: "Copying 23 files (85.0 KB)" sat + # beside the size of 20. + detail(f"\nCopying {_plural(len(p.to_download) - len(lacking), 'file')} " + f"({format_size(dl_size)}) from {LOCAL.pack.name}...") + else: + detail(f"\nDownloading {len(p.to_download)} files ({format_size(dl_size)})...") + detail(" Press Ctrl+C to stop. Running the same command again " + "carries on from here.") + + +def _pass_make_folder(run: _InstallRun, p: _PlatformPass, written: int) -> bool: + """The space checked and the BIOS folder made. True when it was created.""" + plat_name, bios_path = p.plat_name, p.bios_path + with run.writes(len(p.to_download)): + # Checked before the folder is created: a run stopped for space + # left an empty BIOS folder behind. The data trees count too, + # written after the files on the same drive. + _check_free_space(bios_path, written, plat_name, + 1 if run.total_downloaded else 2, on_its_card(plat_name, bios_path)) + p.space_checked = True + created = not bios_path.exists() + try: + bios_path.mkdir(parents=True, exist_ok=True) + except OSError as exc: + sys.stdout.flush() + # The documented code for a folder that cannot be written, + # as when it exists read-only. 1 once an earlier platform + # of the run installed something. + raise Refusal( + "dest", "not_writable", plat_name, + f"\nCannot create {bios_path}.", f" {exc.strerror}.", + _write_advice(bios_path, bios_path in run.assumed_dests, plat_name), + code=1 if run.total_downloaded else 2, + message=f"{bios_path} cannot be created: {exc.strerror}", + ) from None + if created: + detail(f" Created {shown_path(bios_path)}") + return created + + +def _pass_fetch(run: _InstallRun, p: _PlatformPass, dl_size: int, created: bool) -> bool: + """The files downloaded or copied and counted. True when interrupted.""" + args, plat_name, bios_path, to_download = run.args, p.plat_name, p.bios_path, p.to_download + progress = Progress(len(to_download), dl_size, run.term) + failed, interrupted = download_files( + to_download, bios_path, jobs=args.jobs, verbose=args.verbose, + term=run.term, progress=progress, copies=p.copies, + ) + if created and not progress.installed: + # Created for files none of which came: not left behind empty. + try: + bios_path.rmdir() + except OSError as exc: + if args.verbose: + print(f" {shown_path(bios_path)} stays: {exc.strerror}", + file=sys.stderr) + run.bulk_lines += p.hint + if plat_name == "romm" and progress.installed: + run.bulk_lines.append(ROMM_SCAN_WORDS) + run.total_downloaded += progress.installed + # The end line tells BIOS files from game data, as the menu + # 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] + run.files_pending += len(to_download) - progress.installed if interrupted \ + else len(failed) + run.total_errors += len(failed) + run.failures.extend(failed) + run.total_bytes += progress.transferred() + run.total_seconds += progress.elapsed() + if interrupted: + run.total_interrupted = True + _remember_install(args, plat_name, bios_path, p.manifest, p.record_files, + p.games_applied and args.for_games is None) + return interrupted + + +def _pass_download(run: _InstallRun, p: _PlatformPass) -> str: + """The missing files installed: "go" carries on with the setup, "next" + moves to the next one, "stop" ends the run.""" + plan = p.plan + fetched = plan.fetched + if _offline_only() and fetched: + _pass_offline_left(run, p, fetched) + fetched = [] + # What the pack does not hold is said before a size is promised: + # a pack older than the list gave "Copy 6.6 GB" and 8358 files + # failed. They are still tried, and fail as + # not in the pack, the size and the question leaving them out. + # Offline there is no pack, so nothing is lacking. + lacking = {id(f) for f in plan.lacking} + if lacking: + print(f"\n {pack_lacks_words(len(lacking), len(fetched))}") + if lacking and len(lacking) == len(p.to_download) and not plan.data_files: + # Nothing here can come from the pack: no "Copying 0 files", no + # folder made, each file failed as not in it. + run.failures.extend((f["dest"], NOT_IN_PACK) for f in p.to_download) + run.total_errors += len(p.to_download) + run.files_pending += len(p.to_download) + run.total_up_to_date += len(p.up_to_date) + return "next" + coming = plan.without_lacking(p.to_download) + dl_size = _bytes(coming) + fetch_size = _bytes(plan.without_lacking(fetched)) + if not p.to_download: + run.total_up_to_date += len(p.up_to_date) + if _offline_only(): + for _entry, (_root, needed, present) in p.data_states: + run.total_up_to_date += present + run.total_offline += len(needed) + run.files_pending += len(needed) + return "next" + if _pass_declined(run, p, fetch_size): + return "next" + EVENTS.emit("download", platform=p.plat_name, files=len(p.to_download), bytes=dl_size) + _pass_download_head(run, p, fetched, lacking, dl_size) + created = _pass_make_folder(run, p, bytes_written(coming, p.data_states)) + return "stop" if _pass_fetch(run, p, dl_size, created) else "go" + + # --- installer/run_files.py -------------------------------------------------- def _system_label(name: str, manifest: dict | None) -> str: @@ -23946,434 +24378,6 @@ def _check_run_cores(run: _InstallRun) -> None: # --- installer/run.py -------------------------------------------------------- -def _remember_install(args: argparse.Namespace, plat: str, folder: Path, manifest: dict, - written: list[dict], games: bool) -> None: - """Record what this install placed in folder and the choice it made, - games being the card's games applied with no --for-games.""" - if not written and setup_record(plat, folder)[0] is None: - # Nothing of ours is there to record, and no choice to keep. - return - # A games folder is kept only where the next run reads it from a - # record (games_folder_kept): elsewhere the card's own games are. - options = [(flag, value if flag != "--for-games" or not value - else os.path.abspath(value) - if games_folder_kept(os.path.abspath(value), folder) else None) - for flag, value in _INVOCATION.flags(plat)] - if games: - options += [("--for-games", None), - *([("--required-only", None)] if args.required_only else [])] - choice = record_argv(options) - path, setup, problem = write_record(folder, plat, manifest, choice, written) - if problem: - detail(f" {problem}.") - count = len(setup["files"]) - EVENTS.emit("record", platform=plat, folder=str(folder), - path=str(path or record_paths(folder)[0]), - status="not_written" if problem else "written", choice=choice, - date=setup["written"], files=count, - message=f"{problem}." if problem else - f"Recorded {_plural(count, 'file')} and this choice in {path}.") - - -def _drop_stale_parts(bios_path: Path, entries: list[dict]) -> None: - """Remove the partial copy left beside each file now in place.""" - for entry in entries: - try: - stale = _entry_path(bios_path, entry) - except ValueError: - continue - stale = stale.parent / f".{stale.name}.part" - if stale.is_file(): - stale.unlink() - - -def _pass_check_existing(run: _InstallRun, p: _PlatformPass) -> None: - """The setup's folder checked, and where each missing file comes from.""" - args, bios_path, files = run.args, p.bios_path, p.files - detail("\nChecking existing files...") - to_download, up_to_date, mismatched = check_local( - files, bios_path, jobs=args.jobs, term=run.term - ) - present = len(up_to_date) + len(mismatched) - # The screen's words: "0/22 present (0 verified, 0 wrong hash)" - # beside its "0 in place, 22 missing, 0 wrong copies". The data files - # the head counts are among them, as the screen counts them. - wrong = len(mismatched) - # Each data tree read and hashed once in the run: the count here, - # the check, the events, the plan and the install read this. - p.data_states = data_states = [(entry, data_directory_state(entry, bios_path)) - for entry in p.data_dirs] - head_reads_done() - p.trees_missing = trees_missing = sum(len(state[1]) for _entry, state in data_states) - trees_held = p.head_data - trees_missing - detail(f" {len(up_to_date) + trees_held} in place, " - f"{p.run_counts.files - present + trees_missing} missing, " - f"{_plural(wrong, 'wrong copy')}") - - # A partial copy left by an interrupted run is useless once the file - # is in place: it goes. - _drop_stale_parts(bios_path, up_to_date) - - # Mismatched files need re-download - to_download.extend(mismatched) - p.to_download, p.up_to_date, p.mismatched = to_download, up_to_date, mismatched - # The files this machine already holds: misplaced in the BIOS folder - # (bios/bios/, a pack extracted into a folder of its own, a name in - # capitals, still zipped), or in a folder named with --from. - p.bios_index = bios_index = (bios_folder_index(bios_path, files, up_to_date) - if to_download else None) - if bios_index is not None: - run.bios_indexes.append(bios_index) - p.copies = copies = plan_local_copies(to_download, bios_path, bios_index, LOCAL.folders) - p.plan = plan = fetch_plan(to_download, copies, data_states) - p.unread = unread = unreadable_copies(to_download, copies, LOCAL.folders) - selection = p.selection - p.hint = [] if LOCAL.pack is not None else bulk_hint( - to_download, p.manifest, - systems_chosen=bool(selection and selection[0]), - cores_chosen=bool((selection and selection[1]) or args.emulator - or args.installed_cores or p.target), - accepted=p.core_choices, - ) - - if EVENTS.on: - # What the run would write, as _pass_download holds it against the - # free space: the screen's plan warns on this number. - _emit_check( - p.plat_name, p.manifest, bios_path, - CheckTally(files, up_to_date, mismatched, - sum(len(state[1]) for _entry, state in data_states), - len(p.omitted_files), - sum(data_fetch_bytes(entry, state[1]) for entry, state in data_states), - bytes_written(plan.without_lacking(to_download), data_states)), - chosen=selection[0] if selection else None, - ) - emit_fetch_plan(p.plat_name, plan) - emit_copies(p.plat_name, to_download, copies, bios_index, bios_path, files) - emit_unreadable(p.plat_name, unread) - run.total_verified += len(up_to_date) - - -def _pass_check_missing(run: _InstallRun, p: _PlatformPass) -> None: - """--check: the files not in place named, and how to get them.""" - args, bios_path = run.args, p.bios_path - to_download, mismatched, copies, plan = p.to_download, p.mismatched, p.copies, p.plan - # Named, not only counted: a user looking for the one bad - # BIOS learned "1 files need downloading" and nothing else. - # A wrong hash comes first and always in full: listed after - # 8000 missing files, it hid behind "... and 8059 more". - wrong = {id(entry) for entry in mismatched} - missing = [entry for entry in to_download if id(entry) not in wrong] - # A pack extracted from some of its parts: the part is named - # before the hundreds of files it holds. - for line in split_pack_lines(bios_path): - print(line) - offline = _offline_only() - # What the pack lacks is said before the count, as the - # screen says it. - if plan.lacking: - print(f"\n {pack_lacks_words(len(plan.lacking), len(plan.fetched))}") - # One total with the count above it, the data files among - # them as the screen counts them: "0 in place, 10805 missing" - # stood over "8164 files to download". - # The count and the folder by default, each file with - # --verbose: 20 paths hid the line saying what to do. - print(f"\n {_plural(len(to_download) + p.trees_missing, 'file')} " - + ("not in place." if offline or LOCAL.pack is not None - else "to download.")) - for line in check_lines(missing, mismatched, p.files, p.manifest, bios_path, - args.verbose, CheckHeld(p.up_to_date, p.bios_index, copies)): - print(line) - for line in unreadable_lines(p.unread, args.verbose): - print(line) - print(f" BIOS folder: {shown_path(bios_path)}") - # The data files need the internet too: offline, "8164 files - # need the internet" stood under "10805 files not in place". - print(_check_fetch_line(len(plan.fetched) + plan.data_files, - "the BIOS folder", len(plan.lacking), bool(mismatched))) - run.check_pending += len(to_download) - - -def _pass_check_report(run: _InstallRun, p: _PlatformPass) -> None: - """--check: what the setup's folder holds and lacks.""" - args, plat_name, bios_path = run.args, p.plat_name, p.bios_path - if p.to_download: - _pass_check_missing(run, p) - elif p.trees_missing: - # The screen's headline: "Everything is in place." stood - # above "0/169 data files present" and exit code 1. - print(f"\n {_plural(p.trees_missing, 'data file')} to fetch") - else: - print(f"\n {EVERYTHING_IN_PLACE}") - print(f" BIOS folder: {shown_path(bios_path)}") - if plat_name in _RECORD_TAKEN: - # The files counted are the recorded choice's, not the list's. - print(f" {record_menu_words(_RECORD_TAKEN[plat_name])} " - "--all-files checks every file.") - absent = _absent_required(p.omitted_files, bios_path) - # The collection cannot supply these, so they leave the exit - # code alone, but a user asking why a game will not start needs - # their count, and with --verbose their names, and which system - # and emulator each one is for. - if absent and not OUTPUT.verbose: - print(f" {needed_absent_words(len(absent), '--verbose')}") - for line in _needed_lines( - absent, "Not in the collection and absent here, needed to start an emulator", - every=args.verbose, - ): - detail(line) - for entry, (_root, needed, present) in p.data_states: - if needed: - detail(f" {entry['ref']}: {present}/{len(entry['files'])} data files " - f"present, {len(needed)} to fetch") - run.check_pending += len(needed) - - -def _pass_dry_run(run: _InstallRun, p: _PlatformPass) -> None: - """--dry-run: the plan of what an install would write.""" - args, bios_path, to_download, copies = run.args, p.bios_path, p.to_download, p.copies - run.files_pending += len(to_download) - trees = [(entry, state[1]) for entry, state in p.data_states] - # A data file in place with other contents is kept like a BIOS file. - kept = plan_kept(p.mismatched + [ - {"dest": f"{entry['dest']}/{rel}" if entry.get("dest") else rel} - for entry, needed in trees for rel in needed - ], bios_path) - plan = p.plan - # Said before the plan promises a count and a size, as an - # install says it: the dry run promised 23 files where the pack - # held 20. - if plan.lacking: - print(f"\n {pack_lacks_words(len(plan.lacking), len(plan.fetched))}") - _print_plan(plan.coming, bios_path, run.term, - trees, kept, copy_plan_lines(to_download, copies, p.bios_index, - bios_path, p.files, args.verbose, True), - verbose=args.verbose, manifest=p.manifest) - if p.plat_name in _RECORD_TAKEN: - print(f" {record_menu_words(_RECORD_TAKEN[p.plat_name])} " - "--all-files lists every file.") - for line in unreadable_lines(p.unread, args.verbose): - print(line) - for line in p.hint: - print(line) - - -def _pass_offline_left(run: _InstallRun, p: _PlatformPass, fetched: list[dict]) -> None: - """--offline: the files to fetch counted missing, the copies kept to do.""" - # The screen offers no Install for these: the question asked - # to download 6.6 GB that --offline never fetches. With --yes, - # the screen's own install, each one was "downloading", then - # FAILED, and the summary listed it pending and failed at once. - # Counted, never said here: the summary says it once. - # Not done: the summary counts them as missing. - run.files_pending += len(fetched) - run.total_offline += len(fetched) - wrong_ids = {id(entry) for entry in p.mismatched} - run.total_wrong_left += sum(1 for f in fetched if id(f) in wrong_ids) - run.offline_left += [f for f in fetched if id(f) not in wrong_ids] - p.to_download = [f for f in p.to_download if id(f) in p.copies] - - -def _pass_declined(run: _InstallRun, p: _PlatformPass, fetch_size: int) -> bool: - """The size question, where one is asked. True when it was declined.""" - args = run.args - if ( - run.interactive - and not args.yes - and fetch_size >= CONFIRM_FROM_BYTES - and not _confirm( - f"\nCopy {format_size(fetch_size)} from the pack to " - f"{shown_path(p.bios_path)}? [Y/n] " if LOCAL.pack is not None - else f"\nDownload {format_size(fetch_size)} to " - f"{shown_path(p.bios_path)}? [Y/n] " - ) - ): - # A beginner who just passed the c entry was sent to a - # 91-line --help. - print(p.smaller or " Nothing downloaded. --system, --core and --region " - "install less (see --help).") - run.total_up_to_date += len(p.up_to_date) - run.total_declined += len(p.to_download) - run.files_pending += len(p.to_download) - return True - return False - - -def _pass_copy_line(run: _InstallRun, p: _PlatformPass, fetched: list[dict], - lacking: set[int], dl_size: int) -> None: - """The copies from this machine planned, and the line that opens them.""" - copies, bios_index = p.copies, p.bios_index - detail() - for line in copy_plan_lines(p.to_download, copies, bios_index, p.bios_path, - p.files, run.args.verbose, False): - detail(line) - held = len(fetched) - len(lacking) - rest = (f" and {'copying' if LOCAL.pack is not None else 'downloading'} " - f"{held}" if held else "") - where = f" from {LOCAL.pack.name}" if fetched and LOCAL.pack is not None else "" - # Named by the folder they come from, as the line above - # names it: "found on this machine" followed "from E:\". - sources = list(dict.fromkeys(copy.index.label for copy in copies.values())) - named = ", ".join(screen_text(shown_path(label)) for label in sources) - origin = (f"from {named}" if all( - copy.index is not bios_index for copy in copies.values()) - else "found on this machine") - # The size beside what it weighs: after "and downloading - # 19" it read as theirs alone. - sized = f" ({format_size(dl_size)})" - detail(f"\nCopying {_plural(len(copies), 'file')}{'' if rest else sized} " - f"{origin}{rest}{where}{sized if rest else ''}...") - - -def _pass_download_head(run: _InstallRun, p: _PlatformPass, fetched: list[dict], - lacking: set[int], dl_size: int) -> None: - """The lines an install opens on: what comes, from where, to where.""" - args, plat_name, bios_path = run.args, p.plat_name, p.bios_path - if not p.menu: - # What happens and where, the two lines a run without questions - # opens on: the menu's head said them where it was asked. - coming = len(p.to_download) - len(lacking) + p.plan.data_files - weight = dl_size + p.plan.data_bytes - taken = _RECORD_TAKEN.get(plat_name) - print(f"\nInstalling {_plural(coming, 'file')} ({format_size(weight)}) for " - f"{detected_shown(plat_name, bios_path) or p.display}" - + (", what the games need" if p.games_applied else "") - + (f", same choice as on {record_day(taken)}" if taken else "") + ".") - print(f"BIOS folder: {shown_path(bios_path)}") - OUTPUT.where_said = True - if p.unread: - # A file of the user's that could not be read is said in - # every mode: it was expected to be copied. - print() - for line in unreadable_lines(p.unread, args.verbose): - print(line) - if p.copies: - _pass_copy_line(run, p, fetched, lacking, dl_size) - elif LOCAL.pack is not None: - # The files the pack holds: "Copying 23 files (85.0 KB)" sat - # beside the size of 20. - detail(f"\nCopying {_plural(len(p.to_download) - len(lacking), 'file')} " - f"({format_size(dl_size)}) from {LOCAL.pack.name}...") - else: - detail(f"\nDownloading {len(p.to_download)} files ({format_size(dl_size)})...") - detail(" Press Ctrl+C to stop. Running the same command again " - "carries on from here.") - - -def _pass_make_folder(run: _InstallRun, p: _PlatformPass, written: int) -> bool: - """The space checked and the BIOS folder made. True when it was created.""" - plat_name, bios_path = p.plat_name, p.bios_path - with run.writes(len(p.to_download)): - # Checked before the folder is created: a run stopped for space - # left an empty BIOS folder behind. The data trees count too, - # written after the files on the same drive. - _check_free_space(bios_path, written, plat_name, - 1 if run.total_downloaded else 2, on_its_card(plat_name, bios_path)) - p.space_checked = True - created = not bios_path.exists() - try: - bios_path.mkdir(parents=True, exist_ok=True) - except OSError as exc: - sys.stdout.flush() - # The documented code for a folder that cannot be written, - # as when it exists read-only. 1 once an earlier platform - # of the run installed something. - raise Refusal( - "dest", "not_writable", plat_name, - f"\nCannot create {bios_path}.", f" {exc.strerror}.", - _write_advice(bios_path, bios_path in run.assumed_dests, plat_name), - code=1 if run.total_downloaded else 2, - message=f"{bios_path} cannot be created: {exc.strerror}", - ) from None - if created: - detail(f" Created {shown_path(bios_path)}") - return created - - -def _pass_fetch(run: _InstallRun, p: _PlatformPass, dl_size: int, created: bool) -> bool: - """The files downloaded or copied and counted. True when interrupted.""" - args, plat_name, bios_path, to_download = run.args, p.plat_name, p.bios_path, p.to_download - progress = Progress(len(to_download), dl_size, run.term) - failed, interrupted = download_files( - to_download, bios_path, jobs=args.jobs, verbose=args.verbose, - term=run.term, progress=progress, copies=p.copies, - ) - if created and not progress.installed: - # Created for files none of which came: not left behind empty. - try: - bios_path.rmdir() - except OSError as exc: - if args.verbose: - print(f" {shown_path(bios_path)} stays: {exc.strerror}", - file=sys.stderr) - run.bulk_lines += p.hint - if plat_name == "romm" and progress.installed: - run.bulk_lines.append(ROMM_SCAN_WORDS) - run.total_downloaded += progress.installed - # The end line tells BIOS files from game data, as the menu - # 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] - run.files_pending += len(to_download) - progress.installed if interrupted \ - else len(failed) - run.total_errors += len(failed) - run.failures.extend(failed) - run.total_bytes += progress.transferred() - run.total_seconds += progress.elapsed() - if interrupted: - run.total_interrupted = True - _remember_install(args, plat_name, bios_path, p.manifest, p.record_files, - p.games_applied and args.for_games is None) - return interrupted - - -def _pass_download(run: _InstallRun, p: _PlatformPass) -> str: - """The missing files installed: "go" carries on with the setup, "next" - moves to the next one, "stop" ends the run.""" - plan = p.plan - fetched = plan.fetched - if _offline_only() and fetched: - _pass_offline_left(run, p, fetched) - fetched = [] - # What the pack does not hold is said before a size is promised: - # a pack older than the list gave "Copy 6.6 GB" and 8358 files - # failed. They are still tried, and fail as - # not in the pack, the size and the question leaving them out. - # Offline there is no pack, so nothing is lacking. - lacking = {id(f) for f in plan.lacking} - if lacking: - print(f"\n {pack_lacks_words(len(lacking), len(fetched))}") - if lacking and len(lacking) == len(p.to_download) and not plan.data_files: - # Nothing here can come from the pack: no "Copying 0 files", no - # folder made, each file failed as not in it. - run.failures.extend((f["dest"], NOT_IN_PACK) for f in p.to_download) - run.total_errors += len(p.to_download) - run.files_pending += len(p.to_download) - run.total_up_to_date += len(p.up_to_date) - return "next" - coming = plan.without_lacking(p.to_download) - dl_size = _bytes(coming) - fetch_size = _bytes(plan.without_lacking(fetched)) - if not p.to_download: - run.total_up_to_date += len(p.up_to_date) - if _offline_only(): - for _entry, (_root, needed, present) in p.data_states: - run.total_up_to_date += present - run.total_offline += len(needed) - run.files_pending += len(needed) - return "next" - if _pass_declined(run, p, fetch_size): - return "next" - EVENTS.emit("download", platform=p.plat_name, files=len(p.to_download), bytes=dl_size) - _pass_download_head(run, p, fetched, lacking, dl_size) - created = _pass_make_folder(run, p, bytes_written(coming, p.data_states)) - return "stop" if _pass_fetch(run, p, dl_size, created) else "go" - - def _pass_install_tree(run: _InstallRun, p: _PlatformPass, entry: dict, state: tuple[Path, dict[str, dict], int]) -> None: """One data tree fetched or copied, and its line.""" diff --git a/install.sh b/install.sh index cee8a19ea..13ad5b3f1 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="d91de8c232409f6c324a86354f21a62972fbf629c088b68fdcc295233263b409" +DEFAULT_INSTALL_SHA256="bbc5e1c6597873856565869e1a7f8ef376bc698b9d04e7301a3ae56635cfafbd" # 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 c4a4aab83..8b37ee563 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": 1503267, - "sha256": "d91de8c232409f6c324a86354f21a62972fbf629c088b68fdcc295233263b409", + "size": 1503429, + "sha256": "bbc5e1c6597873856565869e1a7f8ef376bc698b9d04e7301a3ae56635cfafbd", "executable": false }, { @@ -71,8 +71,8 @@ "muos": { "archive": { "dest": "ARCHIVE/RetroBIOS.muxapp", - "size": 1556892, - "sha256": "2ecdcf3267356eb35390ef379a242ea33365ba18041df8161716ba8a24357190" + "size": 1557054, + "sha256": "faa3e9a8d39ebd57654ed3daba9b3de730800fde723f5e97b595d9edba950c74" }, "members": [ { @@ -92,8 +92,8 @@ { "name": "RetroBIOS/install.py", "repo_path": "install.py", - "size": 1503267, - "sha256": "d91de8c232409f6c324a86354f21a62972fbf629c088b68fdcc295233263b409", + "size": 1503429, + "sha256": "bbc5e1c6597873856565869e1a7f8ef376bc698b9d04e7301a3ae56635cfafbd", "executable": false }, { @@ -166,8 +166,8 @@ { "dest": ".config/modules/retrobios/install.py", "repo_path": "install.py", - "size": 1503267, - "sha256": "d91de8c232409f6c324a86354f21a62972fbf629c088b68fdcc295233263b409", + "size": 1503429, + "sha256": "bbc5e1c6597873856565869e1a7f8ef376bc698b9d04e7301a3ae56635cfafbd", "executable": false }, { diff --git a/installer/run.py b/installer/run.py index 3ea8f15ee..961667a04 100644 --- a/installer/run.py +++ b/installer/run.py @@ -1,31 +1,18 @@ -"""One install run: each setup's files checked, planned or installed, then its record and summary.""" +"""One install run: each setup applied, its trees and standalone copies, then its record and summary.""" from __future__ import annotations import argparse -import os import sys from pathlib import Path from typing import TYPE_CHECKING, TextIO -from installer.console import OUTPUT, Progress, _confirm, detail -from installer.datadirs import data_directory_state, data_fetch_bytes, install_data_directory +from installer.console import Progress, detail +from installer.datadirs import install_data_directory from installer.destination import _missing_dest, _refuse_closed, _refuse_file, on_its_card from installer.detect_launchbox import launchbox_bios_dirs, launchbox_root -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.local_copies import ( - copy_plan_lines, - emit_copies, - emit_unreadable, - plan_local_copies, - unreadable_copies, - unreadable_lines, -) from installer.from_folders import sources_line from installer.frontend_folders import _retroarch_config_at from installer.handheld_app import finish_app @@ -34,33 +21,21 @@ from installer.install_record import ( _RECORD_TAKEN, apply_record, choice_given, - games_folder_kept, - record_argv, - record_day, record_file, - record_menu_words, - record_paths, - setup_record, - write_record, ) from installer.invocation import _INVOCATION -from installer.local_check import check_local, head_reads_done -from installer.offline import LOCAL, _offline_only, offline_named +from installer.offline import LOCAL, offline_named from installer.outcome import ( EVERYTHING_IN_PLACE, OutcomeDetails, - _check_fetch_line, _report_outcome, - _write_advice, ) from installer.pack import run_pack -from installer.pack_parts import split_pack_lines -from installer.pack_source import NOT_IN_PACK, pack_lacks_words -from installer.paths import _entry_path, shown_path -from installer.plan import CONFIRM_FROM_BYTES, _check_free_space, _print_plan, bulk_hint +from installer.paths import shown_path +from installer.plan import _check_free_space from installer.platforms import display_name from installer.refusal import Refusal -from installer.romm import ROMM_SCAN_WORDS, _check_run_romm, _pass_romm_layout +from installer.romm import _check_run_romm, _pass_romm_layout from installer.run_files import _select_setup_files from installer.run_setups import ( _check_run_cores, @@ -70,454 +45,22 @@ from installer.run_setups import ( _print_platform_list, _start_install, ) -from installer.safe_replace import KEPT, NOT_KEPT, plan_kept +from installer.safe_replace import KEPT, NOT_KEPT from installer.space import bytes_written from installer.standalone import do_standalone_copies, preview_standalone, standalone_folders_here, standalone_plan from installer.tally import ( - CheckTally, - _absent_required, - _bytes, - _emit_check, _left_out_events, - _needed_lines, _skipped, - needed_absent_words, tally, ) -from installer.text import _plural, agree, format_size, screen_text +from installer.text import agree if TYPE_CHECKING: from installer.folder_index import FolderIndex from installer.run_files import _PlatformPass from installer.run_setups import _InstallRun - - -def _remember_install(args: argparse.Namespace, plat: str, folder: Path, manifest: dict, - written: list[dict], games: bool) -> None: - """Record what this install placed in folder and the choice it made, - games being the card's games applied with no --for-games.""" - if not written and setup_record(plat, folder)[0] is None: - # Nothing of ours is there to record, and no choice to keep. - return - # A games folder is kept only where the next run reads it from a - # record (games_folder_kept): elsewhere the card's own games are. - options = [(flag, value if flag != "--for-games" or not value - else os.path.abspath(value) - if games_folder_kept(os.path.abspath(value), folder) else None) - for flag, value in _INVOCATION.flags(plat)] - if games: - options += [("--for-games", None), - *([("--required-only", None)] if args.required_only else [])] - choice = record_argv(options) - path, setup, problem = write_record(folder, plat, manifest, choice, written) - if problem: - detail(f" {problem}.") - count = len(setup["files"]) - EVENTS.emit("record", platform=plat, folder=str(folder), - path=str(path or record_paths(folder)[0]), - status="not_written" if problem else "written", choice=choice, - date=setup["written"], files=count, - message=f"{problem}." if problem else - f"Recorded {_plural(count, 'file')} and this choice in {path}.") - - -def _drop_stale_parts(bios_path: Path, entries: list[dict]) -> None: - """Remove the partial copy left beside each file now in place.""" - for entry in entries: - try: - stale = _entry_path(bios_path, entry) - except ValueError: - continue - stale = stale.parent / f".{stale.name}.part" - if stale.is_file(): - stale.unlink() - - -def _pass_check_existing(run: _InstallRun, p: _PlatformPass) -> None: - """The setup's folder checked, and where each missing file comes from.""" - args, bios_path, files = run.args, p.bios_path, p.files - detail("\nChecking existing files...") - to_download, up_to_date, mismatched = check_local( - files, bios_path, jobs=args.jobs, term=run.term - ) - present = len(up_to_date) + len(mismatched) - # The screen's words: "0/22 present (0 verified, 0 wrong hash)" - # beside its "0 in place, 22 missing, 0 wrong copies". The data files - # the head counts are among them, as the screen counts them. - wrong = len(mismatched) - # Each data tree read and hashed once in the run: the count here, - # the check, the events, the plan and the install read this. - p.data_states = data_states = [(entry, data_directory_state(entry, bios_path)) - for entry in p.data_dirs] - head_reads_done() - p.trees_missing = trees_missing = sum(len(state[1]) for _entry, state in data_states) - trees_held = p.head_data - trees_missing - detail(f" {len(up_to_date) + trees_held} in place, " - f"{p.run_counts.files - present + trees_missing} missing, " - f"{_plural(wrong, 'wrong copy')}") - - # A partial copy left by an interrupted run is useless once the file - # is in place: it goes. - _drop_stale_parts(bios_path, up_to_date) - - # Mismatched files need re-download - to_download.extend(mismatched) - p.to_download, p.up_to_date, p.mismatched = to_download, up_to_date, mismatched - # The files this machine already holds: misplaced in the BIOS folder - # (bios/bios/, a pack extracted into a folder of its own, a name in - # capitals, still zipped), or in a folder named with --from. - p.bios_index = bios_index = (bios_folder_index(bios_path, files, up_to_date) - if to_download else None) - if bios_index is not None: - run.bios_indexes.append(bios_index) - p.copies = copies = plan_local_copies(to_download, bios_path, bios_index, LOCAL.folders) - p.plan = plan = fetch_plan(to_download, copies, data_states) - p.unread = unread = unreadable_copies(to_download, copies, LOCAL.folders) - selection = p.selection - p.hint = [] if LOCAL.pack is not None else bulk_hint( - to_download, p.manifest, - systems_chosen=bool(selection and selection[0]), - cores_chosen=bool((selection and selection[1]) or args.emulator - or args.installed_cores or p.target), - accepted=p.core_choices, - ) - - if EVENTS.on: - # What the run would write, as _pass_download holds it against the - # free space: the screen's plan warns on this number. - _emit_check( - p.plat_name, p.manifest, bios_path, - CheckTally(files, up_to_date, mismatched, - sum(len(state[1]) for _entry, state in data_states), - len(p.omitted_files), - sum(data_fetch_bytes(entry, state[1]) for entry, state in data_states), - bytes_written(plan.without_lacking(to_download), data_states)), - chosen=selection[0] if selection else None, - ) - emit_fetch_plan(p.plat_name, plan) - emit_copies(p.plat_name, to_download, copies, bios_index, bios_path, files) - emit_unreadable(p.plat_name, unread) - run.total_verified += len(up_to_date) - - -def _pass_check_missing(run: _InstallRun, p: _PlatformPass) -> None: - """--check: the files not in place named, and how to get them.""" - args, bios_path = run.args, p.bios_path - to_download, mismatched, copies, plan = p.to_download, p.mismatched, p.copies, p.plan - # Named, not only counted: a user looking for the one bad - # BIOS learned "1 files need downloading" and nothing else. - # A wrong hash comes first and always in full: listed after - # 8000 missing files, it hid behind "... and 8059 more". - wrong = {id(entry) for entry in mismatched} - missing = [entry for entry in to_download if id(entry) not in wrong] - # A pack extracted from some of its parts: the part is named - # before the hundreds of files it holds. - for line in split_pack_lines(bios_path): - print(line) - offline = _offline_only() - # What the pack lacks is said before the count, as the - # screen says it. - if plan.lacking: - print(f"\n {pack_lacks_words(len(plan.lacking), len(plan.fetched))}") - # One total with the count above it, the data files among - # them as the screen counts them: "0 in place, 10805 missing" - # stood over "8164 files to download". - # The count and the folder by default, each file with - # --verbose: 20 paths hid the line saying what to do. - print(f"\n {_plural(len(to_download) + p.trees_missing, 'file')} " - + ("not in place." if offline or LOCAL.pack is not None - else "to download.")) - for line in check_lines(missing, mismatched, p.files, p.manifest, bios_path, - args.verbose, CheckHeld(p.up_to_date, p.bios_index, copies)): - print(line) - for line in unreadable_lines(p.unread, args.verbose): - print(line) - print(f" BIOS folder: {shown_path(bios_path)}") - # The data files need the internet too: offline, "8164 files - # need the internet" stood under "10805 files not in place". - print(_check_fetch_line(len(plan.fetched) + plan.data_files, - "the BIOS folder", len(plan.lacking), bool(mismatched))) - run.check_pending += len(to_download) - - -def _pass_check_report(run: _InstallRun, p: _PlatformPass) -> None: - """--check: what the setup's folder holds and lacks.""" - args, plat_name, bios_path = run.args, p.plat_name, p.bios_path - if p.to_download: - _pass_check_missing(run, p) - elif p.trees_missing: - # The screen's headline: "Everything is in place." stood - # above "0/169 data files present" and exit code 1. - print(f"\n {_plural(p.trees_missing, 'data file')} to fetch") - else: - print(f"\n {EVERYTHING_IN_PLACE}") - print(f" BIOS folder: {shown_path(bios_path)}") - if plat_name in _RECORD_TAKEN: - # The files counted are the recorded choice's, not the list's. - print(f" {record_menu_words(_RECORD_TAKEN[plat_name])} " - "--all-files checks every file.") - absent = _absent_required(p.omitted_files, bios_path) - # The collection cannot supply these, so they leave the exit - # code alone, but a user asking why a game will not start needs - # their count, and with --verbose their names, and which system - # and emulator each one is for. - if absent and not OUTPUT.verbose: - print(f" {needed_absent_words(len(absent), '--verbose')}") - for line in _needed_lines( - absent, "Not in the collection and absent here, needed to start an emulator", - every=args.verbose, - ): - detail(line) - for entry, (_root, needed, present) in p.data_states: - if needed: - detail(f" {entry['ref']}: {present}/{len(entry['files'])} data files " - f"present, {len(needed)} to fetch") - run.check_pending += len(needed) - - -def _pass_dry_run(run: _InstallRun, p: _PlatformPass) -> None: - """--dry-run: the plan of what an install would write.""" - args, bios_path, to_download, copies = run.args, p.bios_path, p.to_download, p.copies - run.files_pending += len(to_download) - trees = [(entry, state[1]) for entry, state in p.data_states] - # A data file in place with other contents is kept like a BIOS file. - kept = plan_kept(p.mismatched + [ - {"dest": f"{entry['dest']}/{rel}" if entry.get("dest") else rel} - for entry, needed in trees for rel in needed - ], bios_path) - plan = p.plan - # Said before the plan promises a count and a size, as an - # install says it: the dry run promised 23 files where the pack - # held 20. - if plan.lacking: - print(f"\n {pack_lacks_words(len(plan.lacking), len(plan.fetched))}") - _print_plan(plan.coming, bios_path, run.term, - trees, kept, copy_plan_lines(to_download, copies, p.bios_index, - bios_path, p.files, args.verbose, True), - verbose=args.verbose, manifest=p.manifest) - if p.plat_name in _RECORD_TAKEN: - print(f" {record_menu_words(_RECORD_TAKEN[p.plat_name])} " - "--all-files lists every file.") - for line in unreadable_lines(p.unread, args.verbose): - print(line) - for line in p.hint: - print(line) - - -def _pass_offline_left(run: _InstallRun, p: _PlatformPass, fetched: list[dict]) -> None: - """--offline: the files to fetch counted missing, the copies kept to do.""" - # The screen offers no Install for these: the question asked - # to download 6.6 GB that --offline never fetches. With --yes, - # the screen's own install, each one was "downloading", then - # FAILED, and the summary listed it pending and failed at once. - # Counted, never said here: the summary says it once. - # Not done: the summary counts them as missing. - run.files_pending += len(fetched) - run.total_offline += len(fetched) - wrong_ids = {id(entry) for entry in p.mismatched} - run.total_wrong_left += sum(1 for f in fetched if id(f) in wrong_ids) - run.offline_left += [f for f in fetched if id(f) not in wrong_ids] - p.to_download = [f for f in p.to_download if id(f) in p.copies] - - -def _pass_declined(run: _InstallRun, p: _PlatformPass, fetch_size: int) -> bool: - """The size question, where one is asked. True when it was declined.""" - args = run.args - if ( - run.interactive - and not args.yes - and fetch_size >= CONFIRM_FROM_BYTES - and not _confirm( - f"\nCopy {format_size(fetch_size)} from the pack to " - f"{shown_path(p.bios_path)}? [Y/n] " if LOCAL.pack is not None - else f"\nDownload {format_size(fetch_size)} to " - f"{shown_path(p.bios_path)}? [Y/n] " - ) - ): - # A beginner who just passed the c entry was sent to a - # 91-line --help. - print(p.smaller or " Nothing downloaded. --system, --core and --region " - "install less (see --help).") - run.total_up_to_date += len(p.up_to_date) - run.total_declined += len(p.to_download) - run.files_pending += len(p.to_download) - return True - return False - - -def _pass_copy_line(run: _InstallRun, p: _PlatformPass, fetched: list[dict], - lacking: set[int], dl_size: int) -> None: - """The copies from this machine planned, and the line that opens them.""" - copies, bios_index = p.copies, p.bios_index - detail() - for line in copy_plan_lines(p.to_download, copies, bios_index, p.bios_path, - p.files, run.args.verbose, False): - detail(line) - held = len(fetched) - len(lacking) - rest = (f" and {'copying' if LOCAL.pack is not None else 'downloading'} " - f"{held}" if held else "") - where = f" from {LOCAL.pack.name}" if fetched and LOCAL.pack is not None else "" - # Named by the folder they come from, as the line above - # names it: "found on this machine" followed "from E:\". - sources = list(dict.fromkeys(copy.index.label for copy in copies.values())) - named = ", ".join(screen_text(shown_path(label)) for label in sources) - origin = (f"from {named}" if all( - copy.index is not bios_index for copy in copies.values()) - else "found on this machine") - # The size beside what it weighs: after "and downloading - # 19" it read as theirs alone. - sized = f" ({format_size(dl_size)})" - detail(f"\nCopying {_plural(len(copies), 'file')}{'' if rest else sized} " - f"{origin}{rest}{where}{sized if rest else ''}...") - - -def _pass_download_head(run: _InstallRun, p: _PlatformPass, fetched: list[dict], - lacking: set[int], dl_size: int) -> None: - """The lines an install opens on: what comes, from where, to where.""" - args, plat_name, bios_path = run.args, p.plat_name, p.bios_path - if not p.menu: - # What happens and where, the two lines a run without questions - # opens on: the menu's head said them where it was asked. - coming = len(p.to_download) - len(lacking) + p.plan.data_files - weight = dl_size + p.plan.data_bytes - taken = _RECORD_TAKEN.get(plat_name) - print(f"\nInstalling {_plural(coming, 'file')} ({format_size(weight)}) for " - f"{detected_shown(plat_name, bios_path) or p.display}" - + (", what the games need" if p.games_applied else "") - + (f", same choice as on {record_day(taken)}" if taken else "") + ".") - print(f"BIOS folder: {shown_path(bios_path)}") - OUTPUT.where_said = True - if p.unread: - # A file of the user's that could not be read is said in - # every mode: it was expected to be copied. - print() - for line in unreadable_lines(p.unread, args.verbose): - print(line) - if p.copies: - _pass_copy_line(run, p, fetched, lacking, dl_size) - elif LOCAL.pack is not None: - # The files the pack holds: "Copying 23 files (85.0 KB)" sat - # beside the size of 20. - detail(f"\nCopying {_plural(len(p.to_download) - len(lacking), 'file')} " - f"({format_size(dl_size)}) from {LOCAL.pack.name}...") - else: - detail(f"\nDownloading {len(p.to_download)} files ({format_size(dl_size)})...") - detail(" Press Ctrl+C to stop. Running the same command again " - "carries on from here.") - - -def _pass_make_folder(run: _InstallRun, p: _PlatformPass, written: int) -> bool: - """The space checked and the BIOS folder made. True when it was created.""" - plat_name, bios_path = p.plat_name, p.bios_path - with run.writes(len(p.to_download)): - # Checked before the folder is created: a run stopped for space - # left an empty BIOS folder behind. The data trees count too, - # written after the files on the same drive. - _check_free_space(bios_path, written, plat_name, - 1 if run.total_downloaded else 2, on_its_card(plat_name, bios_path)) - p.space_checked = True - created = not bios_path.exists() - try: - bios_path.mkdir(parents=True, exist_ok=True) - except OSError as exc: - sys.stdout.flush() - # The documented code for a folder that cannot be written, - # as when it exists read-only. 1 once an earlier platform - # of the run installed something. - raise Refusal( - "dest", "not_writable", plat_name, - f"\nCannot create {bios_path}.", f" {exc.strerror}.", - _write_advice(bios_path, bios_path in run.assumed_dests, plat_name), - code=1 if run.total_downloaded else 2, - message=f"{bios_path} cannot be created: {exc.strerror}", - ) from None - if created: - detail(f" Created {shown_path(bios_path)}") - return created - - -def _pass_fetch(run: _InstallRun, p: _PlatformPass, dl_size: int, created: bool) -> bool: - """The files downloaded or copied and counted. True when interrupted.""" - args, plat_name, bios_path, to_download = run.args, p.plat_name, p.bios_path, p.to_download - progress = Progress(len(to_download), dl_size, run.term) - failed, interrupted = download_files( - to_download, bios_path, jobs=args.jobs, verbose=args.verbose, - term=run.term, progress=progress, copies=p.copies, - ) - if created and not progress.installed: - # Created for files none of which came: not left behind empty. - try: - bios_path.rmdir() - except OSError as exc: - if args.verbose: - print(f" {shown_path(bios_path)} stays: {exc.strerror}", - file=sys.stderr) - run.bulk_lines += p.hint - if plat_name == "romm" and progress.installed: - run.bulk_lines.append(ROMM_SCAN_WORDS) - run.total_downloaded += progress.installed - # The end line tells BIOS files from game data, as the menu - # 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] - run.files_pending += len(to_download) - progress.installed if interrupted \ - else len(failed) - run.total_errors += len(failed) - run.failures.extend(failed) - run.total_bytes += progress.transferred() - run.total_seconds += progress.elapsed() - if interrupted: - run.total_interrupted = True - _remember_install(args, plat_name, bios_path, p.manifest, p.record_files, - p.games_applied and args.for_games is None) - return interrupted - - -def _pass_download(run: _InstallRun, p: _PlatformPass) -> str: - """The missing files installed: "go" carries on with the setup, "next" - moves to the next one, "stop" ends the run.""" - plan = p.plan - fetched = plan.fetched - if _offline_only() and fetched: - _pass_offline_left(run, p, fetched) - fetched = [] - # What the pack does not hold is said before a size is promised: - # a pack older than the list gave "Copy 6.6 GB" and 8358 files - # failed. They are still tried, and fail as - # not in the pack, the size and the question leaving them out. - # Offline there is no pack, so nothing is lacking. - lacking = {id(f) for f in plan.lacking} - if lacking: - print(f"\n {pack_lacks_words(len(lacking), len(fetched))}") - if lacking and len(lacking) == len(p.to_download) and not plan.data_files: - # Nothing here can come from the pack: no "Copying 0 files", no - # folder made, each file failed as not in it. - run.failures.extend((f["dest"], NOT_IN_PACK) for f in p.to_download) - run.total_errors += len(p.to_download) - run.files_pending += len(p.to_download) - run.total_up_to_date += len(p.up_to_date) - return "next" - coming = plan.without_lacking(p.to_download) - dl_size = _bytes(coming) - fetch_size = _bytes(plan.without_lacking(fetched)) - if not p.to_download: - run.total_up_to_date += len(p.up_to_date) - if _offline_only(): - for _entry, (_root, needed, present) in p.data_states: - run.total_up_to_date += present - run.total_offline += len(needed) - run.files_pending += len(needed) - return "next" - if _pass_declined(run, p, fetch_size): - return "next" - EVENTS.emit("download", platform=p.plat_name, files=len(p.to_download), bytes=dl_size) - _pass_download_head(run, p, fetched, lacking, dl_size) - created = _pass_make_folder(run, p, bytes_written(coming, p.data_states)) - return "stop" if _pass_fetch(run, p, dl_size, created) else "go" +from installer.run_check import _pass_check_existing, _pass_check_report, _pass_dry_run +from installer.run_download import _pass_download, _remember_install def _pass_install_tree(run: _InstallRun, p: _PlatformPass, entry: dict, diff --git a/installer/run_check.py b/installer/run_check.py new file mode 100644 index 000000000..a6590c3dd --- /dev/null +++ b/installer/run_check.py @@ -0,0 +1,225 @@ +"""The passes that read a setup: files in place, files missing, and what a dry run would do.""" + +from __future__ import annotations + +from pathlib import Path +from typing import TYPE_CHECKING + +from installer.console import OUTPUT, detail +from installer.datadirs import data_directory_state, data_fetch_bytes +from installer.diagnosis import CheckHeld, bios_folder_index, check_lines +from installer.events import EVENTS +from installer.fetch_plan import emit_fetch_plan, fetch_plan +from installer.install_record import _RECORD_TAKEN, record_menu_words +from installer.local_check import check_local, head_reads_done +from installer.local_copies import ( + copy_plan_lines, + emit_copies, + emit_unreadable, + plan_local_copies, + unreadable_copies, + unreadable_lines, +) +from installer.offline import LOCAL, _offline_only +from installer.outcome import EVERYTHING_IN_PLACE, _check_fetch_line +from installer.pack_parts import split_pack_lines +from installer.pack_source import pack_lacks_words +from installer.paths import _entry_path, shown_path +from installer.plan import _print_plan, bulk_hint +from installer.safe_replace import plan_kept +from installer.space import bytes_written +from installer.tally import ( + CheckTally, + _absent_required, + _emit_check, + _needed_lines, + needed_absent_words, +) +from installer.text import _plural + +if TYPE_CHECKING: + from installer.run_files import _PlatformPass + from installer.run_setups import _InstallRun + + +def _drop_stale_parts(bios_path: Path, entries: list[dict]) -> None: + """Remove the partial copy left beside each file now in place.""" + for entry in entries: + try: + stale = _entry_path(bios_path, entry) + except ValueError: + continue + stale = stale.parent / f".{stale.name}.part" + if stale.is_file(): + stale.unlink() + + +def _pass_check_existing(run: _InstallRun, p: _PlatformPass) -> None: + """The setup's folder checked, and where each missing file comes from.""" + args, bios_path, files = run.args, p.bios_path, p.files + detail("\nChecking existing files...") + to_download, up_to_date, mismatched = check_local( + files, bios_path, jobs=args.jobs, term=run.term + ) + present = len(up_to_date) + len(mismatched) + # The screen's words: "0/22 present (0 verified, 0 wrong hash)" + # beside its "0 in place, 22 missing, 0 wrong copies". The data files + # the head counts are among them, as the screen counts them. + wrong = len(mismatched) + # Each data tree read and hashed once in the run: the count here, + # the check, the events, the plan and the install read this. + p.data_states = data_states = [(entry, data_directory_state(entry, bios_path)) + for entry in p.data_dirs] + head_reads_done() + p.trees_missing = trees_missing = sum(len(state[1]) for _entry, state in data_states) + trees_held = p.head_data - trees_missing + detail(f" {len(up_to_date) + trees_held} in place, " + f"{p.run_counts.files - present + trees_missing} missing, " + f"{_plural(wrong, 'wrong copy')}") + + # A partial copy left by an interrupted run is useless once the file + # is in place: it goes. + _drop_stale_parts(bios_path, up_to_date) + + # Mismatched files need re-download + to_download.extend(mismatched) + p.to_download, p.up_to_date, p.mismatched = to_download, up_to_date, mismatched + # The files this machine already holds: misplaced in the BIOS folder + # (bios/bios/, a pack extracted into a folder of its own, a name in + # capitals, still zipped), or in a folder named with --from. + p.bios_index = bios_index = (bios_folder_index(bios_path, files, up_to_date) + if to_download else None) + if bios_index is not None: + run.bios_indexes.append(bios_index) + p.copies = copies = plan_local_copies(to_download, bios_path, bios_index, LOCAL.folders) + p.plan = plan = fetch_plan(to_download, copies, data_states) + p.unread = unread = unreadable_copies(to_download, copies, LOCAL.folders) + selection = p.selection + p.hint = [] if LOCAL.pack is not None else bulk_hint( + to_download, p.manifest, + systems_chosen=bool(selection and selection[0]), + cores_chosen=bool((selection and selection[1]) or args.emulator + or args.installed_cores or p.target), + accepted=p.core_choices, + ) + + if EVENTS.on: + # What the run would write, as _pass_download holds it against the + # free space: the screen's plan warns on this number. + _emit_check( + p.plat_name, p.manifest, bios_path, + CheckTally(files, up_to_date, mismatched, + sum(len(state[1]) for _entry, state in data_states), + len(p.omitted_files), + sum(data_fetch_bytes(entry, state[1]) for entry, state in data_states), + bytes_written(plan.without_lacking(to_download), data_states)), + chosen=selection[0] if selection else None, + ) + emit_fetch_plan(p.plat_name, plan) + emit_copies(p.plat_name, to_download, copies, bios_index, bios_path, files) + emit_unreadable(p.plat_name, unread) + run.total_verified += len(up_to_date) + + +def _pass_check_missing(run: _InstallRun, p: _PlatformPass) -> None: + """--check: the files not in place named, and how to get them.""" + args, bios_path = run.args, p.bios_path + to_download, mismatched, copies, plan = p.to_download, p.mismatched, p.copies, p.plan + # Named, not only counted: a user looking for the one bad + # BIOS learned "1 files need downloading" and nothing else. + # A wrong hash comes first and always in full: listed after + # 8000 missing files, it hid behind "... and 8059 more". + wrong = {id(entry) for entry in mismatched} + missing = [entry for entry in to_download if id(entry) not in wrong] + # A pack extracted from some of its parts: the part is named + # before the hundreds of files it holds. + for line in split_pack_lines(bios_path): + print(line) + offline = _offline_only() + # What the pack lacks is said before the count, as the + # screen says it. + if plan.lacking: + print(f"\n {pack_lacks_words(len(plan.lacking), len(plan.fetched))}") + # One total with the count above it, the data files among + # them as the screen counts them: "0 in place, 10805 missing" + # stood over "8164 files to download". + # The count and the folder by default, each file with + # --verbose: 20 paths hid the line saying what to do. + print(f"\n {_plural(len(to_download) + p.trees_missing, 'file')} " + + ("not in place." if offline or LOCAL.pack is not None + else "to download.")) + for line in check_lines(missing, mismatched, p.files, p.manifest, bios_path, + args.verbose, CheckHeld(p.up_to_date, p.bios_index, copies)): + print(line) + for line in unreadable_lines(p.unread, args.verbose): + print(line) + print(f" BIOS folder: {shown_path(bios_path)}") + # The data files need the internet too: offline, "8164 files + # need the internet" stood under "10805 files not in place". + print(_check_fetch_line(len(plan.fetched) + plan.data_files, + "the BIOS folder", len(plan.lacking), bool(mismatched))) + run.check_pending += len(to_download) + + +def _pass_check_report(run: _InstallRun, p: _PlatformPass) -> None: + """--check: what the setup's folder holds and lacks.""" + args, plat_name, bios_path = run.args, p.plat_name, p.bios_path + if p.to_download: + _pass_check_missing(run, p) + elif p.trees_missing: + # The screen's headline: "Everything is in place." stood + # above "0/169 data files present" and exit code 1. + print(f"\n {_plural(p.trees_missing, 'data file')} to fetch") + else: + print(f"\n {EVERYTHING_IN_PLACE}") + print(f" BIOS folder: {shown_path(bios_path)}") + if plat_name in _RECORD_TAKEN: + # The files counted are the recorded choice's, not the list's. + print(f" {record_menu_words(_RECORD_TAKEN[plat_name])} " + "--all-files checks every file.") + absent = _absent_required(p.omitted_files, bios_path) + # The collection cannot supply these, so they leave the exit + # code alone, but a user asking why a game will not start needs + # their count, and with --verbose their names, and which system + # and emulator each one is for. + if absent and not OUTPUT.verbose: + print(f" {needed_absent_words(len(absent), '--verbose')}") + for line in _needed_lines( + absent, "Not in the collection and absent here, needed to start an emulator", + every=args.verbose, + ): + detail(line) + for entry, (_root, needed, present) in p.data_states: + if needed: + detail(f" {entry['ref']}: {present}/{len(entry['files'])} data files " + f"present, {len(needed)} to fetch") + run.check_pending += len(needed) + + +def _pass_dry_run(run: _InstallRun, p: _PlatformPass) -> None: + """--dry-run: the plan of what an install would write.""" + args, bios_path, to_download, copies = run.args, p.bios_path, p.to_download, p.copies + run.files_pending += len(to_download) + trees = [(entry, state[1]) for entry, state in p.data_states] + # A data file in place with other contents is kept like a BIOS file. + kept = plan_kept(p.mismatched + [ + {"dest": f"{entry['dest']}/{rel}" if entry.get("dest") else rel} + for entry, needed in trees for rel in needed + ], bios_path) + plan = p.plan + # Said before the plan promises a count and a size, as an + # install says it: the dry run promised 23 files where the pack + # held 20. + if plan.lacking: + print(f"\n {pack_lacks_words(len(plan.lacking), len(plan.fetched))}") + _print_plan(plan.coming, bios_path, run.term, + trees, kept, copy_plan_lines(to_download, copies, p.bios_index, + bios_path, p.files, args.verbose, True), + verbose=args.verbose, manifest=p.manifest) + if p.plat_name in _RECORD_TAKEN: + print(f" {record_menu_words(_RECORD_TAKEN[p.plat_name])} " + "--all-files lists every file.") + for line in unreadable_lines(p.unread, args.verbose): + print(line) + for line in p.hint: + print(line) diff --git a/installer/run_download.py b/installer/run_download.py new file mode 100644 index 000000000..c6a875ee0 --- /dev/null +++ b/installer/run_download.py @@ -0,0 +1,286 @@ +"""The download pass of a setup: what offline leaves, the question, the folder, the fetch.""" + +from __future__ import annotations + +import argparse +import os +import sys +from pathlib import Path +from typing import TYPE_CHECKING + +from installer.console import OUTPUT, Progress, _confirm, detail +from installer.destination import on_its_card +from installer.detect_os import detected_shown +from installer.download import download_files +from installer.events import EVENTS +from installer.install_record import ( + _RECORD_TAKEN, + games_folder_kept, + record_argv, + record_day, + record_file, + record_paths, + setup_record, + write_record, +) +from installer.invocation import _INVOCATION +from installer.local_copies import copy_plan_lines, unreadable_lines +from installer.offline import LOCAL, _offline_only +from installer.outcome import _write_advice +from installer.pack_source import NOT_IN_PACK, pack_lacks_words +from installer.paths import shown_path +from installer.plan import CONFIRM_FROM_BYTES, _check_free_space +from installer.refusal import Refusal +from installer.romm import ROMM_SCAN_WORDS +from installer.space import bytes_written +from installer.tally import _bytes +from installer.text import _plural, format_size, screen_text + +if TYPE_CHECKING: + from installer.run_files import _PlatformPass + from installer.run_setups import _InstallRun + + +def _remember_install(args: argparse.Namespace, plat: str, folder: Path, manifest: dict, + written: list[dict], games: bool) -> None: + """Record what this install placed in folder and the choice it made, + games being the card's games applied with no --for-games.""" + if not written and setup_record(plat, folder)[0] is None: + # Nothing of ours is there to record, and no choice to keep. + return + # A games folder is kept only where the next run reads it from a + # record (games_folder_kept): elsewhere the card's own games are. + options = [(flag, value if flag != "--for-games" or not value + else os.path.abspath(value) + if games_folder_kept(os.path.abspath(value), folder) else None) + for flag, value in _INVOCATION.flags(plat)] + if games: + options += [("--for-games", None), + *([("--required-only", None)] if args.required_only else [])] + choice = record_argv(options) + path, setup, problem = write_record(folder, plat, manifest, choice, written) + if problem: + detail(f" {problem}.") + count = len(setup["files"]) + EVENTS.emit("record", platform=plat, folder=str(folder), + path=str(path or record_paths(folder)[0]), + status="not_written" if problem else "written", choice=choice, + date=setup["written"], files=count, + message=f"{problem}." if problem else + f"Recorded {_plural(count, 'file')} and this choice in {path}.") + + +def _pass_offline_left(run: _InstallRun, p: _PlatformPass, fetched: list[dict]) -> None: + """--offline: the files to fetch counted missing, the copies kept to do.""" + # The screen offers no Install for these: the question asked + # to download 6.6 GB that --offline never fetches. With --yes, + # the screen's own install, each one was "downloading", then + # FAILED, and the summary listed it pending and failed at once. + # Counted, never said here: the summary says it once. + # Not done: the summary counts them as missing. + run.files_pending += len(fetched) + run.total_offline += len(fetched) + wrong_ids = {id(entry) for entry in p.mismatched} + run.total_wrong_left += sum(1 for f in fetched if id(f) in wrong_ids) + run.offline_left += [f for f in fetched if id(f) not in wrong_ids] + p.to_download = [f for f in p.to_download if id(f) in p.copies] + + +def _pass_declined(run: _InstallRun, p: _PlatformPass, fetch_size: int) -> bool: + """The size question, where one is asked. True when it was declined.""" + args = run.args + if ( + run.interactive + and not args.yes + and fetch_size >= CONFIRM_FROM_BYTES + and not _confirm( + f"\nCopy {format_size(fetch_size)} from the pack to " + f"{shown_path(p.bios_path)}? [Y/n] " if LOCAL.pack is not None + else f"\nDownload {format_size(fetch_size)} to " + f"{shown_path(p.bios_path)}? [Y/n] " + ) + ): + # A beginner who just passed the c entry was sent to a + # 91-line --help. + print(p.smaller or " Nothing downloaded. --system, --core and --region " + "install less (see --help).") + run.total_up_to_date += len(p.up_to_date) + run.total_declined += len(p.to_download) + run.files_pending += len(p.to_download) + return True + return False + + +def _pass_copy_line(run: _InstallRun, p: _PlatformPass, fetched: list[dict], + lacking: set[int], dl_size: int) -> None: + """The copies from this machine planned, and the line that opens them.""" + copies, bios_index = p.copies, p.bios_index + detail() + for line in copy_plan_lines(p.to_download, copies, bios_index, p.bios_path, + p.files, run.args.verbose, False): + detail(line) + held = len(fetched) - len(lacking) + rest = (f" and {'copying' if LOCAL.pack is not None else 'downloading'} " + f"{held}" if held else "") + where = f" from {LOCAL.pack.name}" if fetched and LOCAL.pack is not None else "" + # Named by the folder they come from, as the line above + # names it: "found on this machine" followed "from E:\". + sources = list(dict.fromkeys(copy.index.label for copy in copies.values())) + named = ", ".join(screen_text(shown_path(label)) for label in sources) + origin = (f"from {named}" if all( + copy.index is not bios_index for copy in copies.values()) + else "found on this machine") + # The size beside what it weighs: after "and downloading + # 19" it read as theirs alone. + sized = f" ({format_size(dl_size)})" + detail(f"\nCopying {_plural(len(copies), 'file')}{'' if rest else sized} " + f"{origin}{rest}{where}{sized if rest else ''}...") + + +def _pass_download_head(run: _InstallRun, p: _PlatformPass, fetched: list[dict], + lacking: set[int], dl_size: int) -> None: + """The lines an install opens on: what comes, from where, to where.""" + args, plat_name, bios_path = run.args, p.plat_name, p.bios_path + if not p.menu: + # What happens and where, the two lines a run without questions + # opens on: the menu's head said them where it was asked. + coming = len(p.to_download) - len(lacking) + p.plan.data_files + weight = dl_size + p.plan.data_bytes + taken = _RECORD_TAKEN.get(plat_name) + print(f"\nInstalling {_plural(coming, 'file')} ({format_size(weight)}) for " + f"{detected_shown(plat_name, bios_path) or p.display}" + + (", what the games need" if p.games_applied else "") + + (f", same choice as on {record_day(taken)}" if taken else "") + ".") + print(f"BIOS folder: {shown_path(bios_path)}") + OUTPUT.where_said = True + if p.unread: + # A file of the user's that could not be read is said in + # every mode: it was expected to be copied. + print() + for line in unreadable_lines(p.unread, args.verbose): + print(line) + if p.copies: + _pass_copy_line(run, p, fetched, lacking, dl_size) + elif LOCAL.pack is not None: + # The files the pack holds: "Copying 23 files (85.0 KB)" sat + # beside the size of 20. + detail(f"\nCopying {_plural(len(p.to_download) - len(lacking), 'file')} " + f"({format_size(dl_size)}) from {LOCAL.pack.name}...") + else: + detail(f"\nDownloading {len(p.to_download)} files ({format_size(dl_size)})...") + detail(" Press Ctrl+C to stop. Running the same command again " + "carries on from here.") + + +def _pass_make_folder(run: _InstallRun, p: _PlatformPass, written: int) -> bool: + """The space checked and the BIOS folder made. True when it was created.""" + plat_name, bios_path = p.plat_name, p.bios_path + with run.writes(len(p.to_download)): + # Checked before the folder is created: a run stopped for space + # left an empty BIOS folder behind. The data trees count too, + # written after the files on the same drive. + _check_free_space(bios_path, written, plat_name, + 1 if run.total_downloaded else 2, on_its_card(plat_name, bios_path)) + p.space_checked = True + created = not bios_path.exists() + try: + bios_path.mkdir(parents=True, exist_ok=True) + except OSError as exc: + sys.stdout.flush() + # The documented code for a folder that cannot be written, + # as when it exists read-only. 1 once an earlier platform + # of the run installed something. + raise Refusal( + "dest", "not_writable", plat_name, + f"\nCannot create {bios_path}.", f" {exc.strerror}.", + _write_advice(bios_path, bios_path in run.assumed_dests, plat_name), + code=1 if run.total_downloaded else 2, + message=f"{bios_path} cannot be created: {exc.strerror}", + ) from None + if created: + detail(f" Created {shown_path(bios_path)}") + return created + + +def _pass_fetch(run: _InstallRun, p: _PlatformPass, dl_size: int, created: bool) -> bool: + """The files downloaded or copied and counted. True when interrupted.""" + args, plat_name, bios_path, to_download = run.args, p.plat_name, p.bios_path, p.to_download + progress = Progress(len(to_download), dl_size, run.term) + failed, interrupted = download_files( + to_download, bios_path, jobs=args.jobs, verbose=args.verbose, + term=run.term, progress=progress, copies=p.copies, + ) + if created and not progress.installed: + # Created for files none of which came: not left behind empty. + try: + bios_path.rmdir() + except OSError as exc: + if args.verbose: + print(f" {shown_path(bios_path)} stays: {exc.strerror}", + file=sys.stderr) + run.bulk_lines += p.hint + if plat_name == "romm" and progress.installed: + run.bulk_lines.append(ROMM_SCAN_WORDS) + run.total_downloaded += progress.installed + # The end line tells BIOS files from game data, as the menu + # 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] + run.files_pending += len(to_download) - progress.installed if interrupted \ + else len(failed) + run.total_errors += len(failed) + run.failures.extend(failed) + run.total_bytes += progress.transferred() + run.total_seconds += progress.elapsed() + if interrupted: + run.total_interrupted = True + _remember_install(args, plat_name, bios_path, p.manifest, p.record_files, + p.games_applied and args.for_games is None) + return interrupted + + +def _pass_download(run: _InstallRun, p: _PlatformPass) -> str: + """The missing files installed: "go" carries on with the setup, "next" + moves to the next one, "stop" ends the run.""" + plan = p.plan + fetched = plan.fetched + if _offline_only() and fetched: + _pass_offline_left(run, p, fetched) + fetched = [] + # What the pack does not hold is said before a size is promised: + # a pack older than the list gave "Copy 6.6 GB" and 8358 files + # failed. They are still tried, and fail as + # not in the pack, the size and the question leaving them out. + # Offline there is no pack, so nothing is lacking. + lacking = {id(f) for f in plan.lacking} + if lacking: + print(f"\n {pack_lacks_words(len(lacking), len(fetched))}") + if lacking and len(lacking) == len(p.to_download) and not plan.data_files: + # Nothing here can come from the pack: no "Copying 0 files", no + # folder made, each file failed as not in it. + run.failures.extend((f["dest"], NOT_IN_PACK) for f in p.to_download) + run.total_errors += len(p.to_download) + run.files_pending += len(p.to_download) + run.total_up_to_date += len(p.up_to_date) + return "next" + coming = plan.without_lacking(p.to_download) + dl_size = _bytes(coming) + fetch_size = _bytes(plan.without_lacking(fetched)) + if not p.to_download: + run.total_up_to_date += len(p.up_to_date) + if _offline_only(): + for _entry, (_root, needed, present) in p.data_states: + run.total_up_to_date += present + run.total_offline += len(needed) + run.files_pending += len(needed) + return "next" + if _pass_declined(run, p, fetch_size): + return "next" + EVENTS.emit("download", platform=p.plat_name, files=len(p.to_download), bytes=dl_size) + _pass_download_head(run, p, fetched, lacking, dl_size) + created = _pass_make_folder(run, p, bytes_written(coming, p.data_states)) + return "stop" if _pass_fetch(run, p, dl_size, created) else "go" diff --git a/wiki/architecture.md b/wiki/architecture.md index ce1b3c7b3..0d55a289d 100644 --- a/wiki/architecture.md +++ b/wiki/architecture.md @@ -505,7 +505,7 @@ those it imports: | Sources of files | `offline`, `network`, `lists`, `pack_source`, `folder_index`, `local_copies`, `from_folders`, `diagnosis`, `download`, `datadirs`, `standalone` | | What a run keeps | `narrowing`, `choices`, `romm`, `install_record`, `game_files`, `games_index`, `game_regions`, `game_folders`, `games`, `tally`, `space`, `fetch_plan` | | Line mode | `destination`, `line_folder`, `line_menu`, `plan_words`, `plan`, `failure_causes`, `outcome` | -| Runs and actions | `arguments`, `run_setups`, `run_files`, `run`, `pack_parts`, `pack`, `removal_plan`, `removal`, `backups`, `handheld_app`, `cli` | +| Runs and actions | `arguments`, `run_setups`, `run_files`, `run_check`, `run_download`, `run`, `pack_parts`, `pack`, `removal_plan`, `removal`, `backups`, `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_where_views`, `tui_screens`, `tui_help`, `tui_steps`, `tui_folder_actions`, `tui_actions`, `tui_input`, `tui_receive`, `tui_list_words`, `tui_engine`, `tui_first_screen`, `tui_terminal`, `tui_session` | ## Tests