From 2a4fb883d3670e7ed1d92476bb12accb952fc5af Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Tue, 24 Nov 2026 06:01:43 +0100 Subject: [PATCH] refactor: move --restore out of the install record --- install.ps1 | 2 +- install.py | 670 ++++++++++++++++++----------------- install.sh | 2 +- install/launchers/index.json | 16 +- installer/backups.py | 3 +- installer/cli.py | 2 +- installer/install_record.py | 353 +----------------- installer/removal.py | 8 +- installer/removal_plan.py | 3 +- installer/restore.py | 370 +++++++++++++++++++ wiki/architecture.md | 2 +- 11 files changed, 728 insertions(+), 703 deletions(-) create mode 100644 installer/restore.py diff --git a/install.ps1 b/install.ps1 index 98424c6a5..502c2d70c 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 = "24f8bbd81e850b808ac113ec91893a98296453119714c62ad19888add0d42075" + $defaultInstallSha256 = "bf437a4a291a8eda372040014f029689183cf09d78f6b54102b9261c493e40dd" # 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 91e080313..6a939abb9 100644 --- a/install.py +++ b/install.py @@ -11209,344 +11209,10 @@ def apply_record(args: argparse.Namespace, plat: str, folder: Path) -> dict | No return setup -def _backup_note(run: Path) -> dict | None: - """What a removal wrote beside the files it moved into run: the setup, - its folder, its choice before and the record's entries. None for the - backup of files an install replaced, or a note that cannot be read.""" - try: - data = json.loads(_read_record_bytes(run / REMOVED_NOTE).decode("utf-8")) - except (OSError, UnicodeDecodeError, ValueError): - return None - if not isinstance(data, dict) or not isinstance(data.get("platform"), str) \ - or not isinstance(data.get("folder"), str): - return None - setup = {"written": "", "choice": data.get("choice"), "files": data.get("files")} - return data if _valid_setup(setup, Path(data["folder"])) else None - - -def _record_folder(run: Path, path: Path) -> tuple[Path, str] | None: - """The BIOS folder whose record may name a file put back at path, and - its dest there. The holder beside a folder keeps the folder's name as - the first level of each run, the one inside it none.""" - holder, root = run.parent, run.parent.parent - rel = PurePosixPath(*path.relative_to(root).parts) - if len(rel.parts) > 1 and (holder / f"{rel.parts[0]}{RECORD_SUFFIX}").is_file(): - return root / rel.parts[0], PurePosixPath(*rel.parts[1:]).as_posix() - if (holder / f"{root.name or 'folder'}{RECORD_SUFFIX}").is_file(): - return root, rel.as_posix() - return None - - -def _record_without(gone: set[str]) -> Callable[[dict | None], dict | None]: - """The change taking out a setup's entries at the folded dests of gone.""" - def change(setup: dict | None) -> dict | None: - return None if setup is None else { - **setup, "files": [item for item in setup["files"] - if str(item.get("root") or "") not in ("", "data") - or item["dest"].casefold() not in gone]} - return change - - -def _record_after_restore(run: Path, put_back: list[Path]) -> str: - """The record of the folder files went back into, made to say what is - there now: "" once written, else why not. A removal's backup gives its - files back to their setup, with the choice it had. Any other backup - holds the user's own files, which the record never names: its entries - at their places go.""" - note = _backup_note(run) - if note is not None: - folder = Path(note["folder"]) - back = [] - for item in note["files"]: - path = _below(folder, item["dest"])[0] - if path is not None and not _check_ours(path, item)[0]: - back.append(item) - if not back and put_back: - # The files went back, but not where the record's folder is: the - # folder moved or was renamed since the removal. - return f"it is for {folder}, which does not hold the files put back" - if not back: - return "" - return _update_record(folder, note["platform"], - lambda setup: _record_merge(setup, back, note["choice"])) - by_folder: dict[Path, set[str]] = {} - for path in put_back: - found = _record_folder(run, path) - if found is not None: - by_folder.setdefault(found[0], set()).add(found[1].casefold()) - problems = [_update_record(folder, plat, _record_without(gone)) - for folder, gone in by_folder.items() - for plat in sorted((load_record(folder).data or {}).get("setups") or {})] - return next((problem for problem in problems if problem), "") - - -def _recorded_copy(run: Path, dest: Path) -> bool: - """Whether the file at dest is the installer's own copy, as the record - of its folder names it: the collection gives it again, so a restore - replaces it without keeping it.""" - found = _record_folder(run, dest) - if found is None: - return False - try: - info = os.lstat(dest) - except OSError: - return False - if not stat.S_ISREG(info.st_mode) or _is_link(info): - return False - folder, rel = found - items = [item for setup in ((load_record(folder).data or {}).get("setups") or {}).values() - for item in setup.get("files") or [] - if str(item.get("root") or "") in ("", "data") - and item["dest"].casefold() == rel.casefold() and item["size"] == info.st_size] - if not items: - return False - try: - sha1 = _digest_file(dest, ("sha1",))["sha1"] - except OSError: - return False - return any(item["sha1"] == sha1 for item in items) - - -def _record_merge(setup: dict | None, files: list[dict], choice: list[str]) -> dict: - """A setup with files given back and the choice it had before a removal.""" - merged = {(str(item.get("root") or ""), item["dest"]): item - for item in (setup or {}).get("files") or []} - for item in files: - merged[(str(item.get("root") or ""), item["dest"])] = item - return {"list": {"version": None, "generated": None}, **(setup or {}), - "written": _record_now(), "choice": list(choice), - "files": [merged[key] for key in sorted(merged)]} - - def _record_now() -> str: return datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") -def _update_record(folder: Path, plat: str, - change: Callable[[dict | None], dict | None]) -> str: - """Rewrite the setup plat of folder's record as change makes it, None - taking it out: "" once written, else why not. A record that cannot be - read, or that a newer installer wrote, is left as it is.""" - folder = Path(os.path.abspath(folder)) - read = load_record(folder) - if read.newer or (read.data is None and read.path is not None): - return read.problem - data = read.data or {"setups": {}, "folder": str(folder)} - setups = dict(data["setups"]) - new = change(setups.get(plat)) - if new is None: - setups.pop(plat, None) - else: - setups[plat] = new - if not setups: - if read.path is None: - return "" - # Nothing of ours is left in the folder: the record goes with it. - try: - read.path.unlink() - except OSError as exc: - return exc.strerror or str(exc) - return "" - data = {"schema": RECORD_SCHEMA, "installer": installer_id(), - "folder": str(data.get("folder") or folder), "setups": setups} - where, failure = _save_record(folder, data, read.path) - return "" if where is not None else failure - - -class RestoreResult(NamedTuple): - """What --restore did with a backup run folder, for the lines and the events. - - status: not_backup (the folder is no backup), empty (it holds no file), - planned (--dry-run), done, or not_done (a file failed or the record - could not be updated). dests are the places files went back to (would - go back to, planned), failed [(dest, reason)] those that did not, kept - the new backup folders the files at their places went to, as - KeptFiles.summary gives them, problem why the record was not updated. - """ - - run: Path - status: str - dests: tuple[Path, ...] = () - size: int = 0 - failed: tuple[tuple[Path, str], ...] = () - kept: tuple[dict, ...] = () - problem: str = "" - - @property - def root(self) -> Path: - return self.run.parent.parent - - @property - def code(self) -> int: - """0 when every file went back, 1 when one failed or the record was - not updated, 2 when the folder is no backup.""" - if self.status == "not_backup": - return 2 - return 1 if self.status == "not_done" else 0 - - -def _restore_one(run: Path, src: Path) -> tuple[Path, str]: - """Put the backup's src back at its place: (dest, "") once there, else - (dest, why not).""" - root = run.parent.parent - rel = PurePosixPath(*src.relative_to(run).parts) - dest = root / Path(*rel.parts) - try: - sha1 = _digest_file(src, ("sha1",))["sha1"] - dest.parent.mkdir(parents=True, exist_ok=True) - # A file at the place that is not the backup's copy (a newer one, - # one the user put there) is moved aside first, into a new dated - # backup, as an install keeps what it replaces. Its first level - # is the folder the backup's holder sits in. - holder = (root / rel.parts[0], PurePosixPath(*rel.parts[1:])) \ - if len(rel.parts) > 1 else (root, rel) - if not _recorded_copy(run, dest): - KEPT.keep(*holder, dest, {"sha1": sha1}) - _clear_read_only(dest) - _replace_with_copy(src, dest) - except (OSError, _NotKept) as exc: - return dest, getattr(exc, "strerror", None) or str(exc) - return dest, "" - - -def restore_backup(run: Path, dry_run: bool = False) -> RestoreResult: - """Put every file of a backup run folder back where it was. - - run is a / folder a run wrote, its holder named - retrobios-backup. Each file goes to the same path below the holder's - parent. A file there with other contents is moved into a new dated - backup first, never lost. The install record of its folder is made to - say so. The backup is left in place. Each file put back, or not, is a - restored event as it happens. - """ - run = Path(os.path.abspath(os.path.expanduser(str(run)))) - if not _is_backup_run(run): - return RestoreResult(run, "not_backup") - files = _backup_files(run) - if not files: - return RestoreResult(run, "empty") - root = run.parent.parent - if dry_run: - return RestoreResult(run, "planned", - tuple(root / Path(*src.relative_to(run).parts) for src in files), - sum(src.stat().st_size for src in files)) - size = 0 - put_back: list[Path] = [] - failed: list[tuple[Path, str]] = [] - KEPT.reset() - for src in files: - length = src.stat().st_size - dest, reason = _restore_one(run, src) - EVENTS.emit("restored", folder=str(run), path=str(dest), size=length, - ok=not reason, reason=reason) - if reason: - failed.append((dest, reason)) - continue - put_back.append(dest) - size += length - problem = _record_after_restore(run, put_back) - return RestoreResult(run, "not_done" if failed or problem else "done", tuple(put_back), - size, tuple(failed), tuple(KEPT.summary()), problem) - - -def restore_message(result: RestoreResult) -> str: - """Why a restore put nothing back, in one sentence, else "".""" - if result.status == "not_backup": - return f"{result.run} is not a folder the installer kept files in." - if result.status == "empty": - return f"{result.run} holds no file. Nothing to put back." - return "" - - -def say_restore(result: RestoreResult) -> None: - """--restore's outcome in lines.""" - if result.status == "not_backup": - print(f"Error: {restore_message(result)}", file=sys.stderr) - print(f" Name one of the dated folders inside a {BACKUP_DIR} folder, as " - "--backups lists them.", file=sys.stderr) - return - if result.status == "empty": - print(restore_message(result)) - return - if result.status == "planned": - for dest in result.dests: - print(f" would put back {dest}") - print(f"\nWould put back {_plural(len(result.dests), 'file')} " - f"({format_size(result.size)}) under {result.root}. Nothing was written.") - return - for dest, reason in result.failed: - print(f" failed: {dest} ({reason})", file=sys.stderr) - print(f"\nPut back {_plural(len(result.dests), 'file')} ({format_size(result.size)}) " - f"under {result.root}.") - for item in result.kept: - # The files that sat at those places, never lost. - print(f"Kept {_plural(item['files'], 'file')} that were in their place " - f"({format_size(item['bytes'])}) in {item['folder']}") - if result.failed: - print(f"{_plural(len(result.failed), 'file')} could not be put back.", file=sys.stderr) - if result.problem: - print(f"The install record could not be updated ({result.problem}).", file=sys.stderr) - print(f"The copies are still in {result.run}. To free the space: " - f"{_INVOCATION.launcher()} --delete-backup {_INVOCATION.word(str(result.run))}") - - -def restore_kept(run: Path, dry_run: bool = False) -> int: - """--restore: put a backup back, say it in lines and as a restore - event, and return the exit code.""" - result = restore_backup(run, dry_run) - say_restore(result) - EVENTS.emit("restore", folder=str(result.run), status=result.status, - files=len(result.dests), bytes=result.size, kept=list(result.kept), - problem=result.problem, message=restore_message(result)) - return result.code - - -def _below(folder: Path, dest: str) -> tuple[Path | None, str]: - """The file a record's dest names below folder, reached through no link: - (path, "") or (None, why it is left). A dest that climbs or is absolute - is outside, whatever a record says.""" - try: - rel = _safe_relative_path(dest, "dest") - except ValueError: - return None, "outside" - path = folder - for part in rel.parts[:-1]: - path = path / part - try: - info = os.lstat(path) - except FileNotFoundError: - return None, "gone" - except OSError: - return None, "unreadable" - if _is_link(info): - return None, "link" - if not stat.S_ISDIR(info.st_mode): - return None, "not_a_file" - return path / rel.parts[-1], "" - - -def _check_ours(path: Path, item: dict) -> tuple[str, os.stat_result | None]: - """Why the file at path is not the one the record names, "" when it - is, and what lstat read of it.""" - try: - info = os.lstat(path) - except FileNotFoundError: - return "gone", None - except OSError: - return "unreadable", None - if _is_link(info): - return "link", info - if not stat.S_ISREG(info.st_mode): - return "not_a_file", info - if not re.fullmatch(r"[0-9a-f]{40}", str(item["sha1"])) or info.st_size != item["size"]: - return "changed", info - try: - same = _digest_file(path, ("sha1",))["sha1"] == item["sha1"] - except OSError: - return "unreadable", info - return ("" if same else "changed"), info - - # --- installer/choices.py ---------------------------------------------------- def recorded_axes(files: list[dict], omitted: Iterable[dict] = ()) -> frozenset: @@ -13199,6 +12865,342 @@ def _listed(folder: Path) -> list[str]: return [] +# --- installer/restore.py ---------------------------------------------------- + +def _backup_note(run: Path) -> dict | None: + """What a removal wrote beside the files it moved into run: the setup, + its folder, its choice before and the record's entries. None for the + backup of files an install replaced, or a note that cannot be read.""" + try: + data = json.loads(_read_record_bytes(run / REMOVED_NOTE).decode("utf-8")) + except (OSError, UnicodeDecodeError, ValueError): + return None + if not isinstance(data, dict) or not isinstance(data.get("platform"), str) \ + or not isinstance(data.get("folder"), str): + return None + setup = {"written": "", "choice": data.get("choice"), "files": data.get("files")} + return data if _valid_setup(setup, Path(data["folder"])) else None + + +def _record_folder(run: Path, path: Path) -> tuple[Path, str] | None: + """The BIOS folder whose record may name a file put back at path, and + its dest there. The holder beside a folder keeps the folder's name as + the first level of each run, the one inside it none.""" + holder, root = run.parent, run.parent.parent + rel = PurePosixPath(*path.relative_to(root).parts) + if len(rel.parts) > 1 and (holder / f"{rel.parts[0]}{RECORD_SUFFIX}").is_file(): + return root / rel.parts[0], PurePosixPath(*rel.parts[1:]).as_posix() + if (holder / f"{root.name or 'folder'}{RECORD_SUFFIX}").is_file(): + return root, rel.as_posix() + return None + + +def _record_without(gone: set[str]) -> Callable[[dict | None], dict | None]: + """The change taking out a setup's entries at the folded dests of gone.""" + def change(setup: dict | None) -> dict | None: + return None if setup is None else { + **setup, "files": [item for item in setup["files"] + if str(item.get("root") or "") not in ("", "data") + or item["dest"].casefold() not in gone]} + return change + + +def _record_after_restore(run: Path, put_back: list[Path]) -> str: + """The record of the folder files went back into, made to say what is + there now: "" once written, else why not. A removal's backup gives its + files back to their setup, with the choice it had. Any other backup + holds the user's own files, which the record never names: its entries + at their places go.""" + note = _backup_note(run) + if note is not None: + folder = Path(note["folder"]) + back = [] + for item in note["files"]: + path = _below(folder, item["dest"])[0] + if path is not None and not _check_ours(path, item)[0]: + back.append(item) + if not back and put_back: + # The files went back, but not where the record's folder is: the + # folder moved or was renamed since the removal. + return f"it is for {folder}, which does not hold the files put back" + if not back: + return "" + return _update_record(folder, note["platform"], + lambda setup: _record_merge(setup, back, note["choice"])) + by_folder: dict[Path, set[str]] = {} + for path in put_back: + found = _record_folder(run, path) + if found is not None: + by_folder.setdefault(found[0], set()).add(found[1].casefold()) + problems = [_update_record(folder, plat, _record_without(gone)) + for folder, gone in by_folder.items() + for plat in sorted((load_record(folder).data or {}).get("setups") or {})] + return next((problem for problem in problems if problem), "") + + +def _recorded_copy(run: Path, dest: Path) -> bool: + """Whether the file at dest is the installer's own copy, as the record + of its folder names it: the collection gives it again, so a restore + replaces it without keeping it.""" + found = _record_folder(run, dest) + if found is None: + return False + try: + info = os.lstat(dest) + except OSError: + return False + if not stat.S_ISREG(info.st_mode) or _is_link(info): + return False + folder, rel = found + items = [item for setup in ((load_record(folder).data or {}).get("setups") or {}).values() + for item in setup.get("files") or [] + if str(item.get("root") or "") in ("", "data") + and item["dest"].casefold() == rel.casefold() and item["size"] == info.st_size] + if not items: + return False + try: + sha1 = _digest_file(dest, ("sha1",))["sha1"] + except OSError: + return False + return any(item["sha1"] == sha1 for item in items) + + +def _record_merge(setup: dict | None, files: list[dict], choice: list[str]) -> dict: + """A setup with files given back and the choice it had before a removal.""" + merged = {(str(item.get("root") or ""), item["dest"]): item + for item in (setup or {}).get("files") or []} + for item in files: + merged[(str(item.get("root") or ""), item["dest"])] = item + return {"list": {"version": None, "generated": None}, **(setup or {}), + "written": _record_now(), "choice": list(choice), + "files": [merged[key] for key in sorted(merged)]} + + +def _update_record(folder: Path, plat: str, + change: Callable[[dict | None], dict | None]) -> str: + """Rewrite the setup plat of folder's record as change makes it, None + taking it out: "" once written, else why not. A record that cannot be + read, or that a newer installer wrote, is left as it is.""" + folder = Path(os.path.abspath(folder)) + read = load_record(folder) + if read.newer or (read.data is None and read.path is not None): + return read.problem + data = read.data or {"setups": {}, "folder": str(folder)} + setups = dict(data["setups"]) + new = change(setups.get(plat)) + if new is None: + setups.pop(plat, None) + else: + setups[plat] = new + if not setups: + if read.path is None: + return "" + # Nothing of ours is left in the folder: the record goes with it. + try: + read.path.unlink() + except OSError as exc: + return exc.strerror or str(exc) + return "" + data = {"schema": RECORD_SCHEMA, "installer": installer_id(), + "folder": str(data.get("folder") or folder), "setups": setups} + where, failure = _save_record(folder, data, read.path) + return "" if where is not None else failure + + +class RestoreResult(NamedTuple): + """What --restore did with a backup run folder, for the lines and the events. + + status: not_backup (the folder is no backup), empty (it holds no file), + planned (--dry-run), done, or not_done (a file failed or the record + could not be updated). dests are the places files went back to (would + go back to, planned), failed [(dest, reason)] those that did not, kept + the new backup folders the files at their places went to, as + KeptFiles.summary gives them, problem why the record was not updated. + """ + + run: Path + status: str + dests: tuple[Path, ...] = () + size: int = 0 + failed: tuple[tuple[Path, str], ...] = () + kept: tuple[dict, ...] = () + problem: str = "" + + @property + def root(self) -> Path: + return self.run.parent.parent + + @property + def code(self) -> int: + """0 when every file went back, 1 when one failed or the record was + not updated, 2 when the folder is no backup.""" + if self.status == "not_backup": + return 2 + return 1 if self.status == "not_done" else 0 + + +def _restore_one(run: Path, src: Path) -> tuple[Path, str]: + """Put the backup's src back at its place: (dest, "") once there, else + (dest, why not).""" + root = run.parent.parent + rel = PurePosixPath(*src.relative_to(run).parts) + dest = root / Path(*rel.parts) + try: + sha1 = _digest_file(src, ("sha1",))["sha1"] + dest.parent.mkdir(parents=True, exist_ok=True) + # A file at the place that is not the backup's copy (a newer one, + # one the user put there) is moved aside first, into a new dated + # backup, as an install keeps what it replaces. Its first level + # is the folder the backup's holder sits in. + holder = (root / rel.parts[0], PurePosixPath(*rel.parts[1:])) \ + if len(rel.parts) > 1 else (root, rel) + if not _recorded_copy(run, dest): + KEPT.keep(*holder, dest, {"sha1": sha1}) + _clear_read_only(dest) + _replace_with_copy(src, dest) + except (OSError, _NotKept) as exc: + return dest, getattr(exc, "strerror", None) or str(exc) + return dest, "" + + +def restore_backup(run: Path, dry_run: bool = False) -> RestoreResult: + """Put every file of a backup run folder back where it was. + + run is a / folder a run wrote, its holder named + retrobios-backup. Each file goes to the same path below the holder's + parent. A file there with other contents is moved into a new dated + backup first, never lost. The install record of its folder is made to + say so. The backup is left in place. Each file put back, or not, is a + restored event as it happens. + """ + run = Path(os.path.abspath(os.path.expanduser(str(run)))) + if not _is_backup_run(run): + return RestoreResult(run, "not_backup") + files = _backup_files(run) + if not files: + return RestoreResult(run, "empty") + root = run.parent.parent + if dry_run: + return RestoreResult(run, "planned", + tuple(root / Path(*src.relative_to(run).parts) for src in files), + sum(src.stat().st_size for src in files)) + size = 0 + put_back: list[Path] = [] + failed: list[tuple[Path, str]] = [] + KEPT.reset() + for src in files: + length = src.stat().st_size + dest, reason = _restore_one(run, src) + EVENTS.emit("restored", folder=str(run), path=str(dest), size=length, + ok=not reason, reason=reason) + if reason: + failed.append((dest, reason)) + continue + put_back.append(dest) + size += length + problem = _record_after_restore(run, put_back) + return RestoreResult(run, "not_done" if failed or problem else "done", tuple(put_back), + size, tuple(failed), tuple(KEPT.summary()), problem) + + +def restore_message(result: RestoreResult) -> str: + """Why a restore put nothing back, in one sentence, else "".""" + if result.status == "not_backup": + return f"{result.run} is not a folder the installer kept files in." + if result.status == "empty": + return f"{result.run} holds no file. Nothing to put back." + return "" + + +def say_restore(result: RestoreResult) -> None: + """--restore's outcome in lines.""" + if result.status == "not_backup": + print(f"Error: {restore_message(result)}", file=sys.stderr) + print(f" Name one of the dated folders inside a {BACKUP_DIR} folder, as " + "--backups lists them.", file=sys.stderr) + return + if result.status == "empty": + print(restore_message(result)) + return + if result.status == "planned": + for dest in result.dests: + print(f" would put back {dest}") + print(f"\nWould put back {_plural(len(result.dests), 'file')} " + f"({format_size(result.size)}) under {result.root}. Nothing was written.") + return + for dest, reason in result.failed: + print(f" failed: {dest} ({reason})", file=sys.stderr) + print(f"\nPut back {_plural(len(result.dests), 'file')} ({format_size(result.size)}) " + f"under {result.root}.") + for item in result.kept: + # The files that sat at those places, never lost. + print(f"Kept {_plural(item['files'], 'file')} that were in their place " + f"({format_size(item['bytes'])}) in {item['folder']}") + if result.failed: + print(f"{_plural(len(result.failed), 'file')} could not be put back.", file=sys.stderr) + if result.problem: + print(f"The install record could not be updated ({result.problem}).", file=sys.stderr) + print(f"The copies are still in {result.run}. To free the space: " + f"{_INVOCATION.launcher()} --delete-backup {_INVOCATION.word(str(result.run))}") + + +def restore_kept(run: Path, dry_run: bool = False) -> int: + """--restore: put a backup back, say it in lines and as a restore + event, and return the exit code.""" + result = restore_backup(run, dry_run) + say_restore(result) + EVENTS.emit("restore", folder=str(result.run), status=result.status, + files=len(result.dests), bytes=result.size, kept=list(result.kept), + problem=result.problem, message=restore_message(result)) + return result.code + + +def _below(folder: Path, dest: str) -> tuple[Path | None, str]: + """The file a record's dest names below folder, reached through no link: + (path, "") or (None, why it is left). A dest that climbs or is absolute + is outside, whatever a record says.""" + try: + rel = _safe_relative_path(dest, "dest") + except ValueError: + return None, "outside" + path = folder + for part in rel.parts[:-1]: + path = path / part + try: + info = os.lstat(path) + except FileNotFoundError: + return None, "gone" + except OSError: + return None, "unreadable" + if _is_link(info): + return None, "link" + if not stat.S_ISDIR(info.st_mode): + return None, "not_a_file" + return path / rel.parts[-1], "" + + +def _check_ours(path: Path, item: dict) -> tuple[str, os.stat_result | None]: + """Why the file at path is not the one the record names, "" when it + is, and what lstat read of it.""" + try: + info = os.lstat(path) + except FileNotFoundError: + return "gone", None + except OSError: + return "unreadable", None + if _is_link(info): + return "link", info + if not stat.S_ISREG(info.st_mode): + return "not_a_file", info + if not re.fullmatch(r"[0-9a-f]{40}", str(item["sha1"])) or info.st_size != item["size"]: + return "changed", info + try: + same = _digest_file(path, ("sha1",))["sha1"] == item["sha1"] + except OSError: + return "unreadable", info + return ("" if same else "changed"), info + + # --- installer/removal_plan.py ----------------------------------------------- # Removal deletes for good, or moves into a backup with --backup, only what diff --git a/install.sh b/install.sh index 5bfd9f15b..cc5978644 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="24f8bbd81e850b808ac113ec91893a98296453119714c62ad19888add0d42075" +DEFAULT_INSTALL_SHA256="bf437a4a291a8eda372040014f029689183cf09d78f6b54102b9261c493e40dd" # 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 94f5b065a..2e40be7cb 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": 1503510, - "sha256": "24f8bbd81e850b808ac113ec91893a98296453119714c62ad19888add0d42075", + "size": 1503591, + "sha256": "bf437a4a291a8eda372040014f029689183cf09d78f6b54102b9261c493e40dd", "executable": false }, { @@ -71,8 +71,8 @@ "muos": { "archive": { "dest": "ARCHIVE/RetroBIOS.muxapp", - "size": 1557135, - "sha256": "6e7ac34c49310e24291d5fd0ccec18f9656ff562ca0d7cc3d17a6fafe77f9707" + "size": 1557216, + "sha256": "ebed28757531f64d484a567c693a0d84695c4f8c1f4ee561ebc8ce75500ece19" }, "members": [ { @@ -92,8 +92,8 @@ { "name": "RetroBIOS/install.py", "repo_path": "install.py", - "size": 1503510, - "sha256": "24f8bbd81e850b808ac113ec91893a98296453119714c62ad19888add0d42075", + "size": 1503591, + "sha256": "bf437a4a291a8eda372040014f029689183cf09d78f6b54102b9261c493e40dd", "executable": false }, { @@ -166,8 +166,8 @@ { "dest": ".config/modules/retrobios/install.py", "repo_path": "install.py", - "size": 1503510, - "sha256": "24f8bbd81e850b808ac113ec91893a98296453119714c62ad19888add0d42075", + "size": 1503591, + "sha256": "bf437a4a291a8eda372040014f029689183cf09d78f6b54102b9261c493e40dd", "executable": false }, { diff --git a/installer/backups.py b/installer/backups.py index e12ace01c..cf6f8d3d5 100644 --- a/installer/backups.py +++ b/installer/backups.py @@ -16,7 +16,8 @@ from installer.detect_frontends import detect_platforms from installer.detect_os import detect_os from installer.events import EVENTS from installer.host_fs import _clear_read_only -from installer.install_record import _backup_note, day_words, load_record +from installer.restore import _backup_note +from installer.install_record import day_words, load_record from installer.invocation import _INVOCATION from installer.paths import shown_path, spelled from installer.platforms import normalize_platform diff --git a/installer/cli.py b/installer/cli.py index c8e53e31c..7302ca985 100644 --- a/installer/cli.py +++ b/installer/cli.py @@ -18,7 +18,7 @@ from installer.events import EVENTS, EVENT_SCHEMA, _event_exit_code, _event_mode from installer.from_folders import _open_local_sources from installer.handheld_app import app_not_added from installer.host_fs import _is_dir, _writing -from installer.install_record import restore_kept +from installer.restore import restore_kept from installer.invocation import ( LISTING_FLAGS, OFFLINE_VARIABLE, diff --git a/installer/install_record.py b/installer/install_record.py index 87f80b483..5342c6738 100644 --- a/installer/install_record.py +++ b/installer/install_record.py @@ -1,4 +1,4 @@ -"""The install record a run leaves beside the BIOS folder, and --restore.""" +"""The install record a run leaves beside the BIOS folder: read, written, and the choice it keeps.""" from __future__ import annotations import argparse @@ -6,32 +6,21 @@ import datetime import errno import json import os -import re import stat -import sys -from collections.abc import Callable, Iterable -from pathlib import Path, PurePosixPath +from collections.abc import Iterable +from pathlib import Path from typing import NamedTuple from installer.arguments import build_parser from installer.events import EVENTS -from installer.host_fs import _clear_read_only, _is_dir, _is_link, _replace_with_copy, write_atomically +from installer.host_fs import _is_dir, write_atomically from installer.invocation import _INVOCATION, _VALUED_OPTIONS, _command_rank, installer_id -from installer.local_check import _digest_file from installer.offline import LOCAL -from installer.paths import _safe_relative_path from installer.platforms import system_title from installer.safe_replace import ( - BACKUP_DIR, - KEPT, - REMOVED_NOTE, KeptFiles, - _NotKept, - _backup_files, _check_holder, - _is_backup_run, ) -from installer.text import _plural, format_size # The install record: what the runs placed in a BIOS folder, each file with # its hash, and the choice they made, which the next run's plan takes. It @@ -481,339 +470,5 @@ def apply_record(args: argparse.Namespace, plat: str, folder: Path) -> dict | No return setup -def _backup_note(run: Path) -> dict | None: - """What a removal wrote beside the files it moved into run: the setup, - its folder, its choice before and the record's entries. None for the - backup of files an install replaced, or a note that cannot be read.""" - try: - data = json.loads(_read_record_bytes(run / REMOVED_NOTE).decode("utf-8")) - except (OSError, UnicodeDecodeError, ValueError): - return None - if not isinstance(data, dict) or not isinstance(data.get("platform"), str) \ - or not isinstance(data.get("folder"), str): - return None - setup = {"written": "", "choice": data.get("choice"), "files": data.get("files")} - return data if _valid_setup(setup, Path(data["folder"])) else None - - -def _record_folder(run: Path, path: Path) -> tuple[Path, str] | None: - """The BIOS folder whose record may name a file put back at path, and - its dest there. The holder beside a folder keeps the folder's name as - the first level of each run, the one inside it none.""" - holder, root = run.parent, run.parent.parent - rel = PurePosixPath(*path.relative_to(root).parts) - if len(rel.parts) > 1 and (holder / f"{rel.parts[0]}{RECORD_SUFFIX}").is_file(): - return root / rel.parts[0], PurePosixPath(*rel.parts[1:]).as_posix() - if (holder / f"{root.name or 'folder'}{RECORD_SUFFIX}").is_file(): - return root, rel.as_posix() - return None - - -def _record_without(gone: set[str]) -> Callable[[dict | None], dict | None]: - """The change taking out a setup's entries at the folded dests of gone.""" - def change(setup: dict | None) -> dict | None: - return None if setup is None else { - **setup, "files": [item for item in setup["files"] - if str(item.get("root") or "") not in ("", "data") - or item["dest"].casefold() not in gone]} - return change - - -def _record_after_restore(run: Path, put_back: list[Path]) -> str: - """The record of the folder files went back into, made to say what is - there now: "" once written, else why not. A removal's backup gives its - files back to their setup, with the choice it had. Any other backup - holds the user's own files, which the record never names: its entries - at their places go.""" - note = _backup_note(run) - if note is not None: - folder = Path(note["folder"]) - back = [] - for item in note["files"]: - path = _below(folder, item["dest"])[0] - if path is not None and not _check_ours(path, item)[0]: - back.append(item) - if not back and put_back: - # The files went back, but not where the record's folder is: the - # folder moved or was renamed since the removal. - return f"it is for {folder}, which does not hold the files put back" - if not back: - return "" - return _update_record(folder, note["platform"], - lambda setup: _record_merge(setup, back, note["choice"])) - by_folder: dict[Path, set[str]] = {} - for path in put_back: - found = _record_folder(run, path) - if found is not None: - by_folder.setdefault(found[0], set()).add(found[1].casefold()) - problems = [_update_record(folder, plat, _record_without(gone)) - for folder, gone in by_folder.items() - for plat in sorted((load_record(folder).data or {}).get("setups") or {})] - return next((problem for problem in problems if problem), "") - - -def _recorded_copy(run: Path, dest: Path) -> bool: - """Whether the file at dest is the installer's own copy, as the record - of its folder names it: the collection gives it again, so a restore - replaces it without keeping it.""" - found = _record_folder(run, dest) - if found is None: - return False - try: - info = os.lstat(dest) - except OSError: - return False - if not stat.S_ISREG(info.st_mode) or _is_link(info): - return False - folder, rel = found - items = [item for setup in ((load_record(folder).data or {}).get("setups") or {}).values() - for item in setup.get("files") or [] - if str(item.get("root") or "") in ("", "data") - and item["dest"].casefold() == rel.casefold() and item["size"] == info.st_size] - if not items: - return False - try: - sha1 = _digest_file(dest, ("sha1",))["sha1"] - except OSError: - return False - return any(item["sha1"] == sha1 for item in items) - - -def _record_merge(setup: dict | None, files: list[dict], choice: list[str]) -> dict: - """A setup with files given back and the choice it had before a removal.""" - merged = {(str(item.get("root") or ""), item["dest"]): item - for item in (setup or {}).get("files") or []} - for item in files: - merged[(str(item.get("root") or ""), item["dest"])] = item - return {"list": {"version": None, "generated": None}, **(setup or {}), - "written": _record_now(), "choice": list(choice), - "files": [merged[key] for key in sorted(merged)]} - - def _record_now() -> str: return datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") - - -def _update_record(folder: Path, plat: str, - change: Callable[[dict | None], dict | None]) -> str: - """Rewrite the setup plat of folder's record as change makes it, None - taking it out: "" once written, else why not. A record that cannot be - read, or that a newer installer wrote, is left as it is.""" - folder = Path(os.path.abspath(folder)) - read = load_record(folder) - if read.newer or (read.data is None and read.path is not None): - return read.problem - data = read.data or {"setups": {}, "folder": str(folder)} - setups = dict(data["setups"]) - new = change(setups.get(plat)) - if new is None: - setups.pop(plat, None) - else: - setups[plat] = new - if not setups: - if read.path is None: - return "" - # Nothing of ours is left in the folder: the record goes with it. - try: - read.path.unlink() - except OSError as exc: - return exc.strerror or str(exc) - return "" - data = {"schema": RECORD_SCHEMA, "installer": installer_id(), - "folder": str(data.get("folder") or folder), "setups": setups} - where, failure = _save_record(folder, data, read.path) - return "" if where is not None else failure - - -class RestoreResult(NamedTuple): - """What --restore did with a backup run folder, for the lines and the events. - - status: not_backup (the folder is no backup), empty (it holds no file), - planned (--dry-run), done, or not_done (a file failed or the record - could not be updated). dests are the places files went back to (would - go back to, planned), failed [(dest, reason)] those that did not, kept - the new backup folders the files at their places went to, as - KeptFiles.summary gives them, problem why the record was not updated. - """ - - run: Path - status: str - dests: tuple[Path, ...] = () - size: int = 0 - failed: tuple[tuple[Path, str], ...] = () - kept: tuple[dict, ...] = () - problem: str = "" - - @property - def root(self) -> Path: - return self.run.parent.parent - - @property - def code(self) -> int: - """0 when every file went back, 1 when one failed or the record was - not updated, 2 when the folder is no backup.""" - if self.status == "not_backup": - return 2 - return 1 if self.status == "not_done" else 0 - - -def _restore_one(run: Path, src: Path) -> tuple[Path, str]: - """Put the backup's src back at its place: (dest, "") once there, else - (dest, why not).""" - root = run.parent.parent - rel = PurePosixPath(*src.relative_to(run).parts) - dest = root / Path(*rel.parts) - try: - sha1 = _digest_file(src, ("sha1",))["sha1"] - dest.parent.mkdir(parents=True, exist_ok=True) - # A file at the place that is not the backup's copy (a newer one, - # one the user put there) is moved aside first, into a new dated - # backup, as an install keeps what it replaces. Its first level - # is the folder the backup's holder sits in. - holder = (root / rel.parts[0], PurePosixPath(*rel.parts[1:])) \ - if len(rel.parts) > 1 else (root, rel) - if not _recorded_copy(run, dest): - KEPT.keep(*holder, dest, {"sha1": sha1}) - _clear_read_only(dest) - _replace_with_copy(src, dest) - except (OSError, _NotKept) as exc: - return dest, getattr(exc, "strerror", None) or str(exc) - return dest, "" - - -def restore_backup(run: Path, dry_run: bool = False) -> RestoreResult: - """Put every file of a backup run folder back where it was. - - run is a / folder a run wrote, its holder named - retrobios-backup. Each file goes to the same path below the holder's - parent. A file there with other contents is moved into a new dated - backup first, never lost. The install record of its folder is made to - say so. The backup is left in place. Each file put back, or not, is a - restored event as it happens. - """ - run = Path(os.path.abspath(os.path.expanduser(str(run)))) - if not _is_backup_run(run): - return RestoreResult(run, "not_backup") - files = _backup_files(run) - if not files: - return RestoreResult(run, "empty") - root = run.parent.parent - if dry_run: - return RestoreResult(run, "planned", - tuple(root / Path(*src.relative_to(run).parts) for src in files), - sum(src.stat().st_size for src in files)) - size = 0 - put_back: list[Path] = [] - failed: list[tuple[Path, str]] = [] - KEPT.reset() - for src in files: - length = src.stat().st_size - dest, reason = _restore_one(run, src) - EVENTS.emit("restored", folder=str(run), path=str(dest), size=length, - ok=not reason, reason=reason) - if reason: - failed.append((dest, reason)) - continue - put_back.append(dest) - size += length - problem = _record_after_restore(run, put_back) - return RestoreResult(run, "not_done" if failed or problem else "done", tuple(put_back), - size, tuple(failed), tuple(KEPT.summary()), problem) - - -def restore_message(result: RestoreResult) -> str: - """Why a restore put nothing back, in one sentence, else "".""" - if result.status == "not_backup": - return f"{result.run} is not a folder the installer kept files in." - if result.status == "empty": - return f"{result.run} holds no file. Nothing to put back." - return "" - - -def say_restore(result: RestoreResult) -> None: - """--restore's outcome in lines.""" - if result.status == "not_backup": - print(f"Error: {restore_message(result)}", file=sys.stderr) - print(f" Name one of the dated folders inside a {BACKUP_DIR} folder, as " - "--backups lists them.", file=sys.stderr) - return - if result.status == "empty": - print(restore_message(result)) - return - if result.status == "planned": - for dest in result.dests: - print(f" would put back {dest}") - print(f"\nWould put back {_plural(len(result.dests), 'file')} " - f"({format_size(result.size)}) under {result.root}. Nothing was written.") - return - for dest, reason in result.failed: - print(f" failed: {dest} ({reason})", file=sys.stderr) - print(f"\nPut back {_plural(len(result.dests), 'file')} ({format_size(result.size)}) " - f"under {result.root}.") - for item in result.kept: - # The files that sat at those places, never lost. - print(f"Kept {_plural(item['files'], 'file')} that were in their place " - f"({format_size(item['bytes'])}) in {item['folder']}") - if result.failed: - print(f"{_plural(len(result.failed), 'file')} could not be put back.", file=sys.stderr) - if result.problem: - print(f"The install record could not be updated ({result.problem}).", file=sys.stderr) - print(f"The copies are still in {result.run}. To free the space: " - f"{_INVOCATION.launcher()} --delete-backup {_INVOCATION.word(str(result.run))}") - - -def restore_kept(run: Path, dry_run: bool = False) -> int: - """--restore: put a backup back, say it in lines and as a restore - event, and return the exit code.""" - result = restore_backup(run, dry_run) - say_restore(result) - EVENTS.emit("restore", folder=str(result.run), status=result.status, - files=len(result.dests), bytes=result.size, kept=list(result.kept), - problem=result.problem, message=restore_message(result)) - return result.code - - -def _below(folder: Path, dest: str) -> tuple[Path | None, str]: - """The file a record's dest names below folder, reached through no link: - (path, "") or (None, why it is left). A dest that climbs or is absolute - is outside, whatever a record says.""" - try: - rel = _safe_relative_path(dest, "dest") - except ValueError: - return None, "outside" - path = folder - for part in rel.parts[:-1]: - path = path / part - try: - info = os.lstat(path) - except FileNotFoundError: - return None, "gone" - except OSError: - return None, "unreadable" - if _is_link(info): - return None, "link" - if not stat.S_ISDIR(info.st_mode): - return None, "not_a_file" - return path / rel.parts[-1], "" - - -def _check_ours(path: Path, item: dict) -> tuple[str, os.stat_result | None]: - """Why the file at path is not the one the record names, "" when it - is, and what lstat read of it.""" - try: - info = os.lstat(path) - except FileNotFoundError: - return "gone", None - except OSError: - return "unreadable", None - if _is_link(info): - return "link", info - if not stat.S_ISREG(info.st_mode): - return "not_a_file", info - if not re.fullmatch(r"[0-9a-f]{40}", str(item["sha1"])) or info.st_size != item["size"]: - return "changed", info - try: - same = _digest_file(path, ("sha1",))["sha1"] == item["sha1"] - except OSError: - return "unreadable", info - return ("" if same else "changed"), info diff --git a/installer/removal.py b/installer/removal.py index b75878494..5229a760f 100644 --- a/installer/removal.py +++ b/installer/removal.py @@ -16,12 +16,8 @@ from installer.console import QUIT_CODE, _answer_yes from installer.events import EVENTS from installer.filesystems import keeps_case from installer.host_fs import _clear_read_only, _is_link -from installer.install_record import ( - _record_now, - _update_record, - load_record, - setup_record, -) +from installer.install_record import _record_now, load_record, setup_record +from installer.restore import _update_record from installer.invocation import _INVOCATION, offline_requested from installer.lists import fetch_manifest from installer.local_check import _digest_file diff --git a/installer/removal_plan.py b/installer/removal_plan.py index a41514ed9..06b3088fd 100644 --- a/installer/removal_plan.py +++ b/installer/removal_plan.py @@ -11,7 +11,8 @@ from typing import NamedTuple from installer.choices import available_choices, system_ids from installer.filesystems import keeps_case from installer.host_fs import _is_link -from installer.install_record import _below, _check_ours, record_argv, record_options +from installer.restore import _below, _check_ours +from installer.install_record import record_argv, record_options from installer.local_check import _digest_file from installer.manifest import OTHER_SYSTEMS, entry_copies from installer.narrowing import designated_cores diff --git a/installer/restore.py b/installer/restore.py new file mode 100644 index 000000000..68d4f2928 --- /dev/null +++ b/installer/restore.py @@ -0,0 +1,370 @@ +"""--restore: a backup put back in place, and the install record after it.""" + +from __future__ import annotations + +import json +import os +import re +import stat +import sys +from collections.abc import Callable +from pathlib import Path, PurePosixPath +from typing import NamedTuple + +from installer.events import EVENTS +from installer.host_fs import _clear_read_only, _is_link, _replace_with_copy +from installer.install_record import ( + RECORD_SCHEMA, + RECORD_SUFFIX, + _read_record_bytes, + _record_now, + _save_record, + _valid_setup, + load_record, +) +from installer.invocation import _INVOCATION, installer_id +from installer.local_check import _digest_file +from installer.paths import _safe_relative_path +from installer.safe_replace import ( + BACKUP_DIR, + KEPT, + REMOVED_NOTE, + _NotKept, + _backup_files, + _is_backup_run, +) +from installer.text import _plural, format_size + + +def _backup_note(run: Path) -> dict | None: + """What a removal wrote beside the files it moved into run: the setup, + its folder, its choice before and the record's entries. None for the + backup of files an install replaced, or a note that cannot be read.""" + try: + data = json.loads(_read_record_bytes(run / REMOVED_NOTE).decode("utf-8")) + except (OSError, UnicodeDecodeError, ValueError): + return None + if not isinstance(data, dict) or not isinstance(data.get("platform"), str) \ + or not isinstance(data.get("folder"), str): + return None + setup = {"written": "", "choice": data.get("choice"), "files": data.get("files")} + return data if _valid_setup(setup, Path(data["folder"])) else None + + +def _record_folder(run: Path, path: Path) -> tuple[Path, str] | None: + """The BIOS folder whose record may name a file put back at path, and + its dest there. The holder beside a folder keeps the folder's name as + the first level of each run, the one inside it none.""" + holder, root = run.parent, run.parent.parent + rel = PurePosixPath(*path.relative_to(root).parts) + if len(rel.parts) > 1 and (holder / f"{rel.parts[0]}{RECORD_SUFFIX}").is_file(): + return root / rel.parts[0], PurePosixPath(*rel.parts[1:]).as_posix() + if (holder / f"{root.name or 'folder'}{RECORD_SUFFIX}").is_file(): + return root, rel.as_posix() + return None + + +def _record_without(gone: set[str]) -> Callable[[dict | None], dict | None]: + """The change taking out a setup's entries at the folded dests of gone.""" + def change(setup: dict | None) -> dict | None: + return None if setup is None else { + **setup, "files": [item for item in setup["files"] + if str(item.get("root") or "") not in ("", "data") + or item["dest"].casefold() not in gone]} + return change + + +def _record_after_restore(run: Path, put_back: list[Path]) -> str: + """The record of the folder files went back into, made to say what is + there now: "" once written, else why not. A removal's backup gives its + files back to their setup, with the choice it had. Any other backup + holds the user's own files, which the record never names: its entries + at their places go.""" + note = _backup_note(run) + if note is not None: + folder = Path(note["folder"]) + back = [] + for item in note["files"]: + path = _below(folder, item["dest"])[0] + if path is not None and not _check_ours(path, item)[0]: + back.append(item) + if not back and put_back: + # The files went back, but not where the record's folder is: the + # folder moved or was renamed since the removal. + return f"it is for {folder}, which does not hold the files put back" + if not back: + return "" + return _update_record(folder, note["platform"], + lambda setup: _record_merge(setup, back, note["choice"])) + by_folder: dict[Path, set[str]] = {} + for path in put_back: + found = _record_folder(run, path) + if found is not None: + by_folder.setdefault(found[0], set()).add(found[1].casefold()) + problems = [_update_record(folder, plat, _record_without(gone)) + for folder, gone in by_folder.items() + for plat in sorted((load_record(folder).data or {}).get("setups") or {})] + return next((problem for problem in problems if problem), "") + + +def _recorded_copy(run: Path, dest: Path) -> bool: + """Whether the file at dest is the installer's own copy, as the record + of its folder names it: the collection gives it again, so a restore + replaces it without keeping it.""" + found = _record_folder(run, dest) + if found is None: + return False + try: + info = os.lstat(dest) + except OSError: + return False + if not stat.S_ISREG(info.st_mode) or _is_link(info): + return False + folder, rel = found + items = [item for setup in ((load_record(folder).data or {}).get("setups") or {}).values() + for item in setup.get("files") or [] + if str(item.get("root") or "") in ("", "data") + and item["dest"].casefold() == rel.casefold() and item["size"] == info.st_size] + if not items: + return False + try: + sha1 = _digest_file(dest, ("sha1",))["sha1"] + except OSError: + return False + return any(item["sha1"] == sha1 for item in items) + + +def _record_merge(setup: dict | None, files: list[dict], choice: list[str]) -> dict: + """A setup with files given back and the choice it had before a removal.""" + merged = {(str(item.get("root") or ""), item["dest"]): item + for item in (setup or {}).get("files") or []} + for item in files: + merged[(str(item.get("root") or ""), item["dest"])] = item + return {"list": {"version": None, "generated": None}, **(setup or {}), + "written": _record_now(), "choice": list(choice), + "files": [merged[key] for key in sorted(merged)]} + + +def _update_record(folder: Path, plat: str, + change: Callable[[dict | None], dict | None]) -> str: + """Rewrite the setup plat of folder's record as change makes it, None + taking it out: "" once written, else why not. A record that cannot be + read, or that a newer installer wrote, is left as it is.""" + folder = Path(os.path.abspath(folder)) + read = load_record(folder) + if read.newer or (read.data is None and read.path is not None): + return read.problem + data = read.data or {"setups": {}, "folder": str(folder)} + setups = dict(data["setups"]) + new = change(setups.get(plat)) + if new is None: + setups.pop(plat, None) + else: + setups[plat] = new + if not setups: + if read.path is None: + return "" + # Nothing of ours is left in the folder: the record goes with it. + try: + read.path.unlink() + except OSError as exc: + return exc.strerror or str(exc) + return "" + data = {"schema": RECORD_SCHEMA, "installer": installer_id(), + "folder": str(data.get("folder") or folder), "setups": setups} + where, failure = _save_record(folder, data, read.path) + return "" if where is not None else failure + + +class RestoreResult(NamedTuple): + """What --restore did with a backup run folder, for the lines and the events. + + status: not_backup (the folder is no backup), empty (it holds no file), + planned (--dry-run), done, or not_done (a file failed or the record + could not be updated). dests are the places files went back to (would + go back to, planned), failed [(dest, reason)] those that did not, kept + the new backup folders the files at their places went to, as + KeptFiles.summary gives them, problem why the record was not updated. + """ + + run: Path + status: str + dests: tuple[Path, ...] = () + size: int = 0 + failed: tuple[tuple[Path, str], ...] = () + kept: tuple[dict, ...] = () + problem: str = "" + + @property + def root(self) -> Path: + return self.run.parent.parent + + @property + def code(self) -> int: + """0 when every file went back, 1 when one failed or the record was + not updated, 2 when the folder is no backup.""" + if self.status == "not_backup": + return 2 + return 1 if self.status == "not_done" else 0 + + +def _restore_one(run: Path, src: Path) -> tuple[Path, str]: + """Put the backup's src back at its place: (dest, "") once there, else + (dest, why not).""" + root = run.parent.parent + rel = PurePosixPath(*src.relative_to(run).parts) + dest = root / Path(*rel.parts) + try: + sha1 = _digest_file(src, ("sha1",))["sha1"] + dest.parent.mkdir(parents=True, exist_ok=True) + # A file at the place that is not the backup's copy (a newer one, + # one the user put there) is moved aside first, into a new dated + # backup, as an install keeps what it replaces. Its first level + # is the folder the backup's holder sits in. + holder = (root / rel.parts[0], PurePosixPath(*rel.parts[1:])) \ + if len(rel.parts) > 1 else (root, rel) + if not _recorded_copy(run, dest): + KEPT.keep(*holder, dest, {"sha1": sha1}) + _clear_read_only(dest) + _replace_with_copy(src, dest) + except (OSError, _NotKept) as exc: + return dest, getattr(exc, "strerror", None) or str(exc) + return dest, "" + + +def restore_backup(run: Path, dry_run: bool = False) -> RestoreResult: + """Put every file of a backup run folder back where it was. + + run is a / folder a run wrote, its holder named + retrobios-backup. Each file goes to the same path below the holder's + parent. A file there with other contents is moved into a new dated + backup first, never lost. The install record of its folder is made to + say so. The backup is left in place. Each file put back, or not, is a + restored event as it happens. + """ + run = Path(os.path.abspath(os.path.expanduser(str(run)))) + if not _is_backup_run(run): + return RestoreResult(run, "not_backup") + files = _backup_files(run) + if not files: + return RestoreResult(run, "empty") + root = run.parent.parent + if dry_run: + return RestoreResult(run, "planned", + tuple(root / Path(*src.relative_to(run).parts) for src in files), + sum(src.stat().st_size for src in files)) + size = 0 + put_back: list[Path] = [] + failed: list[tuple[Path, str]] = [] + KEPT.reset() + for src in files: + length = src.stat().st_size + dest, reason = _restore_one(run, src) + EVENTS.emit("restored", folder=str(run), path=str(dest), size=length, + ok=not reason, reason=reason) + if reason: + failed.append((dest, reason)) + continue + put_back.append(dest) + size += length + problem = _record_after_restore(run, put_back) + return RestoreResult(run, "not_done" if failed or problem else "done", tuple(put_back), + size, tuple(failed), tuple(KEPT.summary()), problem) + + +def restore_message(result: RestoreResult) -> str: + """Why a restore put nothing back, in one sentence, else "".""" + if result.status == "not_backup": + return f"{result.run} is not a folder the installer kept files in." + if result.status == "empty": + return f"{result.run} holds no file. Nothing to put back." + return "" + + +def say_restore(result: RestoreResult) -> None: + """--restore's outcome in lines.""" + if result.status == "not_backup": + print(f"Error: {restore_message(result)}", file=sys.stderr) + print(f" Name one of the dated folders inside a {BACKUP_DIR} folder, as " + "--backups lists them.", file=sys.stderr) + return + if result.status == "empty": + print(restore_message(result)) + return + if result.status == "planned": + for dest in result.dests: + print(f" would put back {dest}") + print(f"\nWould put back {_plural(len(result.dests), 'file')} " + f"({format_size(result.size)}) under {result.root}. Nothing was written.") + return + for dest, reason in result.failed: + print(f" failed: {dest} ({reason})", file=sys.stderr) + print(f"\nPut back {_plural(len(result.dests), 'file')} ({format_size(result.size)}) " + f"under {result.root}.") + for item in result.kept: + # The files that sat at those places, never lost. + print(f"Kept {_plural(item['files'], 'file')} that were in their place " + f"({format_size(item['bytes'])}) in {item['folder']}") + if result.failed: + print(f"{_plural(len(result.failed), 'file')} could not be put back.", file=sys.stderr) + if result.problem: + print(f"The install record could not be updated ({result.problem}).", file=sys.stderr) + print(f"The copies are still in {result.run}. To free the space: " + f"{_INVOCATION.launcher()} --delete-backup {_INVOCATION.word(str(result.run))}") + + +def restore_kept(run: Path, dry_run: bool = False) -> int: + """--restore: put a backup back, say it in lines and as a restore + event, and return the exit code.""" + result = restore_backup(run, dry_run) + say_restore(result) + EVENTS.emit("restore", folder=str(result.run), status=result.status, + files=len(result.dests), bytes=result.size, kept=list(result.kept), + problem=result.problem, message=restore_message(result)) + return result.code + + +def _below(folder: Path, dest: str) -> tuple[Path | None, str]: + """The file a record's dest names below folder, reached through no link: + (path, "") or (None, why it is left). A dest that climbs or is absolute + is outside, whatever a record says.""" + try: + rel = _safe_relative_path(dest, "dest") + except ValueError: + return None, "outside" + path = folder + for part in rel.parts[:-1]: + path = path / part + try: + info = os.lstat(path) + except FileNotFoundError: + return None, "gone" + except OSError: + return None, "unreadable" + if _is_link(info): + return None, "link" + if not stat.S_ISDIR(info.st_mode): + return None, "not_a_file" + return path / rel.parts[-1], "" + + +def _check_ours(path: Path, item: dict) -> tuple[str, os.stat_result | None]: + """Why the file at path is not the one the record names, "" when it + is, and what lstat read of it.""" + try: + info = os.lstat(path) + except FileNotFoundError: + return "gone", None + except OSError: + return "unreadable", None + if _is_link(info): + return "link", info + if not stat.S_ISREG(info.st_mode): + return "not_a_file", info + if not re.fullmatch(r"[0-9a-f]{40}", str(item["sha1"])) or info.st_size != item["size"]: + return "changed", info + try: + same = _digest_file(path, ("sha1",))["sha1"] == item["sha1"] + except OSError: + return "unreadable", info + return ("" if same else "changed"), info diff --git a/wiki/architecture.md b/wiki/architecture.md index 694d4ecd1..db8f3c100 100644 --- a/wiki/architecture.md +++ b/wiki/architecture.md @@ -503,7 +503,7 @@ those it imports: | Files and folders | `host_fs`, `paths`, `filesystems`, `config_values`, `local_check`, `safe_replace` | | This machine | `detection_notes`, `detect_os`, `detect_android`, `detect_launchbox`, `detect_frontends`, `cards`, `device`, `cores`, `frontend_folders`, `setups` | | 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` | +| What a run keeps | `narrowing`, `choices`, `romm`, `install_record`, `restore`, `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`, `setup_passes`, `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` |