mirror of
https://github.com/Abdess/retroarch_system.git
synced 2026-12-02 06:18:51 -06:00
refactor: return the restore outcome as a record
This commit is contained in:
1 parent
d676991502
commit
19871672e1
13 files changed
+434
-135
No files matched your search
+1
-1
@@ -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 = "0772b655a6313237ddfe2fcd45386e732b5ed37542fb22c146b4908f35ce09cf"
|
||||
$defaultInstallSha256 = "6f5ccd34b7095ddf994648e8596ad30349e5b181517a535731f34f7440787605"
|
||||
# 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
|
||||
|
||||
+156
-56
@@ -1606,6 +1606,15 @@ EVENT_KEYS: dict[str, tuple[str, ...]] = {
|
||||
"removed": ("platform", "dest", "size", "ok", "reason", "moved_to"),
|
||||
# Each file --restore put back from the backup folder to path.
|
||||
"restored": ("folder", "path", "size", "ok", "reason"),
|
||||
# --restore, once it ends: status not_backup (the folder is no backup,
|
||||
# code 2), empty (it holds no file), planned (--dry-run), done, or
|
||||
# not_done (a file failed, or the install record could not be updated:
|
||||
# problem says why). files and bytes are those put back (would be,
|
||||
# planned), kept [{"folder", "files", "bytes"}] the new backup folders
|
||||
# the files at their places were moved into, as in summary. message
|
||||
# says why nothing went back. A kind of its own, since schema 1 never
|
||||
# adds a key to restored.
|
||||
"restore": ("folder", "status", "files", "bytes", "kept", "problem", "message"),
|
||||
# A backup folder: listed by --backups, made by --remove --backup, or
|
||||
# deleted (not_deleted when a file stayed) by --delete-backup. date is
|
||||
# when it was made (local time), source remove for a removal's, install
|
||||
@@ -10574,82 +10583,152 @@ def _update_record(folder: Path, plat: str,
|
||||
return "" if where is not None else failure
|
||||
|
||||
|
||||
def restore_kept(run: Path, dry_run: bool = False) -> int:
|
||||
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 <holder>/<date-time> 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. Returns the exit code:
|
||||
0 when every file went back, 1 when one failed, 2 when the folder is no
|
||||
backup.
|
||||
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):
|
||||
print(f"Error: {run} is not a folder the installer kept files in.", file=sys.stderr)
|
||||
print(f" Name one of the dated folders inside a {BACKUP_DIR} folder, as "
|
||||
"--backups lists them.", file=sys.stderr)
|
||||
return 2
|
||||
root = run.parent.parent
|
||||
return RestoreResult(run, "not_backup")
|
||||
files = _backup_files(run)
|
||||
if not files:
|
||||
print(f"{run} holds no file. Nothing to put back.")
|
||||
return 0
|
||||
restored = size = failed = 0
|
||||
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:
|
||||
rel = PurePosixPath(*src.relative_to(run).parts)
|
||||
dest = root / Path(*rel.parts)
|
||||
length = src.stat().st_size
|
||||
if dry_run:
|
||||
print(f" would put back {dest}")
|
||||
restored += 1
|
||||
size += length
|
||||
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
|
||||
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:
|
||||
reason = getattr(exc, "strerror", None) or str(exc)
|
||||
print(f" failed: {dest} ({reason})", file=sys.stderr)
|
||||
EVENTS.emit("restored", folder=str(run), path=str(dest), size=length, ok=False,
|
||||
reason=reason)
|
||||
failed += 1
|
||||
continue
|
||||
EVENTS.emit("restored", folder=str(run), path=str(dest), size=length, ok=True,
|
||||
reason="")
|
||||
put_back.append(dest)
|
||||
restored += 1
|
||||
size += length
|
||||
if dry_run:
|
||||
print(f"\nWould put back {_plural(restored, 'file')} ({format_size(size)}) "
|
||||
f"under {root}. Nothing was written.")
|
||||
return 0
|
||||
problem = _record_after_restore(run, put_back)
|
||||
print(f"\nPut back {_plural(restored, 'file')} ({format_size(size)}) under {root}.")
|
||||
for item in KEPT.summary():
|
||||
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 failed:
|
||||
print(f"{_plural(failed, 'file')} could not be put back.", file=sys.stderr)
|
||||
if problem:
|
||||
print(f"The install record could not be updated ({problem}).", file=sys.stderr)
|
||||
print(f"The copies are still in {run}. To free the space: {_INVOCATION.launcher()} "
|
||||
f"--delete-backup {_INVOCATION.word(str(run))}")
|
||||
return 1 if failed or problem else 0
|
||||
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]:
|
||||
@@ -27787,7 +27866,9 @@ def _removal_text(state: TuiState) -> list:
|
||||
|
||||
def tui_action_outcome(state: TuiState) -> list:
|
||||
"""What a More action did, in one line, then where."""
|
||||
events = state.action_events
|
||||
end = next((event for event in state.action_events if event.get("event") == "restore"),
|
||||
None)
|
||||
events = [event for event in state.action_events if event.get("event") != "restore"]
|
||||
done = [event for event in events if event.get("ok", True)]
|
||||
failed = [event for event in events if not event.get("ok", True)]
|
||||
size = format_size(sum(int(event.get("size") or 0) for event in done))
|
||||
@@ -27805,10 +27886,29 @@ def tui_action_outcome(state: TuiState) -> list:
|
||||
lines.append(_styled(f"{_plural(len(failed), 'file')} failed.", "failure"))
|
||||
lines += _details([f" {event.get('dest') or event.get('path')}: {event['reason']}"
|
||||
for event in failed])
|
||||
lines += _restore_end_lines(end)
|
||||
lines.append(_styled(f"{_FOLDER_LABEL}{_short_path(state.dest, state.home)}", "path"))
|
||||
return lines
|
||||
|
||||
|
||||
def _restore_end_lines(end: dict | None) -> list:
|
||||
"""What a restore's end event adds to its outcome: why nothing went
|
||||
back, where the files at their places were kept, and why the install
|
||||
record was not updated."""
|
||||
if end is None:
|
||||
return []
|
||||
message = str(end.get("message") or "")
|
||||
lines: list = [_styled(message, "failure") if end.get("status") == "not_backup"
|
||||
else message] if message else []
|
||||
lines += [f"Kept {_plural(int(item['files']), 'file')} that were in their place "
|
||||
f"({format_size(int(item['bytes']))}) in {item['folder']}"
|
||||
for item in end.get("kept") or []]
|
||||
if end.get("problem"):
|
||||
lines.append(_styled(f"The install record could not be updated ({end['problem']}).",
|
||||
"failure"))
|
||||
return lines
|
||||
|
||||
|
||||
def _confirm_action_text(state: TuiState) -> list[str]:
|
||||
if state.action == "remove":
|
||||
plan = state.removal or {}
|
||||
@@ -30815,7 +30915,7 @@ def _take_action_event(state: TuiState, event: dict) -> bool:
|
||||
state.removal = event
|
||||
elif kind == "backup" and state.run == "backups":
|
||||
state.backups = [*(state.backups or []), event]
|
||||
elif kind in ("removed", "restored", "backup") and state.run in (
|
||||
elif kind in ("removed", "restored", "restore", "backup") and state.run in (
|
||||
"remove", "restore", "delete_backup"):
|
||||
state.action_events.append(event)
|
||||
else:
|
||||
|
||||
+1
-1
@@ -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="0772b655a6313237ddfe2fcd45386e732b5ed37542fb22c146b4908f35ce09cf"
|
||||
DEFAULT_INSTALL_SHA256="6f5ccd34b7095ddf994648e8596ad30349e5b181517a535731f34f7440787605"
|
||||
# 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
|
||||
|
||||
@@ -27,8 +27,8 @@
|
||||
{
|
||||
"dest": "roms/ports/retrobios/install.py",
|
||||
"repo_path": "install.py",
|
||||
"size": 1476406,
|
||||
"sha256": "0772b655a6313237ddfe2fcd45386e732b5ed37542fb22c146b4908f35ce09cf",
|
||||
"size": 1480763,
|
||||
"sha256": "6f5ccd34b7095ddf994648e8596ad30349e5b181517a535731f34f7440787605",
|
||||
"executable": false
|
||||
},
|
||||
{
|
||||
@@ -71,8 +71,8 @@
|
||||
"muos": {
|
||||
"archive": {
|
||||
"dest": "ARCHIVE/RetroBIOS.muxapp",
|
||||
"size": 1530031,
|
||||
"sha256": "73d52c29e416292b30962061f8c00721ad5fb42ea64decdd7b72c3979b84386d"
|
||||
"size": 1534388,
|
||||
"sha256": "46f51d49c39fb356ee7c0e32480764503f388dd0cb06096b08fb05f811f89e15"
|
||||
},
|
||||
"members": [
|
||||
{
|
||||
@@ -92,8 +92,8 @@
|
||||
{
|
||||
"name": "RetroBIOS/install.py",
|
||||
"repo_path": "install.py",
|
||||
"size": 1476406,
|
||||
"sha256": "0772b655a6313237ddfe2fcd45386e732b5ed37542fb22c146b4908f35ce09cf",
|
||||
"size": 1480763,
|
||||
"sha256": "6f5ccd34b7095ddf994648e8596ad30349e5b181517a535731f34f7440787605",
|
||||
"executable": false
|
||||
},
|
||||
{
|
||||
@@ -166,8 +166,8 @@
|
||||
{
|
||||
"dest": ".config/modules/retrobios/install.py",
|
||||
"repo_path": "install.py",
|
||||
"size": 1476406,
|
||||
"sha256": "0772b655a6313237ddfe2fcd45386e732b5ed37542fb22c146b4908f35ce09cf",
|
||||
"size": 1480763,
|
||||
"sha256": "6f5ccd34b7095ddf994648e8596ad30349e5b181517a535731f34f7440787605",
|
||||
"executable": false
|
||||
},
|
||||
{
|
||||
|
||||
@@ -183,6 +183,15 @@ EVENT_KEYS: dict[str, tuple[str, ...]] = {
|
||||
"removed": ("platform", "dest", "size", "ok", "reason", "moved_to"),
|
||||
# Each file --restore put back from the backup folder to path.
|
||||
"restored": ("folder", "path", "size", "ok", "reason"),
|
||||
# --restore, once it ends: status not_backup (the folder is no backup,
|
||||
# code 2), empty (it holds no file), planned (--dry-run), done, or
|
||||
# not_done (a file failed, or the install record could not be updated:
|
||||
# problem says why). files and bytes are those put back (would be,
|
||||
# planned), kept [{"folder", "files", "bytes"}] the new backup folders
|
||||
# the files at their places were moved into, as in summary. message
|
||||
# says why nothing went back. A kind of its own, since schema 1 never
|
||||
# adds a key to restored.
|
||||
"restore": ("folder", "status", "files", "bytes", "kept", "problem", "message"),
|
||||
# A backup folder: listed by --backups, made by --remove --backup, or
|
||||
# deleted (not_deleted when a file stayed) by --delete-backup. date is
|
||||
# when it was made (local time), source remove for a removal's, install
|
||||
|
||||
+124
-54
@@ -620,82 +620,152 @@ def _update_record(folder: Path, plat: str,
|
||||
return "" if where is not None else failure
|
||||
|
||||
|
||||
def restore_kept(run: Path, dry_run: bool = False) -> int:
|
||||
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 <holder>/<date-time> 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. Returns the exit code:
|
||||
0 when every file went back, 1 when one failed, 2 when the folder is no
|
||||
backup.
|
||||
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):
|
||||
print(f"Error: {run} is not a folder the installer kept files in.", file=sys.stderr)
|
||||
print(f" Name one of the dated folders inside a {BACKUP_DIR} folder, as "
|
||||
"--backups lists them.", file=sys.stderr)
|
||||
return 2
|
||||
root = run.parent.parent
|
||||
return RestoreResult(run, "not_backup")
|
||||
files = _backup_files(run)
|
||||
if not files:
|
||||
print(f"{run} holds no file. Nothing to put back.")
|
||||
return 0
|
||||
restored = size = failed = 0
|
||||
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:
|
||||
rel = PurePosixPath(*src.relative_to(run).parts)
|
||||
dest = root / Path(*rel.parts)
|
||||
length = src.stat().st_size
|
||||
if dry_run:
|
||||
print(f" would put back {dest}")
|
||||
restored += 1
|
||||
size += length
|
||||
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
|
||||
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:
|
||||
reason = getattr(exc, "strerror", None) or str(exc)
|
||||
print(f" failed: {dest} ({reason})", file=sys.stderr)
|
||||
EVENTS.emit("restored", folder=str(run), path=str(dest), size=length, ok=False,
|
||||
reason=reason)
|
||||
failed += 1
|
||||
continue
|
||||
EVENTS.emit("restored", folder=str(run), path=str(dest), size=length, ok=True,
|
||||
reason="")
|
||||
put_back.append(dest)
|
||||
restored += 1
|
||||
size += length
|
||||
if dry_run:
|
||||
print(f"\nWould put back {_plural(restored, 'file')} ({format_size(size)}) "
|
||||
f"under {root}. Nothing was written.")
|
||||
return 0
|
||||
problem = _record_after_restore(run, put_back)
|
||||
print(f"\nPut back {_plural(restored, 'file')} ({format_size(size)}) under {root}.")
|
||||
for item in KEPT.summary():
|
||||
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 failed:
|
||||
print(f"{_plural(failed, 'file')} could not be put back.", file=sys.stderr)
|
||||
if problem:
|
||||
print(f"The install record could not be updated ({problem}).", file=sys.stderr)
|
||||
print(f"The copies are still in {run}. To free the space: {_INVOCATION.launcher()} "
|
||||
f"--delete-backup {_INVOCATION.word(str(run))}")
|
||||
return 1 if failed or problem else 0
|
||||
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]:
|
||||
|
||||
@@ -457,7 +457,9 @@ def _removal_text(state: TuiState) -> list:
|
||||
|
||||
def tui_action_outcome(state: TuiState) -> list:
|
||||
"""What a More action did, in one line, then where."""
|
||||
events = state.action_events
|
||||
end = next((event for event in state.action_events if event.get("event") == "restore"),
|
||||
None)
|
||||
events = [event for event in state.action_events if event.get("event") != "restore"]
|
||||
done = [event for event in events if event.get("ok", True)]
|
||||
failed = [event for event in events if not event.get("ok", True)]
|
||||
size = format_size(sum(int(event.get("size") or 0) for event in done))
|
||||
@@ -475,10 +477,29 @@ def tui_action_outcome(state: TuiState) -> list:
|
||||
lines.append(_styled(f"{_plural(len(failed), 'file')} failed.", "failure"))
|
||||
lines += _details([f" {event.get('dest') or event.get('path')}: {event['reason']}"
|
||||
for event in failed])
|
||||
lines += _restore_end_lines(end)
|
||||
lines.append(_styled(f"{_FOLDER_LABEL}{_short_path(state.dest, state.home)}", "path"))
|
||||
return lines
|
||||
|
||||
|
||||
def _restore_end_lines(end: dict | None) -> list:
|
||||
"""What a restore's end event adds to its outcome: why nothing went
|
||||
back, where the files at their places were kept, and why the install
|
||||
record was not updated."""
|
||||
if end is None:
|
||||
return []
|
||||
message = str(end.get("message") or "")
|
||||
lines: list = [_styled(message, "failure") if end.get("status") == "not_backup"
|
||||
else message] if message else []
|
||||
lines += [f"Kept {_plural(int(item['files']), 'file')} that were in their place "
|
||||
f"({format_size(int(item['bytes']))}) in {item['folder']}"
|
||||
for item in end.get("kept") or []]
|
||||
if end.get("problem"):
|
||||
lines.append(_styled(f"The install record could not be updated ({end['problem']}).",
|
||||
"failure"))
|
||||
return lines
|
||||
|
||||
|
||||
def _confirm_action_text(state: TuiState) -> list[str]:
|
||||
if state.action == "remove":
|
||||
plan = state.removal or {}
|
||||
|
||||
@@ -52,7 +52,7 @@ def _take_action_event(state: TuiState, event: dict) -> bool:
|
||||
state.removal = event
|
||||
elif kind == "backup" and state.run == "backups":
|
||||
state.backups = [*(state.backups or []), event]
|
||||
elif kind in ("removed", "restored", "backup") and state.run in (
|
||||
elif kind in ("removed", "restored", "restore", "backup") and state.run in (
|
||||
"remove", "restore", "delete_backup"):
|
||||
state.action_events.append(event)
|
||||
else:
|
||||
|
||||
@@ -44,6 +44,7 @@
|
||||
"removal_plan",
|
||||
"removed",
|
||||
"restored",
|
||||
"restore",
|
||||
"backup",
|
||||
"pack",
|
||||
"end"
|
||||
@@ -153,6 +154,9 @@
|
||||
{
|
||||
"$ref": "#/$defs/restored"
|
||||
},
|
||||
{
|
||||
"$ref": "#/$defs/restore"
|
||||
},
|
||||
{
|
||||
"$ref": "#/$defs/backup"
|
||||
},
|
||||
@@ -1218,7 +1222,11 @@
|
||||
"deleted",
|
||||
"not_deleted",
|
||||
"planned",
|
||||
"failed"
|
||||
"failed",
|
||||
"not_backup",
|
||||
"empty",
|
||||
"done",
|
||||
"not_done"
|
||||
]
|
||||
},
|
||||
"choice": {
|
||||
@@ -1373,6 +1381,66 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"restore": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"required": [
|
||||
"event",
|
||||
"folder",
|
||||
"status",
|
||||
"files",
|
||||
"bytes",
|
||||
"kept",
|
||||
"problem",
|
||||
"message"
|
||||
],
|
||||
"properties": {
|
||||
"event": {
|
||||
"const": "restore"
|
||||
},
|
||||
"folder": {
|
||||
"type": "string"
|
||||
},
|
||||
"status": {
|
||||
"enum": [
|
||||
"applied",
|
||||
"written",
|
||||
"unreadable",
|
||||
"not_written",
|
||||
"listed",
|
||||
"made",
|
||||
"deleted",
|
||||
"not_deleted",
|
||||
"planned",
|
||||
"failed",
|
||||
"not_backup",
|
||||
"empty",
|
||||
"done",
|
||||
"not_done"
|
||||
]
|
||||
},
|
||||
"files": {
|
||||
"type": "integer",
|
||||
"minimum": 0
|
||||
},
|
||||
"bytes": {
|
||||
"type": "integer",
|
||||
"minimum": 0
|
||||
},
|
||||
"kept": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object"
|
||||
}
|
||||
},
|
||||
"problem": {
|
||||
"type": "string"
|
||||
},
|
||||
"message": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"backup": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
@@ -1421,7 +1489,11 @@
|
||||
"deleted",
|
||||
"not_deleted",
|
||||
"planned",
|
||||
"failed"
|
||||
"failed",
|
||||
"not_backup",
|
||||
"empty",
|
||||
"done",
|
||||
"not_done"
|
||||
]
|
||||
},
|
||||
"message": {
|
||||
@@ -1482,7 +1554,11 @@
|
||||
"deleted",
|
||||
"not_deleted",
|
||||
"planned",
|
||||
"failed"
|
||||
"failed",
|
||||
"not_backup",
|
||||
"empty",
|
||||
"done",
|
||||
"not_done"
|
||||
]
|
||||
},
|
||||
"message": {
|
||||
|
||||
@@ -27,13 +27,14 @@ KEY_TYPES: dict[str, dict] = {
|
||||
**dict.fromkeys((
|
||||
"installer", "os", "os_name", "stage", "reason", "platform", "message",
|
||||
"folder", "dest", "system", "name", "bios_dir", "path", "member",
|
||||
"list_version", "installed_version", "board", "core", "date", "moved_to",
|
||||
"list_version", "installed_version", "board", "core", "date", "moved_to", "problem",
|
||||
), _TEXT),
|
||||
"mode": {"enum": ["install", "check", "dry-run", "list", "remove", "restore", "pack"]},
|
||||
"source": {"enum": ["remove", "install"]},
|
||||
"state": {"enum": ["present", "wrong_hash", "missing"]},
|
||||
"status": {"enum": ["applied", "written", "unreadable", "not_written", "listed", "made",
|
||||
"deleted", "not_deleted", "planned", "failed"]},
|
||||
"deleted", "not_deleted", "planned", "failed", "not_backup",
|
||||
"empty", "done", "not_done"]},
|
||||
**dict.fromkeys((
|
||||
"files", "files_done", "files_total", "bytes", "bytes_done", "bytes_total",
|
||||
"bytes_local", "bytes_network", "size", "present", "missing", "wrong_hash",
|
||||
|
||||
@@ -343,8 +343,10 @@ class Events(unittest.TestCase):
|
||||
folder = listed[1]["folder"]
|
||||
back = repo.events(repo.run("--restore", folder, "--events"))
|
||||
self.assertEqual([event["event"] for event in back],
|
||||
["start", "restored", "restored", "end"])
|
||||
["start", "restored", "restored", "restore", "end"])
|
||||
self.assertEqual(back[0]["mode"], "restore")
|
||||
self.assertEqual((back[3]["status"], back[3]["files"], back[3]["problem"],
|
||||
back[3]["message"]), ("done", 2, "", ""))
|
||||
gone = repo.events(repo.run("--delete-backup", folder, "--events", "--yes"))
|
||||
self.assertEqual([event["event"] for event in gone], ["start", "backup", "end"])
|
||||
self.assertEqual((gone[1]["status"], gone[2]["code"]), ("deleted", 0))
|
||||
@@ -688,11 +690,10 @@ class ReviewOfTheRemoval(unittest.TestCase):
|
||||
repo.root.rename(moved)
|
||||
try:
|
||||
run = moved / install.BACKUP_DIR / backup["folder"].name
|
||||
with contextlib.redirect_stdout(io.StringIO()), \
|
||||
contextlib.redirect_stderr(io.StringIO()) as err:
|
||||
code = install.restore_kept(run)
|
||||
self.assertEqual(code, 1)
|
||||
self.assertIn("The install record could not be updated", err.getvalue())
|
||||
result = install.restore_backup(run)
|
||||
self.assertEqual((result.status, result.code, result.failed),
|
||||
("not_done", 1, ()))
|
||||
self.assertIn("which does not hold the files put back", result.problem)
|
||||
self.assertTrue((moved / "dest" / "gba_bios.bin").is_file())
|
||||
finally:
|
||||
moved.rename(repo.root)
|
||||
|
||||
@@ -15676,6 +15676,26 @@ class MoreScreens(unittest.TestCase):
|
||||
press(state, "enter")
|
||||
self.assertEqual(state.exit_code, 1)
|
||||
|
||||
def test_a_put_back_says_why_it_is_not_done_and_where_files_were_kept(self):
|
||||
folder = str(BACKUPS[0]["folder"])
|
||||
state = backups_state("putback")
|
||||
press(state, "enter", "enter")
|
||||
install.tui_receive(state, ("event", state.run_id, {
|
||||
"event": "restored", "folder": folder, "path": "/bios/scph5500.bin",
|
||||
"size": 524288, "ok": True, "reason": ""}))
|
||||
install.tui_receive(state, ("event", state.run_id, {
|
||||
"event": "restore", "folder": folder, "status": "not_done", "files": 1,
|
||||
"bytes": 524288, "kept": [{"folder": "/kept/20261122-101010", "files": 1,
|
||||
"bytes": 4}],
|
||||
"problem": "it is for /bios, which does not hold the files put back",
|
||||
"message": ""}))
|
||||
install.tui_receive(state, ("ended", state.run_id, 1, []))
|
||||
text = screen_text(install.tui_view(state, 100, 30))
|
||||
self.assertIn("Put back 1 file, 512.0 KB.", text)
|
||||
self.assertIn("Kept 1 file that were in their place (4 B) in /kept/20261122-101010",
|
||||
text)
|
||||
self.assertIn("The install record could not be updated (it is for /bios", text)
|
||||
|
||||
def test_put_back_and_delete_name_the_backup_alone(self):
|
||||
folder = BACKUPS[0]["folder"]
|
||||
for purpose, run, argv in (
|
||||
|
||||
+3
-2
@@ -922,7 +922,7 @@ anything is removed.
|
||||
Exit codes: `0` once done, `1` when a file or the record could not be
|
||||
written, `2` when nothing was done (no record, nothing to remove, no `--yes`
|
||||
without a terminal, or no at the question). With `--events` the run writes
|
||||
`removal_plan`, `removed`, `backup` and `restored` events, see
|
||||
`removal_plan`, `removed`, `backup`, `restored` and `restore` events, see
|
||||
[Machine-readable events](#machine-readable-events).
|
||||
|
||||
## Making a pack { #making-a-pack }
|
||||
@@ -2256,13 +2256,14 @@ other schemas under `api/v1/schemas/`.
|
||||
| `removal_plan` | `platform`, `folder`, `files`, `bytes`, `systems`, `dests`, `kept`, `gone`, `backup`, `message` | With `--remove`, before anything is removed, and all a `--dry-run` writes: `dests` the files that go in record order, `bytes` the space they free, `systems` those losing a file, `kept` a `{dest, reason}` for each file left (`shared`, `changed`, `link`, `not_a_file`, `outside`, `not_servable`, `unreadable`, `not_recorded`), `gone` the recorded files no longer there, `backup` whether they are moved rather than deleted. With `files` 0 and a `message` when nothing is removed before a plan: no record says what is the installer's, the folder is not there, or a `--file` lies outside it |
|
||||
| `removed` | `platform`, `dest`, `size`, `ok`, `reason`, `moved_to` | Each file `--remove` took. `ok` is false, with `reason`, for a file that stays. `moved_to` is its place in the backup with `--backup`, empty otherwise |
|
||||
| `restored` | `folder`, `path`, `size`, `ok`, `reason` | Each file `--restore` put back from the backup `folder` to `path` |
|
||||
| `restore` | `folder`, `status`, `files`, `bytes`, `kept`, `problem`, `message` | Once `--restore` ends: `status` is `not_backup` (code 2), `empty`, `planned` with `--dry-run`, `done`, or `not_done` when a file failed or the install record could not be updated (`problem` says why). `files` and `bytes` are those put back, `kept` the new backup folders the files at their places went to, as in `summary`. `message` says why nothing went back |
|
||||
| `backup` | `folder`, `date`, `files`, `bytes`, `source`, `status`, `message` | A backup folder: `status` is `listed` by `--backups`, `made` by `--remove --backup`, `deleted` or `not_deleted` by `--delete-backup`. `date` is when it was made, local time. `source` is `remove` for a removal's backup and `install` for the files an install replaced |
|
||||
| `pack` | `platform`, `path`, `files`, `bytes`, `size`, `parts`, `status`, `message` | With `--pack`, once: `status` is `planned` with `--dry-run`, `written` once every part is in place, `failed` when no pack was written (`message` says why). `files` and `bytes` count the pack's members, each file stored once, `size` what the written files take on disk (0 unless `written`), `parts` each file written or to be written, the pack alone when it is one ZIP |
|
||||
| `end` | `code` | Last line, with the exit status the process returns (see [Exit status](#exit-status)) |
|
||||
|
||||
<!-- /generated: events -->
|
||||
|
||||
Schema 1 can gain a kind (`found` came with `--from`, `declared` with `--declared-only`, `unsearched` with the search that goes on past a closed folder, `app` with `--add-app`, `data` with the size of the data trees, `space` with the space the run writes, `version` with the list's version, `record` with the install record, `removal_plan`, `removed`, `restored` and `backup` with removal, `pack` with `--pack`), never a key of an
|
||||
Schema 1 can gain a kind (`found` came with `--from`, `declared` with `--declared-only`, `unsearched` with the search that goes on past a closed folder, `app` with `--add-app`, `data` with the size of the data trees, `space` with the space the run writes, `version` with the list's version, `record` with the install record, `removal_plan`, `removed`, `restored`, `restore` and `backup` with removal, `pack` with `--pack`), never a key of an
|
||||
existing kind: a reader skips a kind it does not know. An option refused
|
||||
before the run starts (`install.py: error:`, code 2) writes
|
||||
no event at all. A program reads a missing `end` as that case, or as a
|
||||
|
||||
Reference in new issue
Block a user