"""The install record a run leaves beside the BIOS folder: read, written, and the choice it keeps.""" from __future__ import annotations import argparse import datetime import errno import json import os import stat 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 _is_dir, write_atomically from installer.invocation import _INVOCATION, _VALUED_OPTIONS, _command_rank, installer_id from installer.offline import LOCAL from installer.platforms import system_title from installer.safe_replace import ( KeptFiles, _check_holder, ) # 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 # lives in the backup holder beside the folder, never loose in it, for the # reason the backups do. On a card it travels with the card. RECORD_SCHEMA = 1 RECORD_SUFFIX = ".install.json" # The options a record keeps as the choice: what the list was narrowed to. RECORD_CHOICE = ("--system", "--core", "--emulator", "--region", "--for-games", "--required-only", "--all-files", "--target", "--every-board", "--no-game-data", "--installed-cores", "--declared-only") # The record's choice options that narrow the list, --all-files aside. RECORD_NARROWING = tuple(flag for flag in RECORD_CHOICE if flag != "--all-files") _MONTHS = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec") def day_words(when: datetime.datetime) -> str: """A day as a list says it: 3 Nov, its year when not this one.""" day = f"{when.day} {_MONTHS[when.month - 1]}" return day if when.year == datetime.datetime.now().year else f"{day} {when.year}" # The records already said unreadable in this run, said once each. _RECORD_SAID: set[str] = set() # Per platform, the record whose choice this run took (apply_record). _RECORD_TAKEN: dict[str, dict] = {} def record_paths(folder: Path) -> list[Path]: """Where the record of folder is looked for, in order: the holder beside it, then the one inside it that a folder with no writable parent gets.""" folder = Path(os.path.abspath(folder)) name = f"{folder.name or 'folder'}{RECORD_SUFFIX}" return [holder / name for holder, _prefix in KeptFiles._holders(folder)] # Read whole, never past this: a record of every file of the longest list # holds 1.6 MB per setup, and a few setups share one folder. MAX_RECORD_BYTES = 16 * 1024 * 1024 # The choice options that take a value. --for-games takes one or none. _RECORD_VALUED = ("--system", "--core", "--emulator", "--region", "--target") def games_folder_kept(value: str, folder: Path) -> bool: """Whether a recorded --for-games folder may be read again: an absolute path under the folder that holds the BIOS folder (a card's root, the setup's own folder), never another drive or a network share.""" if not value or value.startswith(("\\\\", "//")) or not os.path.isabs(value): return False parent = os.path.normcase(os.path.normpath(os.path.dirname(os.path.abspath(folder)))) games = os.path.normcase(os.path.normpath(value)) try: return os.path.commonpath([parent, games]) == parent except ValueError: # Two drives on Windows: no common path. return False def valid_choice(choice: list[str], folder: Path) -> bool: """Whether every word of a recorded choice is an option of the choice or the value right after one: a record naming --dest, --from or --manifest would put them in the commands printed for the user to copy.""" words = list(choice) while words: flag = words.pop(0) if flag not in RECORD_CHOICE: return False if flag in _RECORD_VALUED: if not words or words[0].startswith("-") or not words[0].strip(): return False value = words.pop(0) if any(ord(char) < 32 or ord(char) == 127 for char in value): return False elif flag == "--for-games" and words and not words[0].startswith("--"): if not games_folder_kept(words.pop(0), folder): return False return True def _valid_setup(setup: object, folder: Path) -> bool: if not isinstance(setup, dict): return False choice, files = setup.get("choice"), setup.get("files") return (isinstance(setup.get("written"), str) and isinstance(choice, list) and all(isinstance(word, str) for word in choice) and valid_choice(choice, folder) and isinstance(files, list) and all(isinstance(item, dict) and isinstance(item.get("dest"), str) and isinstance(item.get("sha1"), str) and isinstance(item.get("size"), int) for item in files)) class RecordRead(NamedTuple): """What reading a record found: the record with its usable setups, where it is, why it cannot be used, whether a newer installer wrote it, and the setups it holds that cannot be used.""" data: dict | None path: Path | None problem: str newer: bool = False dropped: tuple = () def _read_record_bytes(path: Path) -> bytes: """The bytes of a record that is a regular file of a record's size. A FIFO, a device or a folder is refused before it is read: reading one waited forever.""" info = os.stat(path) if not stat.S_ISREG(info.st_mode): raise OSError(errno.EINVAL, "it is not a file") if info.st_size > MAX_RECORD_BYTES: raise OSError(errno.EFBIG, "it is larger than any record") flags = os.O_RDONLY | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_BINARY", 0) handle = os.open(path, flags) try: # Opened without waiting, then checked again: what is open now is # what is read, whatever took the name since the stat. if not stat.S_ISREG(os.fstat(handle).st_mode): raise OSError(errno.EINVAL, "it is not a file") chunks, left = [], MAX_RECORD_BYTES + 1 while left > 0: chunk = os.read(handle, min(left, 1 << 20)) if not chunk: break chunks.append(chunk) left -= len(chunk) finally: os.close(handle) data = b"".join(chunks) if len(data) > MAX_RECORD_BYTES: raise OSError(errno.EFBIG, "it is larger than any record") return data def load_record(folder: Path) -> RecordRead: """The record of folder, read once (RecordRead).""" for path in record_paths(folder): try: text = _read_record_bytes(path).decode("utf-8") except (FileNotFoundError, NotADirectoryError): continue except (OSError, UnicodeDecodeError) as exc: reason = getattr(exc, "strerror", None) or str(exc) return RecordRead(None, path, f"The install record {path} cannot be read ({reason})") try: data = json.loads(text) except ValueError: return RecordRead(None, path, f"The install record {path} is damaged") schema = data.get("schema") if isinstance(data, dict) else None if isinstance(schema, int) and not isinstance(schema, bool) and schema > RECORD_SCHEMA: # Its shape is the newer installer's: kept for it, never read. return RecordRead(None, path, f"The install record {path} was written by a newer " "installer", newer=True) if (not isinstance(data, dict) or not isinstance(data.get("setups"), dict) or not isinstance(data.get("folder"), str) or schema != RECORD_SCHEMA): return RecordRead(None, path, f"The install record {path} is damaged") setups = {name: setup for name, setup in data["setups"].items() if _valid_setup(setup, folder)} dropped = tuple(sorted(str(name) for name in data["setups"] if name not in setups)) return RecordRead({**data, "setups": setups}, path, "", dropped=dropped) return RecordRead(None, None, "") def read_record(folder: Path) -> tuple[dict | None, Path | None, str]: """(the record of folder, where it is, why it cannot be used). Neither a record nor a reason where there is none.""" found = load_record(folder) return found.data, found.path, found.problem def setup_record(plat: str, folder: Path) -> tuple[dict | None, Path | None, str]: """The record of plat in folder, where it is, and why it cannot be used. A record written for a folder of another name (copied, or renamed with it) is not this folder's. A setup of it that cannot be used (an option the choice has no place for, a games folder elsewhere) is damaged, the others still read.""" found = load_record(folder) if found.data is None: return None, found.path, found.problem written_for = str(found.data.get("folder") or "") if Path(written_for).name != Path(os.path.abspath(folder)).name: return None, found.path, "" if plat in found.dropped: return None, found.path, f"The install record {found.path} is damaged" return found.data["setups"].get(plat), found.path, "" def record_day(setup: dict) -> str: """The day a record was written, as the plan says it: 3 Nov.""" try: when = datetime.datetime.fromisoformat(setup["written"].replace("Z", "+00:00")) # Year 1 or 9999 cannot be moved to local time: an unknown day. local = when.astimezone() except (KeyError, TypeError, AttributeError, ValueError, OverflowError, OSError): return "" return day_words(local) def record_options(argv: list[str]) -> list[tuple[str, str | None]]: """A record's choice as (option, value) pairs.""" options: list[tuple[str, str | None]] = [] words = list(argv) while words: flag = words.pop(0) valued = flag in _VALUED_OPTIONS or ( flag == "--for-games" and words and not words[0].startswith("--")) options.append((flag, words.pop(0) if valued and words else None)) return options def choice_words(options: Iterable[tuple[str, str | None]]) -> list[str]: """(option, value) pairs as the words of a record's choice, in their order.""" return [word for flag, value in options for word in ([flag] if value is None else [flag, value])] def record_argv(options: Iterable[tuple[str, str | None]]) -> list[str]: """The choice options a record keeps, as words, in the command's order.""" kept = sorted((option for option in options if option[0] in RECORD_CHOICE), key=_command_rank) if not any(flag in RECORD_NARROWING for flag, _value in kept): # The whole list, chosen as such: a card that holds games later # still gets what was installed before. kept = [("--all-files", None)] return [word for flag, value in kept for word in ([flag] if value is None else [flag, value])] def record_says(setup: dict, manifest: dict | None = None) -> str: """The recorded choice in words: Game Boy Advance, the games, the options chosen, every file.""" options = record_options(setup.get("choice") or []) systems = [system_title(value, manifest) for flag, value in options if flag == "--system" and value] if systems: shown = ", ".join(systems[:3]) return shown + (f" and {len(systems) - 3} more" if len(systems) > 3 else "") if any(flag == "--for-games" for flag, _value in options): return "the games" if any(flag in RECORD_NARROWING for flag, _value in options): return "the options chosen" return "every file" def record_changes(setup: dict, entries: Iterable[dict]) -> tuple[int, int]: """Of the files a choice keeps now, those the list changed since the record and those it did not hold then: (updated, new).""" recorded = {(str(item.get("root") or ""), item["dest"]): item["sha1"] for item in setup.get("files") or []} updated = new = 0 for entry in entries: sha1 = recorded.get((str(entry.get("root") or ""), str(entry.get("dest")))) if sha1 is None: new += 1 elif entry.get("sha1") and sha1 != entry.get("sha1"): updated += 1 return updated, new def record_file(entry: dict, origin: str, root: str = "") -> dict: """One file a run wrote, as the record keeps it.""" return {"dest": str(entry["dest"]), "root": root or str(entry.get("root") or ""), "sha1": str(entry.get("sha1") or ""), "size": int(entry.get("size") or 0), "from": origin} def recorded_data_copies(folder: Path) -> dict[str, set[tuple[str, int]]]: """The data tree files earlier runs wrote in folder, as its record names them: (sha1, size) of each, by destination casefolded.""" copies: dict[str, set[tuple[str, int]]] = {} 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 "") == "data": copies.setdefault(item["dest"].casefold(), set()).add((item["sha1"], item["size"])) return copies def write_record( folder: Path, plat: str, manifest: dict, choice: list[str], files: list[dict], ) -> tuple[Path | None, dict, str]: """Write what this run placed in folder for plat, merged with what earlier runs placed: (where, the record of plat, why it was not written). A record that cannot be read is replaced.""" folder = Path(os.path.abspath(folder)) read = load_record(folder) if read.newer: # What a newer installer wrote is kept for it: rewritten here, the # other setups' history would go. if str(read.path) not in _RECORD_SAID: _RECORD_SAID.add(str(read.path)) print(f" {read.problem}: left as it is.") return None, {"files": [], "written": ""}, f"{read.problem}: left as it is" found = read.path # A record that cannot be read is replaced, said when it was read. One # with a setup that cannot be used keeps its others. data = read.data if read.data is not None else {"setups": {}} previous = data["setups"].get(plat) or {} merged = {(str(item.get("root") or ""), item["dest"]): item for item in previous.get("files") or []} for item in files: merged[(item["root"], item["dest"])] = item setup = { "written": _record_now(), "list": {"version": manifest.get("version"), "generated": manifest.get("generated")}, "choice": choice, "files": [merged[key] for key in sorted(merged)], } data = {"schema": RECORD_SCHEMA, "installer": installer_id(), "folder": str(folder), "setups": {**data["setups"], plat: setup}} where, failure = _save_record(folder, data, found) if where is None: return None, setup, f"The install record could not be written ({failure})" return where, setup, "" def _save_record(folder: Path, data: dict, found: Path | None) -> tuple[Path | None, str]: """Write a record's data where it was read, else where it goes: (where, why nothing could be written).""" text = json.dumps(data, separators=(",", ":"), sort_keys=True) + "\n" places = record_paths(folder) if found is not None and found in places: # Rewritten where it was read: never a second record of one folder. places = [found] + [place for place in places if place != found] failure = "nothing could be written beside the folder" for path in places: try: path.parent.mkdir(exist_ok=True) _check_holder(path.parent) write_atomically(path, text.encode("utf-8")) except OSError as exc: failure = exc.strerror or str(exc) continue return path, "" return None, failure def record_menu_words(setup: dict | None) -> str: """What line mode's menu says of a recorded choice it opens on.""" if setup is None: return "" day = record_day(setup) return f"Same choice as on {day}." if day else "Same choice as last time." def choice_given(args: argparse.Namespace) -> bool: """Whether the command line chose what to install, which a record then never replaces: an option of the choice, or a file list of its own.""" # A namespace built by a caller that predates an option lacks it. return (getattr(args, "for_games", None) is not None or LOCAL.manifest is not None or any(getattr(args, flag[2:].replace("-", "_"), None) for flag in RECORD_CHOICE if flag != "--for-games")) def say_record_problem(plat: str, folder: Path, path: Path | None, problem: str) -> None: """A record that cannot be used, said once and ignored.""" key = str(path) if not problem or key in _RECORD_SAID: return _RECORD_SAID.add(key) message = f"{problem}, so it is ignored." print(f" {message}") EVENTS.emit("record", platform=plat, folder=str(folder), path=key, status="unreadable", choice=[], date="", files=0, message=message) def by_record(args: argparse.Namespace) -> bool: """Whether the run's choice came from the install record: nothing of it was typed, so a part that cannot apply is left out, never refused.""" return bool(getattr(args, "from_record", False)) def drop_recorded(args: argparse.Namespace, plat: str, flag: str, why: str, keep: list[str] | None = None) -> None: """Leave out a recorded option that cannot apply, in one line: the run goes on, and the record written after it no longer holds it. keep, for an option of several names, is the names that still apply.""" name = flag[2:].replace("-", "_") setattr(args, name, list(keep) if keep else build_parser().get_default(name)) _INVOCATION.chosen[plat] = options_without(_INVOCATION.chosen.get(plat, []), flag, keep) print(f" Left out of the recorded choice: {flag} ({why}).") def options_without(options: Iterable[tuple[str, str | None]], flag: str, keep: Iterable[str] | None = None) -> list[tuple[str, str | None]]: """options with flag left out, then given again for each name of keep.""" return [option for option in options if option[0] != flag] + [ (flag, value) for value in keep or []] class RecordedChoice(NamedTuple): """A recorded choice as a run takes it: parsed, its words once the parts that no longer apply are out, and those parts in words.""" parsed: argparse.Namespace choice: list[str] left_out: list[str] def take_recorded_choice(choice: list[str]) -> RecordedChoice | None: """The recorded choice made the run's, None where this installer lacks one of its options. A games folder that is gone gives the card's own.""" try: parsed = build_parser().parse_args(choice) except SystemExit: return None words, left_out = list(choice), [] if isinstance(parsed.for_games, Path) and not _is_dir(parsed.for_games): parsed.for_games = True words = choice_words([(flag, None if flag == "--for-games" else value) for flag, value in record_options(choice)]) left_out.append("its games folder (no longer there)") return RecordedChoice(parsed, words, left_out) def apply_record(args: argparse.Namespace, plat: str, folder: Path) -> dict | None: """Take the choice recorded for plat in folder as the run's, as if its options had been typed: the plan's first choice. Returns the record, None where none is taken.""" setup, path, problem = setup_record(plat, folder) say_record_problem(plat, folder, path, problem) if setup is None: return None taken = take_recorded_choice(setup["choice"]) if taken is None: say_record_problem(plat, folder, path, f"The install record {path} names options this installer lacks") return None parsed = taken.parsed for flag in RECORD_CHOICE: name = flag[2:].replace("-", "_") setattr(args, name, getattr(parsed, name)) if args.for_games is not None: args.all_files = False args.from_record = True options = record_options(taken.choice) if any(flag in RECORD_NARROWING for flag, _value in options): # Said where it narrows the list: the whole list again is the run # a person expects, and said nothing new. _RECORD_TAKEN[plat] = setup _INVOCATION.chosen[plat] = [option for option in options if option[0] != "--all-files"] for part in taken.left_out: print(f" Left out of the recorded choice: {part}.") message = record_menu_words(setup) EVENTS.emit("record", platform=plat, folder=str(folder), path=str(path), status="applied", choice=list(setup["choice"]), date=setup["written"], files=len(setup["files"]), message=message) return setup def _record_now() -> str: return datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")