From 92462effc641f908bbfb961a4e54fa927749a918 Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Wed, 11 Nov 2026 17:17:42 +0100 Subject: [PATCH 1/6] feat: make a pack from the installer --pack downloads the narrowed choice into a pack ZIP laid out as --from-pack reads it, the list narrowed to the choice inside. Every member is checked against its SHA-1 before the ZIP is closed, and a failure leaves no file behind. --split writes parts that are each a whole ZIP, and a pack past 4 GB on a FAT32 drive is split by itself. More on the plan holds Make a pack, its plan and its result. Event pack. --- install.py | 965 +++++++++++++++++- tests/fixtures/tui/colour-120x40.txt | 131 ++- tests/fixtures/tui/colour-40x12.txt | 49 +- tests/fixtures/tui/colour-40x15.txt | 58 +- tests/fixtures/tui/colour-80x24.txt | 83 +- tests/fixtures/tui/more-120x40.txt | 2 +- tests/fixtures/tui/more-40x12.txt | 2 +- tests/fixtures/tui/more-40x15.txt | 2 +- tests/fixtures/tui/more-80x24.txt | 2 +- tests/fixtures/tui/pack-done-120x40.txt | 40 + tests/fixtures/tui/pack-done-40x12.txt | 12 + tests/fixtures/tui/pack-done-40x15.txt | 15 + tests/fixtures/tui/pack-done-80x24.txt | 24 + tests/fixtures/tui/pack-plan-120x40.txt | 40 + tests/fixtures/tui/pack-plan-40x12.txt | 12 + tests/fixtures/tui/pack-plan-40x15.txt | 15 + tests/fixtures/tui/pack-plan-80x24.txt | 24 + tests/fixtures/tui/pack-plan-parts-120x40.txt | 40 + tests/fixtures/tui/pack-plan-parts-40x12.txt | 12 + tests/fixtures/tui/pack-plan-parts-40x15.txt | 15 + tests/fixtures/tui/pack-plan-parts-80x24.txt | 24 + tests/fixtures/tui/plan-120x40.txt | 2 +- tests/fixtures/tui/plan-40x12.txt | 4 +- tests/fixtures/tui/plan-40x15.txt | 2 +- tests/fixtures/tui/plan-80x24.txt | 2 +- tests/fixtures/tui/plan-games-120x40.txt | 2 +- tests/fixtures/tui/plan-games-40x12.txt | 2 +- tests/fixtures/tui/plan-games-40x15.txt | 4 +- tests/fixtures/tui/plan-games-80x24.txt | 2 +- tests/fixtures/tui/plan-in-place-120x40.txt | 2 +- tests/fixtures/tui/plan-in-place-40x12.txt | 2 +- tests/fixtures/tui/plan-in-place-40x15.txt | 2 +- tests/fixtures/tui/plan-in-place-80x24.txt | 2 +- tests/fixtures/tui/route-evmapy.txt | 190 +++- tests/fixtures/tui/route-gptokeyb.txt | 190 +++- tests/fixtures/tui/route-gptokeyb_muxterm.txt | 190 +++- tests/fixtures/tui/route-keys.txt | 190 +++- tests/fixtures/tui/route-miyoo.txt | 190 +++- tests/fixtures/tui/route-muxterm.txt | 190 +++- tests/test_install_pack.py | 455 +++++++++ tests/test_install_tui.py | 149 ++- 41 files changed, 3174 insertions(+), 165 deletions(-) create mode 100644 tests/fixtures/tui/pack-done-120x40.txt create mode 100644 tests/fixtures/tui/pack-done-40x12.txt create mode 100644 tests/fixtures/tui/pack-done-40x15.txt create mode 100644 tests/fixtures/tui/pack-done-80x24.txt create mode 100644 tests/fixtures/tui/pack-plan-120x40.txt create mode 100644 tests/fixtures/tui/pack-plan-40x12.txt create mode 100644 tests/fixtures/tui/pack-plan-40x15.txt create mode 100644 tests/fixtures/tui/pack-plan-80x24.txt create mode 100644 tests/fixtures/tui/pack-plan-parts-120x40.txt create mode 100644 tests/fixtures/tui/pack-plan-parts-40x12.txt create mode 100644 tests/fixtures/tui/pack-plan-parts-40x15.txt create mode 100644 tests/fixtures/tui/pack-plan-parts-80x24.txt create mode 100644 tests/test_install_pack.py diff --git a/install.py b/install.py index f01e2d8cc..4c8bcbbf3 100644 --- a/install.py +++ b/install.py @@ -685,8 +685,8 @@ class Progress: # exactly these keys besides "event", in this order, and nothing else. EVENT_SCHEMA = 1 EVENT_KEYS: dict[str, tuple[str, ...]] = { - # mode: install, check, dry-run, list, remove (--remove, --delete-backup) or - # restore. + # mode: install, check, dry-run, list, remove (--remove, --delete-backup), + # restore or pack (--pack, with --dry-run too). "start": ("schema", "installer", "mode"), # A folder detection could not look in, once each, before detect: the # probes under it counted as absent and the others went on. reason is @@ -842,6 +842,10 @@ EVENT_KEYS: dict[str, tuple[str, ...]] = { # when it was made (local time), source remove for a removal's, install # for the files an install replaced. "backup": ("folder", "date", "files", "bytes", "source", "status", "message"), + # --pack: planned (--dry-run), written or failed. files and bytes are + # the pack's members, each stored once, size what it takes on disk, + # parts each file written (the pack alone when it is one ZIP). + "pack": ("platform", "path", "files", "bytes", "size", "parts", "status", "message"), "end": ("code",), } # Seconds between two progress events while bytes arrive. @@ -888,6 +892,8 @@ def _event_mode(args: argparse.Namespace) -> str: return "restore" if getattr(args, "backups", False): return "list" + if getattr(args, "pack", None) is not None: + return "pack" if args.check: return "check" if args.dry_run: @@ -13508,9 +13514,12 @@ class PackSource: def platforms(self) -> list[str]: """The platforms the pack's name spells, several for a grouped pack.""" - stem = "_" + self.name[: -len("_BIOS_Pack.zip")] + "_" - return [plat for plat in AVAILABLE_PLATFORMS - if f"_{PLATFORM_NAMES[plat].replace(' ', '_')}_" in stem] + spelled = pack_name_platforms(self.name) + if spelled: + return spelled + # A pack made by --pack under a name of the user's says it inside. + named = (self.install_list or {}).get("platform") + return [named] if named in AVAILABLE_PLATFORMS else [] def manifest(self, plat: str) -> dict: """A file list for plat: the install list the pack carries, else one @@ -13640,6 +13649,636 @@ def pack_lacks_words(count: int, total: int) -> str: f"{name}: {'it' if count == 1 else 'they'} cannot be installed from it.") +# --pack writes the narrowed choice as a pack --from-pack reads: each file +# once by its SHA-1, at its destination (a file of another root under that +# root's name), each data tree at its place, and manifest.json carrying the +# list narrowed to the choice. The bytes depend on the inputs alone: members +# in a fixed order, a fixed date and mode, one compression level, as +# generate_pack.py writes its packs. +PACK_NAME_END = "_BIOS_Pack.zip" +PACK_MEMBER_DATE = (1980, 1, 1, 0, 0, 0) +PACK_COMPRESSLEVEL = 9 +# FAT32 holds no file of 4 GiB or more (its size field is 32 bits). A pack +# that would pass that on such a drive is written in parts of at most this +# many bytes, the margin keeping each well under. +FAT_FILE_LIMIT = 4 * 1024 ** 3 - 1 +FAT_PART_BYTES = 4 * 1024 ** 3 - 64 * 1024 ** 2 +MIN_PART_BYTES = 64 * 1024 +# The marker each part carries at its root, as scripts/split_pack.py writes +# it: the sizes at a fixed width, so its length does not depend on them. +PART_SIZE_WIDTH = 13 +# A member may grow under deflate (zlib's deflateBound is under one byte in +# a thousand, plus a few), and its headers carry a ZIP64 field past 2 GiB. +# A part is planned on these bounds, never on the compressed size, which is +# known only once written. +_ZIP_LOCAL_BYTES = 30 + 20 +_ZIP_CENTRAL_BYTES = 46 + 28 +_ZIP_END_BYTES = 22 + 56 + 20 + + +class PackError(Exception): + """A pack that cannot be made as asked: nothing is written.""" + + +class PackMember(NamedTuple): + """One member of a pack being made: its name, the bytes it must hold + and the file they are read from.""" + + name: str + sha1: str + size: int + source: Path + + +def parse_part_size(text: str) -> int: + """--split SIZE: bytes, or a number with K, M or G (powers of 1024).""" + match = re.fullmatch(r"\s*(\d+)\s*([KMG]?)(?:I?B)?\s*", text, re.IGNORECASE) + if match is None: + raise argparse.ArgumentTypeError( + f"{text!r} is not a size: give bytes, or a number with K, M or G (1900M)") + size = int(match[1]) * 1024 ** " KMG".index((match[2] or " ").upper()) + if size < MIN_PART_BYTES: + raise argparse.ArgumentTypeError( + f"a part of {format_size(size)} is too small: give {format_size(MIN_PART_BYTES)} " + "or more") + return size + + +def pack_default_name(plat: str, narrowed: bool) -> str: + """_BIOS_Pack.zip, with _Custom when the choice narrows the + list, as generate_pack.py names a narrowed pack.""" + stem = PLATFORM_NAMES.get(plat, plat).replace(" ", "_") + return f"{stem}{'_Custom' if narrowed else ''}{PACK_NAME_END}" + + +def pack_path(given: Path, plat: str, narrowed: bool) -> Path: + """The pack --pack names: the file given, or the default name inside a + folder given.""" + path = Path(os.path.expanduser(str(given))) + if _is_dir(path) or str(given).endswith(("/", os.sep)): + path = path / pack_default_name(plat, narrowed) + return path.absolute() + + +def pack_name_platforms(name: str) -> list[str]: + """The platforms a pack's name spells, as PackSource reads them.""" + if not name.endswith(PACK_NAME_END): + return [] + stem = "_" + name[: -len(PACK_NAME_END)] + "_" + return [plat for plat in AVAILABLE_PLATFORMS + if f"_{PLATFORM_NAMES[plat].replace(' ', '_')}_" in stem] + + +def mountinfo_types(text: str) -> list[tuple[str, str]]: + """(mount point, file system type) of each line of /proc/self/mountinfo: + the point is field 5, its space, tab and backslash written as octal + escapes, the type the first field after the " - " separator (proc(5)).""" + mounts = [] + for line in text.splitlines(): + head, _sep, tail = line.partition(" - ") + fields = head.split(" ") + if len(fields) > 4 and tail: + point = re.sub(r"\\([0-7]{3})", lambda m: chr(int(m.group(1), 8)), fields[4]) + mounts.append((point, tail.split(" ")[0])) + return mounts + + +def mount_list_types(text: str) -> list[tuple[str, str]]: + """(mount point, file system type) of each line macOS's mount prints: + "/dev/disk4s1 on /Volumes/CARD (msdos, local, nodev)".""" + return [(found[1], found[2]) for found in + (re.match(r".+? on (.+) \(([^,)]+)", line) for line in text.splitlines()) + if found] + + +def fat_mounted(target: Path, mounts: list[tuple[str, str]]) -> bool: + """Whether the deepest mount holding target is FAT (vfat on Linux, + msdos on macOS).""" + best = "" + kind = "" + for point, fstype in mounts: + mount = Path(point) + if (target == mount or mount in target.parents) and len(point) >= len(best): + best, kind = point, fstype + return kind.lower() in ("vfat", "msdos", "fat") + + +def fat32_drive(folder: Path) -> bool: + """Whether folder is on a FAT32 (or FAT16) drive, which holds no file of + 4 GiB: the mount table's type on Linux, the volume's file system on + Windows, the mount list on macOS. False where the system does not say.""" + probe = folder + while not _is_dir(probe) and probe != probe.parent: + probe = probe.parent + if os.name == "nt": + try: + import ctypes # noqa: PLC0415 + root = ctypes.create_unicode_buffer(261) + kind = ctypes.create_unicode_buffer(261) + kernel = ctypes.windll.kernel32 # type: ignore[attr-defined] + if not kernel.GetVolumePathNameW(str(probe), root, 261): + return False + if not kernel.GetVolumeInformationW(root, None, 0, None, None, None, kind, 261): + return False + except (AttributeError, OSError): + return False + return kind.value.upper() in ("FAT32", "FAT") + try: + target = probe.resolve() + if sys.platform == "darwin": + listing = subprocess.run(["/sbin/mount"], capture_output=True, text=True, + timeout=5, check=False).stdout + return fat_mounted(target, mount_list_types(listing)) + text = Path("/proc/self/mountinfo").read_text(encoding="utf-8", errors="replace") + except (OSError, subprocess.SubprocessError): + return False + return fat_mounted(target, mountinfo_types(text)) + + +def pack_layout(files: list[dict], data_dirs: list[dict]) -> tuple[ + dict[str, tuple[str, int]], list[dict], dict[str, dict]]: + """Where each file of the choice goes in the pack: the members, by name, + with their SHA-1 and size, the list manifest.json carries (path, sha1, + size, systems) of the BIOS files, and the entry each member that no + data tree holds is fetched as. + + A data tree's files take the path the reader looks under. A BIOS file + is stored once by its SHA-1: at its dest, a file of another root (the + save directory, an emulator's folder) under the root's name, and below + by-sha1/ when another file already holds that name. A BIOS file whose + bytes a tree holds is read from the tree's member.""" + members: dict[str, tuple[str, int]] = {} + for entry in data_dirs: + lead = f"{str(entry.get('dest') or '').rstrip('/')}/" if entry.get("dest") else "" + for rel, meta in sorted((entry.get("files") or {}).items()): + members.setdefault(f"{lead}{rel}", (str(meta["sha1"]), int(meta["size"]))) + by_sha1: dict[str, str] = {} + for name, (sha1, _size) in sorted(members.items()): + by_sha1.setdefault(sha1, name) + systems: dict[str, set[str]] = {} + listed: set[str] = set() + sources: dict[str, dict] = {} + for entry in sorted(files, key=lambda f: (str(f.get("root") or ""), str(f["dest"]))): + sha1 = str(entry["sha1"]).lower() + systems.setdefault(sha1, set()).update(entry.get("systems") or []) + if sha1 not in by_sha1: + root = str(entry.get("root") or "") + name = f"{root}/{entry['dest']}" if root else str(entry["dest"]) + if name in members: + name = f"by-sha1/{sha1}/{PurePosixPath(str(entry['dest'])).name}" + members[name] = (sha1, int(entry["size"])) + by_sha1[sha1] = name + sources[name] = entry + listed.add(by_sha1[sha1]) + rows = [] + for name in sorted(listed): + sha1, size = members[name] + row: dict = {"path": name, "sha1": sha1, "size": size} + if systems.get(sha1): + row["systems"] = sorted(systems[sha1]) + rows.append(row) + return members, rows, sources + + +def pack_install_list(manifest: dict, files: list[dict], omitted: list[dict], + data_dirs: list[dict]) -> dict: + """The platform's list narrowed to the choice, which the pack carries: + --from-pack with no option installs what the choice kept, the same + files at the same places.""" + narrowed = {key: value for key, value in manifest.items() + if key not in ("files", "case_variants", "omitted_files", + "data_directories")} + narrowed["files"] = [entry for entry in files if not entry.get("case_variant")] + variants = [{key: value for key, value in entry.items() if key != "case_variant"} + for entry in files if entry.get("case_variant")] + if variants or "case_variants" in manifest: + narrowed["case_variants"] = variants + narrowed["omitted_files"] = list(omitted) + if data_dirs or "data_directories" in manifest: + narrowed["data_directories"] = list(data_dirs) + return narrowed + + +def pack_manifest(plat: str, install_list: dict, rows: list[dict], + targets: dict | None) -> bytes: + """manifest.json of a pack made here, as --from-pack reads it.""" + entries = [*install_list.get("files", []), *install_list.get("omitted_files", [])] + records = {"systems"} if any("systems" in entry for entry in entries) else set() + if any(copy.get("cores") for entry in install_list.get("files", []) + for copy in [entry, *entry.get("alternatives", []), + *entry.get("slot_choices", [])]): + records.add("cores") + if records or any("regions" in entry for entry in entries): + records.add("regions") + data: dict = {"platform": plat, "files": rows} + for key in ("system_titles", "system_names"): + if install_list.get(key): + data[key] = install_list[key] + data["list_records"] = sorted(records) + if install_list.get("version"): + data["list_version"] = install_list["version"] + data["install_list"] = install_list + if targets is not None: + data["targets"] = targets + return json.dumps(data, ensure_ascii=False, separators=(",", ":")).encode("utf-8") + + +def _member_bound(name: str, size: int) -> int: + """The most bytes a member can take in a part: both headers and its + data deflated at worst.""" + encoded = len(name.encode("utf-8")) + return _ZIP_LOCAL_BYTES + _ZIP_CENTRAL_BYTES + 2 * encoded + size + size // 1000 + 64 + + +def pack_bound(manifest_size: int, members: list[PackMember]) -> int: + """The most bytes the pack can take as one ZIP.""" + return (_ZIP_END_BYTES + _member_bound("manifest.json", manifest_size) + + sum(_member_bound(member.name, member.size) for member in members)) + + +def part_file_name(name: str, index: int, count: int) -> str: + return f"{name[: -len('.zip')]}.part{index}of{count}.zip" + + +def part_marker_name(name: str, index: int, count: int) -> str: + return f"{name[: -len('.zip')]}.part{index}of{count}.txt" + + +def part_marker_text(name: str, index: int, sizes: list[int]) -> bytes: + """The marker of part index, in the words scripts/split_pack.py writes + and read_part_marker reads back.""" + count = len(sizes) + lines = [ + "RetroBIOS split pack", + f"This folder holds part {index} of {count} of {name}.", + "Every part is needed: extract them all into this same folder.", + "The installer's --check names a part missing from the folder.", + "", + f"pack: {name}", + f"part: {index} of {count}", + ] + lines += [f"file: {size:>{PART_SIZE_WIDTH}} {part_file_name(name, number, count)}" + for number, size in enumerate(sizes, 1)] + return ("\n".join(lines) + "\n").encode("utf-8") + + +def _marker_bound(name: str, count: int) -> int: + marker = len(part_marker_name(name, count, count).encode("utf-8")) + return 30 + 46 + 2 * marker + len(part_marker_text(name, count, [0] * count)) + + +def plan_pack_parts(name: str, manifest_size: int, members: list[PackMember], + limit: int | None) -> list[list[PackMember]]: + """The members of each part, in pack order, manifest.json in the first. + One part without a limit, or when the whole pack stays under it. Each + part's bound stays under the limit, room kept for its marker, the plan + made again until the count it assumed is the count it gives.""" + if limit is None or pack_bound(manifest_size, members) < limit: + return [list(members)] + count = 2 + while True: + floor = _ZIP_END_BYTES + _marker_bound(name, count) + parts: list[list[PackMember]] = [[]] + size = floor + _member_bound("manifest.json", manifest_size) + if size >= limit: + raise PackError(f"the list alone needs {format_size(size)}, more than a part " + f"of {format_size(limit)} holds") + for member in members: + weight = _member_bound(member.name, member.size) + if floor + weight >= limit: + raise PackError(f"{member.name} ({format_size(member.size)}) does not fit " + f"in a part of {format_size(limit)}") + if size + weight >= limit or len(parts[-1]) >= 0xFFFE: + parts.append([]) + size = floor + parts[-1].append(member) + size += weight + if len(parts) > MAX_PARTS: + raise PackError(f"the pack would take {len(parts)} parts, more than " + f"{MAX_PARTS}: give a larger size") + if len(parts) <= count: + return parts + count = len(parts) + + +def _pack_info(name: str, compress: int = zipfile.ZIP_DEFLATED) -> zipfile.ZipInfo: + """A member header that depends on its name alone.""" + info = zipfile.ZipInfo(name, date_time=PACK_MEMBER_DATE) + info.compress_type = compress + info.create_system = 3 + info.external_attr = 0o100644 << 16 + return info + + +def _write_member(archive: zipfile.ZipFile, member: PackMember) -> None: + """Copy one member into the archive, its SHA-1 and size checked on the + bytes written, before the archive is closed.""" + info = _pack_info(member.name) + info.file_size = member.size + digest = hashlib.sha1() + size = 0 + with open(member.source, "rb") as src, archive.open(info, "w") as out: + while True: + chunk = src.read(1024 * 1024) + if not chunk: + break + digest.update(chunk) + size += len(chunk) + out.write(chunk) + if size != member.size or digest.hexdigest() != member.sha1: + raise PackError(f"{member.name} does not match the list: {size} bytes of SHA-1 " + f"{digest.hexdigest()}, the list says {member.size} of " + f"{member.sha1}") + + +def _patch_marker(path: Path, marker: str, body: bytes) -> None: + """Write the real marker over its placeholder of the same length: the + data, and the CRC-32 of the local and the central header.""" + with zipfile.ZipFile(path) as archive: + first = archive.infolist()[0] + central = int(archive.start_dir) # type: ignore[attr-defined] + if first.filename != marker or first.file_size != len(body) or first.header_offset: + raise PackError(f"{path.name} does not start with its marker") + crc = zlib.crc32(body).to_bytes(4, "little") + with open(path, "r+b") as handle: + local = handle.read(30) + if local[:4] != b"PK\x03\x04": + raise PackError(f"{path.name} has no local header at its start") + data = (30 + int.from_bytes(local[26:28], "little") + + int.from_bytes(local[28:30], "little")) + handle.seek(14) + handle.write(crc) + handle.seek(data) + handle.write(body) + handle.seek(central) + if handle.read(4) != b"PK\x01\x02": + raise PackError(f"{path.name} has no central directory where it says") + handle.seek(central + 16) + handle.write(crc) + + +def _part_contents(name: str, index: int, count: int, manifest: bytes, + chosen: list[PackMember]) -> list[tuple[str, int]]: + """(name, size) of each member of a part, in the order written.""" + held = ([(part_marker_name(name, index, count), + len(part_marker_text(name, index, [0] * count)))] if count > 1 else []) + held += [("manifest.json", len(manifest))] if index == 1 else [] + return held + [(member.name, member.size) for member in chosen] + + +def write_pack(path: Path, manifest: bytes, members: list[PackMember], + limit: int | None) -> list[Path]: + """Write the pack at path, or in parts beside it when a limit is given + and the pack would pass it. Returns the files written. + + Each file is written beside its final name and renamed only once every + member was checked against its SHA-1 and the archives read back: a + failure leaves no file behind, and a pack of that name written before + stays as it was. An earlier pack of that name in another layout (whole, + or in another count of parts) goes once the new one is in place: + --from-pack would otherwise find both.""" + name = path.name + plan = plan_pack_parts(name, len(manifest), members, limit) + count = len(plan) + finals = ([path] if count == 1 else + [path.with_name(part_file_name(name, index, count)) + for index in range(1, count + 1)]) + scratches: list[Path] = [] + try: + for index, (final, chosen) in enumerate(zip(finals, plan), 1): + handle, scratch = tempfile.mkstemp(prefix=f".{final.name}.", suffix=".partial", + dir=str(path.parent)) + os.close(handle) + scratches.append(Path(scratch)) + with zipfile.ZipFile(scratch, "w", zipfile.ZIP_DEFLATED, + compresslevel=PACK_COMPRESSLEVEL) as archive: + if count > 1: + archive.writestr( + _pack_info(part_marker_name(name, index, count), zipfile.ZIP_STORED), + part_marker_text(name, index, [0] * count)) + if index == 1: + archive.writestr(_pack_info("manifest.json"), manifest) + for member in chosen: + if _stop.is_set(): + raise KeyboardInterrupt + _write_member(archive, member) + sizes = [scratch.stat().st_size for scratch in scratches] + if count > 1: + for index, scratch in enumerate(scratches, 1): + _patch_marker(scratch, part_marker_name(name, index, count), + part_marker_text(name, index, sizes)) + for index, (scratch, chosen) in enumerate(zip(scratches, plan), 1): + shown = finals[index - 1].name + with zipfile.ZipFile(scratch) as archive: + held = [(info.filename, info.file_size) for info in archive.infolist()] + if count > 1 and archive.read(part_marker_name(name, index, count)) != \ + part_marker_text(name, index, sizes): + raise PackError(f"{shown}: its marker does not read back") + if held != _part_contents(name, index, count, manifest, chosen): + raise PackError(f"{shown} does not read back as written") + if limit is not None and count > 1 and sizes[index - 1] >= limit: + raise PackError(f"{shown} reached the limit of {format_size(limit)}") + except BaseException: + for scratch in scratches: + scratch.unlink(missing_ok=True) + raise + stem = name[: -len(".zip")] + stale = [old for old in _listed_paths(path.parent) + if old not in finals and (old == path or ( + _PART_FILE.match(old.name) is not None + and _PART_FILE.match(old.name)["stem"] == stem))] # type: ignore[index] + for scratch, final in zip(scratches, finals): + os.replace(scratch, final) + for old in stale: + old.unlink(missing_ok=True) + return finals + + +def _listed_paths(folder: Path) -> list[Path]: + """The files of a folder, [] when it cannot be listed.""" + return [folder / name for name in sorted(_listed(folder))] + + +def _pack_targets(plat: str) -> dict | None: + """The cores per board the pack carries, as a pack built by the + repository does: the list at hand offline, else the one fetched. None + for a platform that publishes none, or a list that cannot be read.""" + if plat not in TARGET_PLATFORMS: + return None + if LOCAL.offline: + return local_targets(plat) + with contextlib.redirect_stderr(io.StringIO()): + return fetch_targets(plat) + + +def _pack_event(plat: str, path: Path, members: dict[str, tuple[str, int]], + parts: list[Path], status: str, message: str, size: int = 0) -> None: + EVENTS.emit("pack", platform=plat, path=str(path), files=len(members), + bytes=sum(length for _sha1, length in members.values()), size=size, + parts=[str(part) for part in parts], status=status, message=message) + + +def _pack_refused(plat: str, path: Path, words: str, code: int, + members: dict[str, tuple[str, int]] | None = None) -> int: + """Say why no pack is made, the event saying it too: code.""" + print(f"Error: {screen_text(words)}. No pack was written.", file=sys.stderr) + _pack_event(plat, path, members or {}, [], "failed", f"{words}.") + return code + + +def pack_parts_words(count: int, limit: int | None, fat: bool) -> str: + """How the pack is written, in one line: whole, or in parts and why.""" + if count == 1: + return "One ZIP." + each = f"In {count} parts of at most {format_size(limit or 0)}" + return f"{each}, as FAT32 holds no file of 4 GB." if fat else f"{each}." + + +def run_pack(args: argparse.Namespace, plat: str, manifest: dict, files: list[dict], + omitted: list[dict], data_dirs: list[dict], narrowed: bool, + term: Terminal) -> int: + """--pack: the choice downloaded into a pack instead of a folder, every + member checked against its SHA-1 before the ZIP is closed. Returns the + exit code: 0 once written (or listed with --dry-run), 1 when a file + could not be had or the pack written, 2 when nothing was tried.""" + path = pack_path(args.pack, plat, narrowed) + display = display_name(plat, manifest) + if not path.name.endswith(PACK_NAME_END): + return _pack_refused(plat, path, f"{path.name} does not end with {PACK_NAME_END}, " + "which --from-pack and the parts of a pack read", 2) + if not _is_dir(path.parent): + return _pack_refused(plat, path, f"the folder {shown_path(path.parent)} does not " + "exist", 2) + members, rows, sources = pack_layout(files, data_dirs) + if not members: + return _pack_refused(plat, path, "the choice keeps no file to put in a pack", 2) + body = pack_manifest(plat, pack_install_list(manifest, files, omitted, data_dirs), rows, + _pack_targets(plat)) + planned = [PackMember(name, sha1, size, Path()) + for name, (sha1, size) in sorted(members.items())] + fat = fat32_drive(path.parent) + limit = args.split + if fat and (limit is None and pack_bound(len(body), planned) > FAT_FILE_LIMIT + or limit is not None and limit > FAT_PART_BYTES): + limit = FAT_PART_BYTES + try: + plan = plan_pack_parts(path.name, len(body), planned, limit) + except PackError as exc: + return _pack_refused(plat, path, str(exc), 2, members) + count = len(plan) + finals = ([path] if count == 1 else + [path.with_name(part_file_name(path.name, index, count)) + for index in range(1, count + 1)]) + total = sum(size for _sha1, size in members.values()) + print(f"\nPack for {display}: {_plural(len(members), 'file')} ({format_size(total)}).") + print(f"Pack: {shown_path(path)}") + how = pack_parts_words(count, limit, fat and limit == FAT_PART_BYTES) + if count > 1: + print(f" {how}") + if args.dry_run: + for name in sorted(members): + detail(f" {screen_text(name)} ({format_size(members[name][1])})") + if not OUTPUT.verbose: + print(" --verbose lists the files.") + _pack_event(plat, path, members, finals, "planned", how) + return 0 + needed = total + pack_bound(len(body), planned) + try: + free = shutil.disk_usage(path.parent).free + except OSError: + free = needed + if free < needed: + return _pack_refused(plat, path, f"the drive holding {shown_path(path.parent)} has " + f"{format_size(free)} free, and making the pack needs " + f"{format_size(needed)}", 2, members) + staging = Path(tempfile.mkdtemp(prefix=f".{path.name}.", suffix=".staging", + dir=str(path.parent))) + try: + return _fill_pack(args, plat, path, body, members, sources, data_dirs, limit, + staging, term) + except KeyboardInterrupt: + _stop.set() + print("\n Stopped. No pack was written.", file=sys.stderr) + _pack_event(plat, path, members, [], "failed", "Stopped before the pack was written.") + return 130 + finally: + shutil.rmtree(staging, ignore_errors=True) + + +def _fill_pack(args: argparse.Namespace, plat: str, path: Path, body: bytes, + members: dict[str, tuple[str, int]], sources: dict[str, dict], + data_dirs: list[dict], limit: int | None, staging: Path, + term: Terminal) -> int: + """Fetch every member into staging, then write the pack from it.""" + staged = [{**{key: value for key, value in entry.items() + if key not in ("root", "core_folder", "case_variant")}, "dest": name} + for name, entry in sorted(sources.items())] + copies = plan_local_copies(staged, staging, None, LOCAL.folders) + fetched = sum(int(entry.get("size") or 0) for entry in staged) + EVENTS.emit("download", platform=plat, files=len(staged), bytes=fetched) + detail(f"\nDownloading {_plural(len(staged), 'file')} ({format_size(fetched)})...") + failed, interrupted = download_files(staged, staging, jobs=args.jobs, + verbose=args.verbose, term=term, copies=copies) + if interrupted: + raise KeyboardInterrupt + owners: dict[str, Path] = {} + trees_failed: list[tuple[str, str]] = [] + for index, entry in enumerate(data_dirs): + lead = f"{str(entry.get('dest') or '').rstrip('/')}/" if entry.get("dest") else "" + root = staging / ".trees" / str(index) + names = [f"{lead}{rel}" for rel in sorted(entry.get("files") or {})] + owned = [name for name in names if name in members and name not in sources + and name not in owners] + if not owned: + continue + detail(f" {entry.get('ref', 'data')}: {_plural(len(names), 'data file')}...") + counts = install_data_directory(entry, root) + problem = (str(counts["error"]) if counts["error"] + else f"{counts['changed']} changed in its source" if counts["changed"] + else f"{counts['absent']} not in its source" if counts["absent"] + else "") + if problem: + trees_failed.append((str(entry.get("ref", "data")), problem)) + continue + for name in owned: + owners[name] = root.joinpath(*PurePosixPath(name).parts) + if failed or trees_failed: + lines = [*failed, *trees_failed] + print(f"\n {_plural(len(lines), 'file')} could not be had: no pack was written.", + file=sys.stderr) + for dest, reason in lines[: None if args.verbose else 5]: + print(f" {screen_text(dest)}: {screen_text(str(reason))}", file=sys.stderr) + if len(lines) > 5 and not args.verbose: + print(f" ... and {len(lines) - 5} more (--verbose lists them)", file=sys.stderr) + _pack_event(plat, path, members, [], "failed", + f"{_plural(len(lines), 'file')} could not be had: no pack was written.") + return 1 + ordered = [PackMember(name, sha1, size, + owners[name] if name in owners + else staging.joinpath(*PurePosixPath(name).parts)) + for name, (sha1, size) in sorted(members.items())] + detail(f"\nWriting {path.name}...") + try: + written = write_pack(path, body, ordered, limit) + except (OSError, PackError) as exc: + words = (DRIVE_FULL if isinstance(exc, OSError) and _drive_full(exc) + else exc.strerror if isinstance(exc, OSError) and exc.strerror else str(exc)) + print(f"\n {path.name} could not be written: {screen_text(str(words))}. No pack " + "was left behind.", file=sys.stderr) + _pack_event(plat, path, members, [], "failed", + f"{path.name} could not be written: {words}.") + return 1 + size = sum(part.stat().st_size for part in written) + print(f"\nPack made: {_plural(len(members), 'file')}, {format_size(size)}" + + (f", in {len(written)} parts" if len(written) > 1 else "") + ".") + for part in written if len(written) > 1 else []: + print(f" {shown_path(part)}") + print("Install from it on the other device with --from-pack.") + _pack_event(plat, path, members, written, "written", + f"{path.name}: {_plural(len(members), 'file')}, every one checked.", size) + return 0 + + class _Offline(OSError): """A network request in a run told to make none.""" @@ -15652,6 +16291,22 @@ def build_parser() -> argparse.ArgumentParser: help=f"delete one backup (a dated folder inside {BACKUP_DIR}) after one " "question, to free its space", ) + parser.add_argument( + "--pack", + type=Path, + metavar="PATH", + help=f"download the choice into a pack ZIP at PATH instead of a BIOS folder, for " + f"another device or an install without the internet (--from-pack reads it). " + f"A folder takes {PACK_NAME_END}. The narrowing options apply, and " + "--dry-run lists what would go in", + ) + parser.add_argument( + "--split", + type=parse_part_size, + metavar="SIZE", + help="with --pack, write parts of at most SIZE (1900M, 4G), each a whole ZIP. " + "A pack that would pass 4 GiB on a FAT32 drive is split by itself", + ) parser.add_argument( "--tui", action="store_true", @@ -15814,6 +16469,7 @@ def main() -> None: f"here: {reason}", file=sys.stderr) sys.exit(2) _check_actions(parser, args) + _check_pack(parser, args) if args.restore is not None: _run_action(args, lambda given: restore_kept(given.restore, given.dry_run)) if args.delete_backup is not None: @@ -15945,6 +16601,36 @@ def _check_actions(parser: argparse.ArgumentParser, args: argparse.Namespace) -> f"not {narrowed[0]} and {narrowed[1]}") +def _check_pack(parser: argparse.ArgumentParser, args: argparse.Namespace) -> None: + """Refuse --split without --pack, and --pack with an option that reads + or writes a BIOS folder: applied or refused, never ignored.""" + pack = getattr(args, "pack", None) + if getattr(args, "split", None) is not None and pack is None: + parser.error("--split applies to --pack") + if pack is None: + return + for flag, given in ( + ("--check", args.check), ("--dest", args.dest), + ("--installed-cores", args.installed_cores), ("--cores-dir", args.cores_dir), + ("--save-dir", args.save_dir), ("--standalone-copies", args.standalone_copies), + ("--add-app", args.add_app), ("--romm-firmware", args.romm_firmware is not None), + ("--tui", args.tui), ("--list-platforms", args.list_platforms), + ("--list-targets", args.list_targets), ("--list-systems", args.list_systems), + ("--list-cores", args.list_cores), ("--list-emulators", args.list_emulators), + ): + if given: + parser.error(f"--pack writes a pack ZIP, and {flag} reads or writes the " + "BIOS folder of this machine") + if args.for_games is True: + parser.error("--for-games with --pack needs its FOLDER: no card is read for a pack") + name = Path(os.path.expanduser(str(pack))).name + if not (_is_dir(Path(os.path.expanduser(str(pack)))) + or str(pack).endswith(("/", os.sep)) or name.endswith(PACK_NAME_END)): + parser.error(f"--pack names a folder, or a file whose name ends with " + f"{PACK_NAME_END} (--from-pack and the parts of a pack read that " + f"name): {name}") + + def _run_action(args: argparse.Namespace, action: Callable[[argparse.Namespace], int]) -> NoReturn: """Run an action and exit with its code, its events framed by start and @@ -17341,6 +18027,18 @@ def _install(args: argparse.Namespace, real_stdout: TextIO) -> None: _enter_wsl() _wsl_dest(args) _open_local_sources(args) + # --pack: the files go into a ZIP for another device, no folder of this + # machine is read or written, and nothing is asked. + packing = getattr(args, "pack", None) is not None + if packing: + interactive = False + if args.platform is None: + spelled = pack_name_platforms(Path(os.path.expanduser(str(args.pack))).name) + if len(spelled) != 1: + print("Error: name the platform the pack is for with --platform.", + file=sys.stderr) + sys.exit(2) + args.platform = spelled[0] # Early exit for listing if args.list_platforms: @@ -17379,7 +18077,10 @@ def _install(args: argparse.Namespace, real_stdout: TextIO) -> None: if args.dest: plat, args.dest = card_dest(named, args.platform or "", args.dest) args.platform = plat or args.platform - if args.platform and args.dest: + if packing: + # Where the pack goes stands for the folder: nothing is read there. + platforms = [(args.platform, pack_path(args.pack, args.platform, False).parent)] + elif args.platform and args.dest: platforms = [(args.platform, args.dest)] elif args.platform: detail("Looking for setups here...") @@ -17560,7 +18261,7 @@ def _install(args: argparse.Namespace, real_stdout: TextIO) -> None: # would have chosen: --yes beside two setups filled both, 14 GB in # two folders, where its help says it stops on what to name. _several_found(platforms, setups) - if platforms: + if platforms and not packing: EVENTS.emit("detect", os=os_type, os_name=_os_name(), platforms=[ {"platform": name, "name": display_name(name), "bios_dir": str(path)} for name, path in platforms @@ -17579,7 +18280,7 @@ def _install(args: argparse.Namespace, real_stdout: TextIO) -> None: if args.dest is not None and not listing: _missing_dest(args.dest, interactive and not (args.check or args.dry_run or args.yes)) - elif not listing: + elif not listing and not packing: # A system_directory under /root read from retroarch.cfg, run without # sudo: the case probe raised PermissionError before any line. for name, path in platforms: @@ -17658,7 +18359,7 @@ def _install(args: argparse.Namespace, real_stdout: TextIO) -> None: message=f"{problem}." if problem else f"Recorded {_plural(count, 'file')} and this choice in {path}.") - if len(platforms) == 1 and not listing and not choice_given(args): + if len(platforms) == 1 and not listing and not packing and not choice_given(args): apply_record(args, *platforms[0]) # --target is checked for every platform before anything is written, as @@ -17703,7 +18404,7 @@ def _install(args: argparse.Namespace, real_stdout: TextIO) -> None: # refusal for the second platform must not follow an install of the first. cores_found: dict[tuple[str, Path], list[str]] = {} cores_searched: dict[tuple[str, Path], list[Path]] = {} - for plat_name, bios_path in platforms: + for plat_name, bios_path in [] if packing else platforms: if plat_name in CORE_PLATFORMS: if args.cores_dir: _check_cores_dir(args.cores_dir) @@ -17740,7 +18441,8 @@ def _install(args: argparse.Namespace, real_stdout: TextIO) -> None: files = manifest.get("files", []) omitted_files = manifest.get("omitted_files", []) variants = manifest.get("case_variants", []) - case_kept = keeps_case(bios_path) + # A ZIP keeps both spellings: the device installing it folds them. + case_kept = packing or keeps_case(bios_path) if variants and case_kept: # The list is folded for Windows and macOS, but here bios.col and # BIOS.col are two files that two cores open. @@ -17756,7 +18458,8 @@ def _install(args: argparse.Namespace, real_stdout: TextIO) -> None: f" {_plural(len(folded), 'file')} left out: {bios_path} does not keep " f"case and holds another file under the same name ({shown})" ) - if any(FAT_REFUSED.search(str(entry.get("dest", ""))) for entry in files) \ + if not packing and any(FAT_REFUSED.search(str(entry.get("dest", ""))) + for entry in files) \ and not holds_fat_refused_names(bios_path): files, refused = split_fat_refused(files) shown = ", ".join(refused[:3]) + (" ..." if len(refused) > 3 else "") @@ -17802,7 +18505,7 @@ def _install(args: argparse.Namespace, real_stdout: TextIO) -> None: # a card prepared on a computer took every board's files, and the # full-screen interface, which always gives --dest, never applied one. target = args.target - if (not target and not args.every_board + if (not target and not args.every_board and not packing and (not LOCAL.offline or local_targets(plat_name) is not None)): board = detect_board(plat_name) where = "detected" @@ -17888,7 +18591,7 @@ def _install(args: argparse.Namespace, real_stdout: TextIO) -> None: ) # Said before the install and again with the result. - note = None if listing else version_note(plat_name, bios_path, manifest) + note = None if listing or packing else version_note(plat_name, bios_path, manifest) if note is not None: print(f" {note[2]}") version_notes.append(note[2]) @@ -17899,14 +18602,18 @@ def _install(args: argparse.Namespace, real_stdout: TextIO) -> None: # one read from an unknown save directory left out. Said once the # choice is made, over the files it keeps (say_saves). display = display_name(plat_name, manifest) - files, unplaced = place_save_entries( - files, bios_path, manifest, args.save_dir, display, say=False) - files, beyond = place_relative_entries( - files, bios_path, manifest, display, say=not listing) - files, elsewhere = place_emulator_entries( - files, bios_path, manifest, display, say=not listing) - unplaced = [*unplaced, *beyond, *elsewhere] - if not manifest.get("save_directory"): + unplaced = [] + if not packing: + # A pack keeps every root's files: the device installing it + # places them. + files, unplaced = place_save_entries( + files, bios_path, manifest, args.save_dir, display, say=False) + files, beyond = place_relative_entries( + files, bios_path, manifest, display, say=not listing) + files, elsewhere = place_emulator_entries( + files, bios_path, manifest, display, say=not listing) + unplaced = [*unplaced, *beyond, *elsewhere] + if not manifest.get("save_directory") and not packing: # Its own list leaves these files out: naming the folder with # --save-dir installs none of them, and was advised in a loop. _SAVE_WHY[bios_path] = unlisted_saves_words(display) @@ -17919,7 +18626,7 @@ def _install(args: argparse.Namespace, real_stdout: TextIO) -> None: # two games, while the screen offers what they need first. Not for a # run given its list (the screen's own runs, the choice already # made), nor one narrowed by name. - unasked = (not interactive and not args.check and not listing + unasked = (not interactive and not args.check and not listing and not packing and not getattr(args, "all_files", False) and LOCAL.manifest is None and LOCAL.pack is None and not (args.installed_cores or args.no_game_data or args.system @@ -18076,7 +18783,8 @@ def _install(args: argparse.Namespace, real_stdout: TextIO) -> None: if unplaced: total_omitted += len(unplaced) omitted_seen.extend(unplaced) - say_saves(plat_name, files, omitted_files + unplaced, bios_path, display, menu) + if not packing: + say_saves(plat_name, files, omitted_files + unplaced, bios_path, display, menu) if args.list_systems or args.list_cores: _print_choices(plat_name, files, omitted_files, args.list_systems, manifest) @@ -18128,6 +18836,9 @@ def _install(args: argparse.Namespace, real_stdout: TextIO) -> None: (selection[0] if selection else [])], bool(game_data_cut))) if empty_choice: print(f" {empty_choice}") + if packing: + sys.exit(_pack_refused(plat_name, pack_path(args.pack, plat_name, narrowed), + "the choice keeps no file to put in a pack", 2)) if not EVENTS.on: continue if omitted_files: @@ -18148,6 +18859,10 @@ def _install(args: argparse.Namespace, real_stdout: TextIO) -> None: and not entry.get("frontend") else entry for entry in omitted_files) + if packing: + sys.exit(run_pack(args, plat_name, manifest, files, omitted_files, data_dirs, + narrowed, term)) + if plat_name == "romm": try: layout = romm_firmware_layout(bios_path, args.romm_firmware) @@ -19681,6 +20396,14 @@ class TuiState: self.action_code: int | None = None # Whether the folder checked has a backup, read once each check. self.has_backups: bool = False + # Make a pack: the folder it goes in (Downloads by default), what + # its dry run said (the pack event), what the run made, its count + # of files fetched so far and its code. + self.pack_dir: Path | None = None + self.pack_plan: dict | None = None + self.pack_done: dict | None = None + self.pack_fetched: tuple[int, int] | None = None + self.pack_code: int | None = None @property def screen(self) -> str: @@ -19999,6 +20722,7 @@ def tui_blocker( ("--list-emulators", args.list_emulators), ("--events", args.events), ("--quiet", args.quiet), ("--yes", args.yes), ("--no-input", args.no_input), ("--restore", args.restore is not None), + ("--pack", getattr(args, "pack", None) is not None), ): if given: return f"{flag} runs without questions" @@ -20727,10 +21451,9 @@ TUI_MORE_ROW = TuiRow("more", "More") def _more_row(state: TuiState) -> list[TuiRow]: - """More, where it has something to act on: an install record of this - setup in the folder, or a backup of it. A first install's plan keeps - its rows.""" - return [TUI_MORE_ROW] if state.record is not None or state.has_backups else [] + """More, on every plan: a pack can always be made, and the folder's + record or backups add removing and putting back.""" + return [TUI_MORE_ROW] # The plan's row for the record's choice, and the one back to the setups. @@ -21231,6 +21954,10 @@ def _replace(state: TuiState, screen: str) -> None: def _back(state: TuiState) -> list[tuple]: + if state.screen == "packdone" and not state.running and "more" in state.stack: + # Made or not, its plan is spent: back to More. + del state.stack[state.stack.index("more") + 1:] + return [] if state.screen == "actdone" and not state.running: # Done: what was planned is gone, and the plan is counted again. return _activate_action(state, TuiRow("recheck", "")) @@ -21828,7 +22555,7 @@ def _browse_to(state: TuiState, folder: Path | None, came_from: Path | None = No # A pack is a ZIP, never a folder. state.browse_rows = [row for row in state.browse_rows if row.action != "use"] focus = 0 - if (folder is not None and state.browse_for not in ("from", "pack") + if (folder is not None and state.browse_for not in ("from", "pack", "packto") and folder in (state.home, Path(folder.anchor))): # No frontend reads its BIOS files from HOME or a drive's root: A # pressed through the screens installed into ~. A goes into a @@ -22046,6 +22773,12 @@ def _activate(state: TuiState, row: TuiRow) -> list[tuple]: if action == "zip" and state.browse_for == "pack": # Opened in this process (perform), which answers pack_opened. return [("pack", row.value)] + if action == "use" and state.browse_for == "packto": + state.pack_dir = state.browse_dir + state.browse_for = "dest" + state.stack.pop() + state.pack_plan = None + return _start_run(state, "pack_plan") if action == "use" and state.browse_for == "save": state.passthrough = [flag for flag in state.passthrough if flag[0] != "--save-dir"] @@ -23824,6 +24557,7 @@ _ROW_VERBS = { "backups": "Open", "putback": "Open", "dropbackup": "Open", "rmall": "Choose", "rmsystem": "Choose", "rmgo": "Remove", "rmbackup": "Change", "backup": "Choose", "bkrestore": "Put back", "bkdelete": "Delete", "actgo": "Confirm", + "packmake": "Open", "packgo": "Make", "packwhere": "Change", } @@ -24608,11 +25342,14 @@ def _view_browse(state: TuiState, width: int, height: int) -> tuple: "cores read files there."] elif state.browse_for == "pack": hint = ["Choose the pack ZIP downloaded before: nothing is downloaded then."] + elif state.browse_for == "packto": + hint = ["Choose the folder the pack goes in."] # The hint is kept whole under the list, which scrolls: three folders at # 40x12 cut it to "Choose the old card, a backup folder". return ("Copy from" if state.browse_for == "from" else "Save folder" if state.browse_for == "save" - else "From a pack" if state.browse_for == "pack" else "Browse for a folder", + else "From a pack" if state.browse_for == "pack" + else "Pack folder" if state.browse_for == "packto" else "Browse for a folder", _compose(state, width, height, [where], tui_rows(state), _status_after(state), hint), ("A/Enter Open", "B/Esc Back", "? Help")) @@ -24932,6 +25669,9 @@ def _plan_body(state: TuiState, width: int, height: int, lines: list, # plan offered Choose another folder and Install anyway and no word of # why. kept += [line for line in lines if str(line).startswith(CANNOT_WRITE)] + # A file in place that the install replaces, said whatever the rows: the + # More row every plan holds pushed it out of a 40x12 plan. + kept += [line for line in lines if "backed up, replaced" in str(line)] top = _text_lines(kept, width) drawn = [str(line).strip() for line in body] # Three lines at least for the rows: two of them and where the list is, @@ -25836,16 +26576,52 @@ def _open_details(state: TuiState) -> list[tuple]: # The screens below More, each listing its rows in _action_rows. -_ACTION_SCREENS = ("more", "remove", "removal", "backups", "backup", "actconfirm", "actdone") +_ACTION_SCREENS = ("more", "remove", "removal", "backups", "backup", "actconfirm", "actdone", + "packplan", "packdone") # The runs More starts, each a child as an install is: what --remove would # take (removal_plan), the removal, the backups listed, one put back and # one deleted. -TUI_ACTION_RUNS = ("removal_plan", "remove", "backups", "restore", "delete_backup") +TUI_ACTION_RUNS = ("removal_plan", "remove", "backups", "restore", "delete_backup", + "pack_plan", "pack") +# The plan's options a pack's run leaves out: each reads or writes the BIOS +# folder of this machine, which --pack refuses. +TUI_PACK_DROPPED = ("--dest", "--installed-cores", "--cores-dir", "--save-dir", + "--standalone-copies", "--add-app", "--romm-firmware", "--for-games", + "--required-only") + + +def tui_pack_dir(state: TuiState) -> Path: + """The folder the pack goes in: the one chosen, else Downloads where + there is one, else the home folder.""" + if state.pack_dir is not None: + return state.pack_dir + downloads = state.home / "Downloads" + return downloads if _is_dir(downloads) else state.home + + +def tui_pack_argv(state: TuiState, run: str, python: str, script: str) -> list[str]: + """The child that makes the pack, or lists it (pack_plan): the plan's + choice, none of the options of this machine's folder. The games of a + folder named stay a choice, the card's own are not read for a pack.""" + argv = [python, script, f"--platform={state.platform}"] + if state.manifest_path is not None: + argv.append(f"--manifest={state.manifest_path}") + flags = [flag for flag in tui_flags(state) if flag[0] not in TUI_PACK_DROPPED] + if state.for_games and state.games_folder: + flags.append(("--for-games", str(state.games_folder))) + if state.required_only: + flags.append(("--required-only", None)) + argv += [flag if value is None else f"{flag}={value}" for flag, value in flags] + argv.append(f"--pack={tui_pack_dir(state)}{os.sep}") + return argv + (["--dry-run", "--events"] if run == "pack_plan" else ["--events", "--yes"]) def tui_action_argv(state: TuiState, run: str, python: str, script: str) -> list[str]: """The child of a More action: its own options and none of the plan's, - whose --system is an install's choice, not what to remove.""" + whose --system is an install's choice, not what to remove. A pack + takes the plan's choice.""" + if run in ("pack_plan", "pack"): + return tui_pack_argv(state, run, python, script) if run in ("restore", "delete_backup"): folder = str((state.backup_chosen or {}).get("folder", "")) flag = "--restore" if run == "restore" else "--delete-backup" @@ -25882,8 +26658,21 @@ def tui_removal_systems(state: TuiState) -> list[tuple[str, int, int]]: def _more_rows(state: TuiState) -> list[TuiRow]: - return [TuiRow("remove", "Remove files"), TuiRow("backups", "Backups"), - TuiRow("putback", "Put back a backup"), TuiRow("dropbackup", "Delete a backup")] + """Removing and the backups where the folder has a record or a backup, + then Make a pack.""" + rows = ([TuiRow("remove", "Remove files"), TuiRow("backups", "Backups"), + TuiRow("putback", "Put back a backup"), TuiRow("dropbackup", "Delete a backup")] + if state.record is not None or state.has_backups else []) + return rows + [TuiRow("packmake", "Make a pack")] + + +def _pack_plan_rows(state: TuiState) -> list[TuiRow]: + """Make the pack, once its dry run said what goes in, and Change where.""" + if state.running or state.pack_plan is None: + return [] + rows = ([TuiRow("packgo", "Make the pack")] + if state.pack_plan.get("status") == "planned" else []) + return rows + [TuiRow("packwhere", "Change where")] def _remove_rows(state: TuiState) -> list[TuiRow]: @@ -25946,6 +26735,10 @@ def _action_rows(state: TuiState) -> list[TuiRow]: return [TuiRow("actgo", verb), TuiRow("back", "Back")] if screen == "actdone" and not state.running: return [TuiRow("close", "Close"), TuiRow("recheck", "Check again")] + if screen == "packplan": + return _pack_plan_rows(state) + if screen == "packdone" and not state.running: + return [TuiRow("close", "Close")] return [] @@ -25962,6 +26755,22 @@ def _activate_action(state: TuiState, row: TuiRow) -> list[tuple]: screen, action = state.screen, row.action if action == "back": return _back(state) + if screen == "more" and action == "packmake": + state.pack_plan = None + _push(state, "packplan") + return _start_run(state, "pack_plan") + if screen == "packplan" and action == "packwhere": + state.browse_for = "packto" + _push(state, "browse") + _browse_to(state, _nearest_folder(tui_pack_dir(state))) + return [] + if screen == "packplan" and action == "packgo": + state.pack_done, state.pack_code, state.pack_fetched = None, None, None + _push(state, "packdone") + return _start_run(state, "pack") + if screen == "packdone" and action == "close": + state.exit_code = state.pack_code if state.pack_code is not None else 1 + return [] if screen == "more" and action == "remove": return _push(state, "remove") if screen == "more": @@ -26007,7 +26816,13 @@ def _activate_action(state: TuiState, row: TuiRow) -> list[tuple]: def _take_action_event(state: TuiState, event: dict) -> bool: """An event of a More run, kept for its screen: whether it was one.""" kind = event.get("event") - if kind == "removal_plan" and state.run in ("removal_plan", "remove"): + if kind == "pack" and state.run == "pack_plan": + state.pack_plan = event + elif kind == "pack" and state.run == "pack": + state.pack_done = event + elif kind in ("progress", "downloaded") and state.run == "pack": + state.pack_fetched = (int(event["files_done"]), int(event["files_total"])) + elif kind == "removal_plan" and state.run in ("removal_plan", "remove"): state.removal = event elif kind == "backup" and state.run == "backups": state.backups = [*(state.backups or []), event] @@ -26021,6 +26836,11 @@ def _take_action_event(state: TuiState, event: dict) -> bool: def _action_ended(state: TuiState, code: int, tail: list[str]) -> list[tuple]: """A More run's end: the plan, the list, or what the action did.""" + if state.run == "pack_plan": + return _fail(state, tail, code) if state.pack_plan is None else [] + if state.run == "pack": + state.pack_code = code if code >= 0 else 128 - code + return [] if state.run == "removal_plan": if state.removal is None: return _fail(state, tail, code) @@ -26160,6 +26980,78 @@ def tui_action_outcome(state: TuiState) -> list: return lines +def tui_pack_text(state: TuiState) -> list: + """The pack's plan: what goes in and its size, where, how many parts, + the part files behind Details.""" + plan = state.pack_plan or {} + if plan.get("status") != "planned": + return [str(plan.get("message") or "No pack can be made of this choice.")] + parts = list(plan.get("parts") or []) + lines: list = [f"{_plural(int(plan['files']), 'file')}, " + f"{format_size(int(plan['bytes']))}, for " + f"{display_name(state.platform, state.manifest)}."] + shown = Path(str(parts[0] if parts else plan["path"])) + lines.append(_styled(f"Pack: {_short_path(shown, state.home)}", "path")) + lines.append(str(plan.get("message") or "") + if len(parts) > 1 else "One ZIP, installed with --from-pack.") + if len(parts) > 1: + lines += _details(["", "Parts:"] + [f" {Path(part).name}" for part in parts]) + return lines + + +def tui_pack_outcome(state: TuiState) -> list: + """What making the pack did, in one line, then where.""" + done = state.pack_done or {} + if done.get("status") != "written": + lines: list = [_styled("No pack was made.", "failure")] + if done.get("message"): + lines.append(str(done["message"])) + lines += _details(list(state.tail)) + return lines + parts = list(done.get("parts") or []) + lines = [f"Pack made: {_plural(int(done['files']), 'file')}, " + f"{format_size(int(done['size']))}" + + (f", in {len(parts)} parts." if len(parts) > 1 else ".")] + shown = Path(str(parts[0] if parts else done["path"])) + lines.append(_styled(f"Pack: {_short_path(shown, state.home)}", "path")) + lines.append("On the other device, install from it with --from-pack.") + if len(parts) > 1: + lines += _details(["", "Parts:"] + [f" {Path(part).name}" for part in parts]) + return lines + + +def _wrapped_paths(lines: list, width: int) -> list: + """A path line too wide for the screen, folded over the next lines.""" + return [piece for line in lines for piece in ( + [_styled(part, "folder" if index else "") for index, part in enumerate( + _wrap(str(line), width, " "))] + if getattr(line, "style", "") == "path" and cell_width(str(line)) > width + else [line])] + + +def _view_packplan(state: TuiState, width: int, height: int) -> tuple: + if state.running or state.pack_plan is None: + return ("Make a pack", _compose(state, width, height, + ["Reading what goes into the pack..."], []), + ("B/Esc Back", "? Help")) + lines = _wrapped_paths(_shown(state, tui_pack_text(state)), width) + return ("Make a pack", _compose(state, width, height, lines, tui_rows(state)), + ("A/Enter Choose", "B/Esc Back", "? Help")) + + +def _view_packdone(state: TuiState, width: int, height: int) -> tuple: + if state.running: + fetched = state.pack_fetched + words = (f"Making the pack: {fetched[0]} of {fetched[1]} files." + if fetched else "Making the pack...") + return ("Working", _compose(state, width, height, [words], []), ("B/Esc Stop",)) + lines = _wrapped_paths(_shown(state, tui_pack_outcome(state)), width) + lines[0] = _styled(str(lines[0]), "title") + return ("Done" if state.pack_code == 0 else "Not done", + _compose(state, width, height, lines, tui_rows(state)), + ("A/Enter Close", "B/Esc Back", "? Help")) + + def _view_actdone(state: TuiState, width: int, height: int) -> tuple: if state.running: words = {"remove": "Removing the files...", "restore": "Putting the files back...", @@ -26184,6 +27076,7 @@ _TUI_VIEWS: dict[str, Callable[[TuiState, int, int], tuple]] = { "device": _view_device, "emulators": _view_emulators, "more": _view_more, "remove": _view_remove, "removal": _view_removal, "backups": _view_backups, "backup": _view_backup, "actconfirm": _view_actconfirm, "actdone": _view_actdone, + "packplan": _view_packplan, "packdone": _view_packdone, } diff --git a/tests/fixtures/tui/colour-120x40.txt b/tests/fixtures/tui/colour-120x40.txt index bd2fed376..4d83d7fab 100644 --- a/tests/fixtures/tui/colour-120x40.txt +++ b/tests/fixtures/tui/colour-120x40.txt @@ -337,6 +337,7 @@ Copy the BIOS files from an old card or a folder Details Change + More Quit @@ -363,7 +364,6 @@ - ^[[0;1;35mA/Enter^[[0m Install ^[[0;2mB/Esc^[[0m Back ^[[0;2mY/o^[[0m Change ^[[0;2m?^[[0m Help @@ -376,7 +376,7 @@ ^[[0;7;35m > Close^[[0m Details Change - + More @@ -997,6 +997,7 @@ Copy the BIOS files from an old card or a folder Details Change + More Quit @@ -1019,7 +1020,6 @@ - ^[[0;1;35mA/Enter^[[0m Install ^[[0;2mB/Esc^[[0m Back ^[[0;2mY/o^[[0m Change ^[[0;2m?^[[0m Help @@ -1194,7 +1194,7 @@ Backups Put back a backup Delete a backup - + Make a pack @@ -1433,3 +1433,126 @@ ^[[0;1;35mA/Enter^[[0m Choose ^[[0;2mB/Esc^[[0m Back ^[[0;2m?^[[0m Help +=== pack-plan +^[[0;1m ^[[0;1;35mRetroBIOS^[[0;1m: Make a pack^[[0m + + 4 files, 1.0 MB, for RetroArch. + Pack: ~/Downloads/RetroArch_Custom_BIOS_Pack.zip + One ZIP, installed with --from-pack. + +^[[0;7;35m > Make the pack^[[0m + Change where + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ^[[0;1;35mA/Enter^[[0m Make ^[[0;2mB/Esc^[[0m Back ^[[0;2m?^[[0m Help +=== pack-plan-parts +^[[0;1m ^[[0;1;35mRetroBIOS^[[0;1m: Make a pack^[[0m + + 4 files, 1.0 MB, for RetroArch. + Pack: ~/Downloads/RetroArch_Custom_BIOS_Pack.part1of3.zip + In 3 parts of at most 3.9 GB, as FAT32 holds no file of 4 GB. + +^[[0;7;35m > Make the pack^[[0m + Change where + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ^[[0;1;35mA/Enter^[[0m Make ^[[0;2mB/Esc^[[0m Back ^[[0;2m?^[[0m Help +=== pack-done +^[[0;1m ^[[0;1;35mRetroBIOS^[[0;1m: ^[[0;1;32mDone^[[0m + +^[[0;1m Pack made: ^[[0;1;35m4^[[0;1m files, ^[[0;1;35m1023.4 KB^[[0;1m, in ^[[0;1;35m3^[[0;1m parts.^[[0m + Pack: ~/Downloads/RetroArch_Custom_BIOS_Pack.part1of3.zip + On the other device, install from it with --from-pack. + +^[[0;7;35m > Close^[[0m + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ^[[0;1;35mA/Enter^[[0m Close ^[[0;2mB/Esc^[[0m Back ^[[0;2m?^[[0m Help diff --git a/tests/fixtures/tui/colour-40x12.txt b/tests/fixtures/tui/colour-40x12.txt index ca8b09433..61e860630 100644 --- a/tests/fixtures/tui/colour-40x12.txt +++ b/tests/fixtures/tui/colour-40x12.txt @@ -108,12 +108,12 @@ ^[[0;1m ^[[0;1;35m4^[[0;1m files to download, ^[[0;1;35m1.0 MB^[[0m BIOS folder: ^[[0;1m~/.config/retroarch/system^[[0m + ^[[0;7;35m > Install^[[0m Choose systems Copy from an old card or a folder Details - Change - Quit +^[[0;2m 1-4 of 7^[[0m ^[[0;1;35mA^[[0m Install ^[[0;2mB^[[0m Back ^[[0;2mY^[[0m Change ^[[0;2m?^[[0m Help === plan-in-place ^[[0;1m ^[[0;1;35mRetroBIOS^[[0;1m: RetroArch^[[0m @@ -125,7 +125,7 @@ ^[[0;7;35m > Close^[[0m Details Change - + More ^[[0;1;35mA^[[0m Close ^[[0;2mB^[[0m Back ^[[0;2mY^[[0m Change ^[[0;2m?^[[0m Help === systems @@ -321,7 +321,7 @@ For the games on this card: yes 412 Only what starts: no Show the games -^[[0;2m 1-4 of 9^[[0m +^[[0;2m 1-4 of 10^[[0m ^[[0;1;35mA^[[0m Install ^[[0;2mB^[[0m Back ^[[0;2mY^[[0m Change ^[[0;2m?^[[0m Help === games ^[[0;1m ^[[0;1;35mRetroBIOS^[[0;1m: Games on this card^[[0m @@ -382,7 +382,7 @@ Backups Put back a backup Delete a backup - + Make a pack @@ -453,3 +453,42 @@ ^[[0;1;35mA^[[0m Choose ^[[0;2mB^[[0m Back ^[[0;2m?^[[0m Help +=== pack-plan +^[[0;1m ^[[0;1;35mRetroBIOS^[[0;1m: Make a pack^[[0m + + 4 files, 1.0 MB, for RetroArch. + Pack: ~/Downloads/ + ^[[0;1mRetroArch_Custom_BIOS_Pack.zip^[[0m + One ZIP, installed with --from-pack. + +^[[0;7;35m > Make the pack^[[0m + Change where + + + ^[[0;1;35mA^[[0m Make ^[[0;2mB^[[0m Back ^[[0;2m?^[[0m Help +=== pack-plan-parts +^[[0;1m ^[[0;1;35mRetroBIOS^[[0;1m: Make a pack^[[0m + + 4 files, 1.0 MB, for RetroArch. + Pack: ~/Downloads/ + ^[[0;1mRetroArch_Custom_BIOS_Pack.part1of3.^[[0m + ^[[0;1mzip^[[0m + In 3 parts of at most 3.9 GB, as FAT32 + holds no file of 4 GB. + +^[[0;7;35m > Make the pack^[[0m + Change where + ^[[0;1;35mA^[[0m Make ^[[0;2mB^[[0m Back ^[[0;2m?^[[0m Help +=== pack-done +^[[0;1m ^[[0;1;35mRetroBIOS^[[0;1m: ^[[0;1;32mDone^[[0m + +^[[0;1m Pack made: ^[[0;1;35m4^[[0;1m files, ^[[0;1;35m1023.4 KB^[[0;1m, in ^[[0;1;35m3^[[0m +^[[0;1m parts.^[[0m + Pack: ~/Downloads/ + ^[[0;1mRetroArch_Custom_BIOS_Pack.part1of3.^[[0m + ^[[0;1mzip^[[0m + On the other device, install from it + with --from-pack. + +^[[0;7;35m > Close^[[0m + ^[[0;1;35mA^[[0m Close ^[[0;2mB^[[0m Back ^[[0;2m?^[[0m Help diff --git a/tests/fixtures/tui/colour-40x15.txt b/tests/fixtures/tui/colour-40x15.txt index f04989f6e..3f9d7274d 100644 --- a/tests/fixtures/tui/colour-40x15.txt +++ b/tests/fixtures/tui/colour-40x15.txt @@ -138,9 +138,9 @@ Copy from an old card or a folder Details Change + More Quit - ^[[0;1;35mA^[[0m Install ^[[0;2mB^[[0m Back ^[[0;2mY^[[0m Change ^[[0;2m?^[[0m Help === plan-in-place ^[[0;1m ^[[0;1;35mRetroBIOS^[[0;1m: RetroArch^[[0m @@ -152,7 +152,7 @@ ^[[0;7;35m > Close^[[0m Details Change - + More @@ -388,6 +388,7 @@ ^[[0;1m ^[[0;1;35m4^[[0;1m files to download, ^[[0;1;35m1.0 MB^[[0m BIOS folder: ^[[0;1m~/.config/retroarch/system^[[0m + ^[[0;7;35m > Install^[[0m For the games on this card: yes 412 Only what starts: no @@ -395,8 +396,7 @@ Choose systems Copy from an old card or a folder Details - Change - Quit +^[[0;2m 1-7 of 10^[[0m ^[[0;1;35mA^[[0m Install ^[[0;2mB^[[0m Back ^[[0;2mY^[[0m Change ^[[0;2m?^[[0m Help === games ^[[0;1m ^[[0;1;35mRetroBIOS^[[0;1m: Games on this card^[[0m @@ -469,7 +469,7 @@ Backups Put back a backup Delete a backup - + Make a pack @@ -558,3 +558,51 @@ ^[[0;1;35mA^[[0m Choose ^[[0;2mB^[[0m Back ^[[0;2m?^[[0m Help +=== pack-plan +^[[0;1m ^[[0;1;35mRetroBIOS^[[0;1m: Make a pack^[[0m + + 4 files, 1.0 MB, for RetroArch. + Pack: ~/Downloads/ + ^[[0;1mRetroArch_Custom_BIOS_Pack.zip^[[0m + One ZIP, installed with --from-pack. + +^[[0;7;35m > Make the pack^[[0m + Change where + + + + + + ^[[0;1;35mA^[[0m Make ^[[0;2mB^[[0m Back ^[[0;2m?^[[0m Help +=== pack-plan-parts +^[[0;1m ^[[0;1;35mRetroBIOS^[[0;1m: Make a pack^[[0m + + 4 files, 1.0 MB, for RetroArch. + Pack: ~/Downloads/ + ^[[0;1mRetroArch_Custom_BIOS_Pack.part1of3.^[[0m + ^[[0;1mzip^[[0m + In 3 parts of at most 3.9 GB, as FAT32 + holds no file of 4 GB. + +^[[0;7;35m > Make the pack^[[0m + Change where + + + + ^[[0;1;35mA^[[0m Make ^[[0;2mB^[[0m Back ^[[0;2m?^[[0m Help +=== pack-done +^[[0;1m ^[[0;1;35mRetroBIOS^[[0;1m: ^[[0;1;32mDone^[[0m + +^[[0;1m Pack made: ^[[0;1;35m4^[[0;1m files, ^[[0;1;35m1023.4 KB^[[0;1m, in ^[[0;1;35m3^[[0m +^[[0;1m parts.^[[0m + Pack: ~/Downloads/ + ^[[0;1mRetroArch_Custom_BIOS_Pack.part1of3.^[[0m + ^[[0;1mzip^[[0m + On the other device, install from it + with --from-pack. + +^[[0;7;35m > Close^[[0m + + + + ^[[0;1;35mA^[[0m Close ^[[0;2mB^[[0m Back ^[[0;2m?^[[0m Help diff --git a/tests/fixtures/tui/colour-80x24.txt b/tests/fixtures/tui/colour-80x24.txt index cc8570b48..672214f9d 100644 --- a/tests/fixtures/tui/colour-80x24.txt +++ b/tests/fixtures/tui/colour-80x24.txt @@ -209,6 +209,7 @@ Copy the BIOS files from an old card or a folder Details Change + More Quit @@ -221,7 +222,6 @@ - ^[[0;1;35mA/Enter^[[0m Install ^[[0;2mB/Esc^[[0m Back ^[[0;2mY/o^[[0m Change ^[[0;2m?^[[0m Help === plan-in-place ^[[0;1m ^[[0;1;35mRetroBIOS^[[0;1m: RetroArch^[[0m @@ -232,7 +232,7 @@ ^[[0;7;35m > Close^[[0m Details Change - + More @@ -613,6 +613,7 @@ Copy the BIOS files from an old card or a folder Details Change + More Quit @@ -621,7 +622,6 @@ - ^[[0;1;35mA/Enter^[[0m Install ^[[0;2mB/Esc^[[0m Back ^[[0;2mY/o^[[0m Change ^[[0;2m?^[[0m Help === games ^[[0;1m ^[[0;1;35mRetroBIOS^[[0;1m: Games on this card^[[0m @@ -730,7 +730,7 @@ Backups Put back a backup Delete a backup - + Make a pack @@ -873,3 +873,78 @@ ^[[0;1;35mA/Enter^[[0m Choose ^[[0;2mB/Esc^[[0m Back ^[[0;2m?^[[0m Help +=== pack-plan +^[[0;1m ^[[0;1;35mRetroBIOS^[[0;1m: Make a pack^[[0m + + 4 files, 1.0 MB, for RetroArch. + Pack: ~/Downloads/RetroArch_Custom_BIOS_Pack.zip + One ZIP, installed with --from-pack. + +^[[0;7;35m > Make the pack^[[0m + Change where + + + + + + + + + + + + + + + + ^[[0;1;35mA/Enter^[[0m Make ^[[0;2mB/Esc^[[0m Back ^[[0;2m?^[[0m Help +=== pack-plan-parts +^[[0;1m ^[[0;1;35mRetroBIOS^[[0;1m: Make a pack^[[0m + + 4 files, 1.0 MB, for RetroArch. + Pack: ~/Downloads/RetroArch_Custom_BIOS_Pack.part1of3.zip + In 3 parts of at most 3.9 GB, as FAT32 holds no file of 4 GB. + +^[[0;7;35m > Make the pack^[[0m + Change where + + + + + + + + + + + + + + + + ^[[0;1;35mA/Enter^[[0m Make ^[[0;2mB/Esc^[[0m Back ^[[0;2m?^[[0m Help +=== pack-done +^[[0;1m ^[[0;1;35mRetroBIOS^[[0;1m: ^[[0;1;32mDone^[[0m + +^[[0;1m Pack made: ^[[0;1;35m4^[[0;1m files, ^[[0;1;35m1023.4 KB^[[0;1m, in ^[[0;1;35m3^[[0;1m parts.^[[0m + Pack: ~/Downloads/RetroArch_Custom_BIOS_Pack.part1of3.zip + On the other device, install from it with --from-pack. + +^[[0;7;35m > Close^[[0m + + + + + + + + + + + + + + + + + ^[[0;1;35mA/Enter^[[0m Close ^[[0;2mB/Esc^[[0m Back ^[[0;2m?^[[0m Help diff --git a/tests/fixtures/tui/more-120x40.txt b/tests/fixtures/tui/more-120x40.txt index 60e3ad3b9..febfd566a 100644 --- a/tests/fixtures/tui/more-120x40.txt +++ b/tests/fixtures/tui/more-120x40.txt @@ -4,7 +4,7 @@ Backups Put back a backup Delete a backup - + Make a pack diff --git a/tests/fixtures/tui/more-40x12.txt b/tests/fixtures/tui/more-40x12.txt index ae70101fa..2256e66c6 100644 --- a/tests/fixtures/tui/more-40x12.txt +++ b/tests/fixtures/tui/more-40x12.txt @@ -4,7 +4,7 @@ Backups Put back a backup Delete a backup - + Make a pack diff --git a/tests/fixtures/tui/more-40x15.txt b/tests/fixtures/tui/more-40x15.txt index f6d6a6794..1db338dcb 100644 --- a/tests/fixtures/tui/more-40x15.txt +++ b/tests/fixtures/tui/more-40x15.txt @@ -4,7 +4,7 @@ Backups Put back a backup Delete a backup - + Make a pack diff --git a/tests/fixtures/tui/more-80x24.txt b/tests/fixtures/tui/more-80x24.txt index 2d1d511d9..00baa9073 100644 --- a/tests/fixtures/tui/more-80x24.txt +++ b/tests/fixtures/tui/more-80x24.txt @@ -4,7 +4,7 @@ Backups Put back a backup Delete a backup - + Make a pack diff --git a/tests/fixtures/tui/pack-done-120x40.txt b/tests/fixtures/tui/pack-done-120x40.txt new file mode 100644 index 000000000..2487a5c3d --- /dev/null +++ b/tests/fixtures/tui/pack-done-120x40.txt @@ -0,0 +1,40 @@ + RetroBIOS: Done + + Pack made: 4 files, 1023.4 KB, in 3 parts. + Pack: ~/Downloads/RetroArch_Custom_BIOS_Pack.part1of3.zip + On the other device, install from it with --from-pack. + + > Close + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + A/Enter Close B/Esc Back ? Help diff --git a/tests/fixtures/tui/pack-done-40x12.txt b/tests/fixtures/tui/pack-done-40x12.txt new file mode 100644 index 000000000..282491972 --- /dev/null +++ b/tests/fixtures/tui/pack-done-40x12.txt @@ -0,0 +1,12 @@ + RetroBIOS: Done + + Pack made: 4 files, 1023.4 KB, in 3 + parts. + Pack: ~/Downloads/ + RetroArch_Custom_BIOS_Pack.part1of3. + zip + On the other device, install from it + with --from-pack. + + > Close + A Close B Back ? Help diff --git a/tests/fixtures/tui/pack-done-40x15.txt b/tests/fixtures/tui/pack-done-40x15.txt new file mode 100644 index 000000000..e2b470d27 --- /dev/null +++ b/tests/fixtures/tui/pack-done-40x15.txt @@ -0,0 +1,15 @@ + RetroBIOS: Done + + Pack made: 4 files, 1023.4 KB, in 3 + parts. + Pack: ~/Downloads/ + RetroArch_Custom_BIOS_Pack.part1of3. + zip + On the other device, install from it + with --from-pack. + + > Close + + + + A Close B Back ? Help diff --git a/tests/fixtures/tui/pack-done-80x24.txt b/tests/fixtures/tui/pack-done-80x24.txt new file mode 100644 index 000000000..944cf7c92 --- /dev/null +++ b/tests/fixtures/tui/pack-done-80x24.txt @@ -0,0 +1,24 @@ + RetroBIOS: Done + + Pack made: 4 files, 1023.4 KB, in 3 parts. + Pack: ~/Downloads/RetroArch_Custom_BIOS_Pack.part1of3.zip + On the other device, install from it with --from-pack. + + > Close + + + + + + + + + + + + + + + + + A/Enter Close B/Esc Back ? Help diff --git a/tests/fixtures/tui/pack-plan-120x40.txt b/tests/fixtures/tui/pack-plan-120x40.txt new file mode 100644 index 000000000..2cd4321a4 --- /dev/null +++ b/tests/fixtures/tui/pack-plan-120x40.txt @@ -0,0 +1,40 @@ + RetroBIOS: Make a pack + + 4 files, 1.0 MB, for RetroArch. + Pack: ~/Downloads/RetroArch_Custom_BIOS_Pack.zip + One ZIP, installed with --from-pack. + + > Make the pack + Change where + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + A/Enter Make B/Esc Back ? Help diff --git a/tests/fixtures/tui/pack-plan-40x12.txt b/tests/fixtures/tui/pack-plan-40x12.txt new file mode 100644 index 000000000..1773fd6c0 --- /dev/null +++ b/tests/fixtures/tui/pack-plan-40x12.txt @@ -0,0 +1,12 @@ + RetroBIOS: Make a pack + + 4 files, 1.0 MB, for RetroArch. + Pack: ~/Downloads/ + RetroArch_Custom_BIOS_Pack.zip + One ZIP, installed with --from-pack. + + > Make the pack + Change where + + + A Make B Back ? Help diff --git a/tests/fixtures/tui/pack-plan-40x15.txt b/tests/fixtures/tui/pack-plan-40x15.txt new file mode 100644 index 000000000..30d814263 --- /dev/null +++ b/tests/fixtures/tui/pack-plan-40x15.txt @@ -0,0 +1,15 @@ + RetroBIOS: Make a pack + + 4 files, 1.0 MB, for RetroArch. + Pack: ~/Downloads/ + RetroArch_Custom_BIOS_Pack.zip + One ZIP, installed with --from-pack. + + > Make the pack + Change where + + + + + + A Make B Back ? Help diff --git a/tests/fixtures/tui/pack-plan-80x24.txt b/tests/fixtures/tui/pack-plan-80x24.txt new file mode 100644 index 000000000..798a0d430 --- /dev/null +++ b/tests/fixtures/tui/pack-plan-80x24.txt @@ -0,0 +1,24 @@ + RetroBIOS: Make a pack + + 4 files, 1.0 MB, for RetroArch. + Pack: ~/Downloads/RetroArch_Custom_BIOS_Pack.zip + One ZIP, installed with --from-pack. + + > Make the pack + Change where + + + + + + + + + + + + + + + + A/Enter Make B/Esc Back ? Help diff --git a/tests/fixtures/tui/pack-plan-parts-120x40.txt b/tests/fixtures/tui/pack-plan-parts-120x40.txt new file mode 100644 index 000000000..69f932d2b --- /dev/null +++ b/tests/fixtures/tui/pack-plan-parts-120x40.txt @@ -0,0 +1,40 @@ + RetroBIOS: Make a pack + + 4 files, 1.0 MB, for RetroArch. + Pack: ~/Downloads/RetroArch_Custom_BIOS_Pack.part1of3.zip + In 3 parts of at most 3.9 GB, as FAT32 holds no file of 4 GB. + + > Make the pack + Change where + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + A/Enter Make B/Esc Back ? Help diff --git a/tests/fixtures/tui/pack-plan-parts-40x12.txt b/tests/fixtures/tui/pack-plan-parts-40x12.txt new file mode 100644 index 000000000..afb5674c8 --- /dev/null +++ b/tests/fixtures/tui/pack-plan-parts-40x12.txt @@ -0,0 +1,12 @@ + RetroBIOS: Make a pack + + 4 files, 1.0 MB, for RetroArch. + Pack: ~/Downloads/ + RetroArch_Custom_BIOS_Pack.part1of3. + zip + In 3 parts of at most 3.9 GB, as FAT32 + holds no file of 4 GB. + + > Make the pack + Change where + A Make B Back ? Help diff --git a/tests/fixtures/tui/pack-plan-parts-40x15.txt b/tests/fixtures/tui/pack-plan-parts-40x15.txt new file mode 100644 index 000000000..05ff70358 --- /dev/null +++ b/tests/fixtures/tui/pack-plan-parts-40x15.txt @@ -0,0 +1,15 @@ + RetroBIOS: Make a pack + + 4 files, 1.0 MB, for RetroArch. + Pack: ~/Downloads/ + RetroArch_Custom_BIOS_Pack.part1of3. + zip + In 3 parts of at most 3.9 GB, as FAT32 + holds no file of 4 GB. + + > Make the pack + Change where + + + + A Make B Back ? Help diff --git a/tests/fixtures/tui/pack-plan-parts-80x24.txt b/tests/fixtures/tui/pack-plan-parts-80x24.txt new file mode 100644 index 000000000..70507a0d8 --- /dev/null +++ b/tests/fixtures/tui/pack-plan-parts-80x24.txt @@ -0,0 +1,24 @@ + RetroBIOS: Make a pack + + 4 files, 1.0 MB, for RetroArch. + Pack: ~/Downloads/RetroArch_Custom_BIOS_Pack.part1of3.zip + In 3 parts of at most 3.9 GB, as FAT32 holds no file of 4 GB. + + > Make the pack + Change where + + + + + + + + + + + + + + + + A/Enter Make B/Esc Back ? Help diff --git a/tests/fixtures/tui/plan-120x40.txt b/tests/fixtures/tui/plan-120x40.txt index e13a1f79c..2730938be 100644 --- a/tests/fixtures/tui/plan-120x40.txt +++ b/tests/fixtures/tui/plan-120x40.txt @@ -8,6 +8,7 @@ Copy the BIOS files from an old card or a folder Details Change + More Quit @@ -34,7 +35,6 @@ - A/Enter Install B/Esc Back Y/o Change ? Help diff --git a/tests/fixtures/tui/plan-40x12.txt b/tests/fixtures/tui/plan-40x12.txt index 86f6ecb9e..5eed40509 100644 --- a/tests/fixtures/tui/plan-40x12.txt +++ b/tests/fixtures/tui/plan-40x12.txt @@ -3,10 +3,10 @@ 4 files to download, 1.0 MB BIOS folder: ~/.config/retroarch/system + > Install Choose systems Copy from an old card or a folder Details - Change - Quit + 1-4 of 7 A Install B Back Y Change ? Help diff --git a/tests/fixtures/tui/plan-40x15.txt b/tests/fixtures/tui/plan-40x15.txt index 7f1b90d34..b94b96cb5 100644 --- a/tests/fixtures/tui/plan-40x15.txt +++ b/tests/fixtures/tui/plan-40x15.txt @@ -9,7 +9,7 @@ Copy from an old card or a folder Details Change + More Quit - A Install B Back Y Change ? Help diff --git a/tests/fixtures/tui/plan-80x24.txt b/tests/fixtures/tui/plan-80x24.txt index 4465455ca..bbd567d2b 100644 --- a/tests/fixtures/tui/plan-80x24.txt +++ b/tests/fixtures/tui/plan-80x24.txt @@ -8,6 +8,7 @@ Copy the BIOS files from an old card or a folder Details Change + More Quit @@ -20,5 +21,4 @@ - A/Enter Install B/Esc Back Y/o Change ? Help diff --git a/tests/fixtures/tui/plan-games-120x40.txt b/tests/fixtures/tui/plan-games-120x40.txt index abde59b88..4ce2aa67e 100644 --- a/tests/fixtures/tui/plan-games-120x40.txt +++ b/tests/fixtures/tui/plan-games-120x40.txt @@ -12,6 +12,7 @@ Copy the BIOS files from an old card or a folder Details Change + More Quit @@ -34,7 +35,6 @@ - A/Enter Install B/Esc Back Y/o Change ? Help diff --git a/tests/fixtures/tui/plan-games-40x12.txt b/tests/fixtures/tui/plan-games-40x12.txt index 74547d4d2..7567ec176 100644 --- a/tests/fixtures/tui/plan-games-40x12.txt +++ b/tests/fixtures/tui/plan-games-40x12.txt @@ -8,5 +8,5 @@ For the games on this card: yes 412 Only what starts: no Show the games - 1-4 of 9 + 1-4 of 10 A Install B Back Y Change ? Help diff --git a/tests/fixtures/tui/plan-games-40x15.txt b/tests/fixtures/tui/plan-games-40x15.txt index 86f7e3feb..73df3bebd 100644 --- a/tests/fixtures/tui/plan-games-40x15.txt +++ b/tests/fixtures/tui/plan-games-40x15.txt @@ -3,6 +3,7 @@ 4 files to download, 1.0 MB BIOS folder: ~/.config/retroarch/system + > Install For the games on this card: yes 412 Only what starts: no @@ -10,6 +11,5 @@ Choose systems Copy from an old card or a folder Details - Change - Quit + 1-7 of 10 A Install B Back Y Change ? Help diff --git a/tests/fixtures/tui/plan-games-80x24.txt b/tests/fixtures/tui/plan-games-80x24.txt index 38ae53edb..4fe964e80 100644 --- a/tests/fixtures/tui/plan-games-80x24.txt +++ b/tests/fixtures/tui/plan-games-80x24.txt @@ -12,6 +12,7 @@ Copy the BIOS files from an old card or a folder Details Change + More Quit @@ -20,5 +21,4 @@ - A/Enter Install B/Esc Back Y/o Change ? Help diff --git a/tests/fixtures/tui/plan-in-place-120x40.txt b/tests/fixtures/tui/plan-in-place-120x40.txt index 466492ed6..4a24a9ee5 100644 --- a/tests/fixtures/tui/plan-in-place-120x40.txt +++ b/tests/fixtures/tui/plan-in-place-120x40.txt @@ -6,7 +6,7 @@ > Close Details Change - + More diff --git a/tests/fixtures/tui/plan-in-place-40x12.txt b/tests/fixtures/tui/plan-in-place-40x12.txt index 360413780..334cca29a 100644 --- a/tests/fixtures/tui/plan-in-place-40x12.txt +++ b/tests/fixtures/tui/plan-in-place-40x12.txt @@ -7,6 +7,6 @@ > Close Details Change - + More A Close B Back Y Change ? Help diff --git a/tests/fixtures/tui/plan-in-place-40x15.txt b/tests/fixtures/tui/plan-in-place-40x15.txt index 15e3895ac..d4a344ab1 100644 --- a/tests/fixtures/tui/plan-in-place-40x15.txt +++ b/tests/fixtures/tui/plan-in-place-40x15.txt @@ -7,7 +7,7 @@ > Close Details Change - + More diff --git a/tests/fixtures/tui/plan-in-place-80x24.txt b/tests/fixtures/tui/plan-in-place-80x24.txt index 66f1f191e..82eb9414c 100644 --- a/tests/fixtures/tui/plan-in-place-80x24.txt +++ b/tests/fixtures/tui/plan-in-place-80x24.txt @@ -6,7 +6,7 @@ > Close Details Change - + More diff --git a/tests/fixtures/tui/route-evmapy.txt b/tests/fixtures/tui/route-evmapy.txt index bf31d3862..3dc99f2ab 100644 --- a/tests/fixtures/tui/route-evmapy.txt +++ b/tests/fixtures/tui/route-evmapy.txt @@ -407,12 +407,12 @@ 4 files to download, 1.0 MB BIOS folder: ~/.config/retroarch/system + > Install Choose systems Copy from an old card or a folder Details - Change - Quit + 1-4 of 7 A Install B Back Y Change === plan 40x15 RetroBIOS: RetroArch @@ -426,9 +426,9 @@ Copy from an old card or a folder Details Change + More Quit - A Install B Back Y Change === plan 80x24 RetroBIOS: RetroArch @@ -441,6 +441,7 @@ Copy the BIOS files from an old card or a folder Details Change + More Quit @@ -453,7 +454,6 @@ - A Install B Back Y Change === plan-in-place 40x12 RetroBIOS: RetroArch @@ -465,7 +465,7 @@ > Close Details Change - + More A Close B Back Y Change === plan-in-place 40x15 @@ -478,7 +478,7 @@ > Close Details Change - + More @@ -493,7 +493,7 @@ > Close Details Change - + More @@ -1144,7 +1144,7 @@ For the games on this card: yes 412 Only what starts: no Show the games - 1-4 of 9 + 1-4 of 10 A Install B Back Y Change === plan-games 40x15 RetroBIOS: RetroArch @@ -1152,6 +1152,7 @@ 4 files to download, 1.0 MB BIOS folder: ~/.config/retroarch/system + > Install For the games on this card: yes 412 Only what starts: no @@ -1159,8 +1160,7 @@ Choose systems Copy from an old card or a folder Details - Change - Quit + 1-7 of 10 A Install B Back Y Change === plan-games 80x24 RetroBIOS: RetroArch @@ -1177,6 +1177,7 @@ Copy the BIOS files from an old card or a folder Details Change + More Quit @@ -1185,7 +1186,6 @@ - A Install B Back Y Change === games 80x24 RetroBIOS: Games on this card @@ -1352,7 +1352,7 @@ Backups Put back a backup Delete a backup - + Make a pack @@ -1365,7 +1365,7 @@ Backups Put back a backup Delete a backup - + Make a pack @@ -1381,7 +1381,7 @@ Backups Put back a backup Delete a backup - + Make a pack @@ -1669,3 +1669,165 @@ A Choose B Back +=== pack-plan 40x12 + RetroBIOS: Make a pack + + 4 files, 1.0 MB, for RetroArch. + Pack: ~/Downloads/ + RetroArch_Custom_BIOS_Pack.zip + One ZIP, installed with --from-pack. + + > Make the pack + Change where + + + A Make B Back +=== pack-plan 40x15 + RetroBIOS: Make a pack + + 4 files, 1.0 MB, for RetroArch. + Pack: ~/Downloads/ + RetroArch_Custom_BIOS_Pack.zip + One ZIP, installed with --from-pack. + + > Make the pack + Change where + + + + + + A Make B Back +=== pack-plan 80x24 + RetroBIOS: Make a pack + + 4 files, 1.0 MB, for RetroArch. + Pack: ~/Downloads/RetroArch_Custom_BIOS_Pack.zip + One ZIP, installed with --from-pack. + + > Make the pack + Change where + + + + + + + + + + + + + + + + A Make B Back +=== pack-plan-parts 40x12 + RetroBIOS: Make a pack + + 4 files, 1.0 MB, for RetroArch. + Pack: ~/Downloads/ + RetroArch_Custom_BIOS_Pack.part1of3. + zip + In 3 parts of at most 3.9 GB, as FAT32 + holds no file of 4 GB. + + > Make the pack + Change where + A Make B Back +=== pack-plan-parts 40x15 + RetroBIOS: Make a pack + + 4 files, 1.0 MB, for RetroArch. + Pack: ~/Downloads/ + RetroArch_Custom_BIOS_Pack.part1of3. + zip + In 3 parts of at most 3.9 GB, as FAT32 + holds no file of 4 GB. + + > Make the pack + Change where + + + + A Make B Back +=== pack-plan-parts 80x24 + RetroBIOS: Make a pack + + 4 files, 1.0 MB, for RetroArch. + Pack: ~/Downloads/RetroArch_Custom_BIOS_Pack.part1of3.zip + In 3 parts of at most 3.9 GB, as FAT32 holds no file of 4 GB. + + > Make the pack + Change where + + + + + + + + + + + + + + + + A Make B Back +=== pack-done 40x12 + RetroBIOS: Done + + Pack made: 4 files, 1023.4 KB, in 3 + parts. + Pack: ~/Downloads/ + RetroArch_Custom_BIOS_Pack.part1of3. + zip + On the other device, install from it + with --from-pack. + + > Close + A Close B Back +=== pack-done 40x15 + RetroBIOS: Done + + Pack made: 4 files, 1023.4 KB, in 3 + parts. + Pack: ~/Downloads/ + RetroArch_Custom_BIOS_Pack.part1of3. + zip + On the other device, install from it + with --from-pack. + + > Close + + + + A Close B Back +=== pack-done 80x24 + RetroBIOS: Done + + Pack made: 4 files, 1023.4 KB, in 3 parts. + Pack: ~/Downloads/RetroArch_Custom_BIOS_Pack.part1of3.zip + On the other device, install from it with --from-pack. + + > Close + + + + + + + + + + + + + + + + + A Close B Back diff --git a/tests/fixtures/tui/route-gptokeyb.txt b/tests/fixtures/tui/route-gptokeyb.txt index e8753e477..2199e8666 100644 --- a/tests/fixtures/tui/route-gptokeyb.txt +++ b/tests/fixtures/tui/route-gptokeyb.txt @@ -407,12 +407,12 @@ 4 files to download, 1.0 MB BIOS folder: ~/.config/retroarch/system + > Install Choose systems Copy from an old card or a folder Details - Change - Quit + 1-4 of 7 A Install B Back Y Change === plan 40x15 RetroBIOS: RetroArch @@ -426,9 +426,9 @@ Copy from an old card or a folder Details Change + More Quit - A Install B Back Y Change === plan 80x24 RetroBIOS: RetroArch @@ -441,6 +441,7 @@ Copy the BIOS files from an old card or a folder Details Change + More Quit @@ -453,7 +454,6 @@ - A Install B Back Y Change === plan-in-place 40x12 RetroBIOS: RetroArch @@ -465,7 +465,7 @@ > Close Details Change - + More A Close B Back Y Change === plan-in-place 40x15 @@ -478,7 +478,7 @@ > Close Details Change - + More @@ -493,7 +493,7 @@ > Close Details Change - + More @@ -1144,7 +1144,7 @@ For the games on this card: yes 412 Only what starts: no Show the games - 1-4 of 9 + 1-4 of 10 A Install B Back Y Change === plan-games 40x15 RetroBIOS: RetroArch @@ -1152,6 +1152,7 @@ 4 files to download, 1.0 MB BIOS folder: ~/.config/retroarch/system + > Install For the games on this card: yes 412 Only what starts: no @@ -1159,8 +1160,7 @@ Choose systems Copy from an old card or a folder Details - Change - Quit + 1-7 of 10 A Install B Back Y Change === plan-games 80x24 RetroBIOS: RetroArch @@ -1177,6 +1177,7 @@ Copy the BIOS files from an old card or a folder Details Change + More Quit @@ -1185,7 +1186,6 @@ - A Install B Back Y Change === games 80x24 RetroBIOS: Games on this card @@ -1352,7 +1352,7 @@ Backups Put back a backup Delete a backup - + Make a pack @@ -1365,7 +1365,7 @@ Backups Put back a backup Delete a backup - + Make a pack @@ -1381,7 +1381,7 @@ Backups Put back a backup Delete a backup - + Make a pack @@ -1669,3 +1669,165 @@ A Choose B Back +=== pack-plan 40x12 + RetroBIOS: Make a pack + + 4 files, 1.0 MB, for RetroArch. + Pack: ~/Downloads/ + RetroArch_Custom_BIOS_Pack.zip + One ZIP, installed with --from-pack. + + > Make the pack + Change where + + + A Make B Back +=== pack-plan 40x15 + RetroBIOS: Make a pack + + 4 files, 1.0 MB, for RetroArch. + Pack: ~/Downloads/ + RetroArch_Custom_BIOS_Pack.zip + One ZIP, installed with --from-pack. + + > Make the pack + Change where + + + + + + A Make B Back +=== pack-plan 80x24 + RetroBIOS: Make a pack + + 4 files, 1.0 MB, for RetroArch. + Pack: ~/Downloads/RetroArch_Custom_BIOS_Pack.zip + One ZIP, installed with --from-pack. + + > Make the pack + Change where + + + + + + + + + + + + + + + + A Make B Back +=== pack-plan-parts 40x12 + RetroBIOS: Make a pack + + 4 files, 1.0 MB, for RetroArch. + Pack: ~/Downloads/ + RetroArch_Custom_BIOS_Pack.part1of3. + zip + In 3 parts of at most 3.9 GB, as FAT32 + holds no file of 4 GB. + + > Make the pack + Change where + A Make B Back +=== pack-plan-parts 40x15 + RetroBIOS: Make a pack + + 4 files, 1.0 MB, for RetroArch. + Pack: ~/Downloads/ + RetroArch_Custom_BIOS_Pack.part1of3. + zip + In 3 parts of at most 3.9 GB, as FAT32 + holds no file of 4 GB. + + > Make the pack + Change where + + + + A Make B Back +=== pack-plan-parts 80x24 + RetroBIOS: Make a pack + + 4 files, 1.0 MB, for RetroArch. + Pack: ~/Downloads/RetroArch_Custom_BIOS_Pack.part1of3.zip + In 3 parts of at most 3.9 GB, as FAT32 holds no file of 4 GB. + + > Make the pack + Change where + + + + + + + + + + + + + + + + A Make B Back +=== pack-done 40x12 + RetroBIOS: Done + + Pack made: 4 files, 1023.4 KB, in 3 + parts. + Pack: ~/Downloads/ + RetroArch_Custom_BIOS_Pack.part1of3. + zip + On the other device, install from it + with --from-pack. + + > Close + A Close B Back +=== pack-done 40x15 + RetroBIOS: Done + + Pack made: 4 files, 1023.4 KB, in 3 + parts. + Pack: ~/Downloads/ + RetroArch_Custom_BIOS_Pack.part1of3. + zip + On the other device, install from it + with --from-pack. + + > Close + + + + A Close B Back +=== pack-done 80x24 + RetroBIOS: Done + + Pack made: 4 files, 1023.4 KB, in 3 parts. + Pack: ~/Downloads/RetroArch_Custom_BIOS_Pack.part1of3.zip + On the other device, install from it with --from-pack. + + > Close + + + + + + + + + + + + + + + + + A Close B Back diff --git a/tests/fixtures/tui/route-gptokeyb_muxterm.txt b/tests/fixtures/tui/route-gptokeyb_muxterm.txt index ed09cc872..0f47f0e63 100644 --- a/tests/fixtures/tui/route-gptokeyb_muxterm.txt +++ b/tests/fixtures/tui/route-gptokeyb_muxterm.txt @@ -407,12 +407,12 @@ 4 files to download, 1.0 MB BIOS folder: ~/.config/retroarch/system + > Install Choose systems Copy from an old card or a folder Details - Change - Quit + 1-4 of 7 A Install B Back Y Change === plan 40x15 RetroBIOS: RetroArch @@ -426,9 +426,9 @@ Copy from an old card or a folder Details Change + More Quit - A Install B Back Y Change === plan 80x24 RetroBIOS: RetroArch @@ -441,6 +441,7 @@ Copy the BIOS files from an old card or a folder Details Change + More Quit @@ -453,7 +454,6 @@ - A Install B Back Y Change === plan-in-place 40x12 RetroBIOS: RetroArch @@ -465,7 +465,7 @@ > Close Details Change - + More A Close B Back Y Change === plan-in-place 40x15 @@ -478,7 +478,7 @@ > Close Details Change - + More @@ -493,7 +493,7 @@ > Close Details Change - + More @@ -1144,7 +1144,7 @@ For the games on this card: yes 412 Only what starts: no Show the games - 1-4 of 9 + 1-4 of 10 A Install B Back Y Change === plan-games 40x15 RetroBIOS: RetroArch @@ -1152,6 +1152,7 @@ 4 files to download, 1.0 MB BIOS folder: ~/.config/retroarch/system + > Install For the games on this card: yes 412 Only what starts: no @@ -1159,8 +1160,7 @@ Choose systems Copy from an old card or a folder Details - Change - Quit + 1-7 of 10 A Install B Back Y Change === plan-games 80x24 RetroBIOS: RetroArch @@ -1177,6 +1177,7 @@ Copy the BIOS files from an old card or a folder Details Change + More Quit @@ -1185,7 +1186,6 @@ - A Install B Back Y Change === games 80x24 RetroBIOS: Games on this card @@ -1352,7 +1352,7 @@ Backups Put back a backup Delete a backup - + Make a pack @@ -1365,7 +1365,7 @@ Backups Put back a backup Delete a backup - + Make a pack @@ -1381,7 +1381,7 @@ Backups Put back a backup Delete a backup - + Make a pack @@ -1669,3 +1669,165 @@ A Choose B Back +=== pack-plan 40x12 + RetroBIOS: Make a pack + + 4 files, 1.0 MB, for RetroArch. + Pack: ~/Downloads/ + RetroArch_Custom_BIOS_Pack.zip + One ZIP, installed with --from-pack. + + > Make the pack + Change where + + + A Make B Back +=== pack-plan 40x15 + RetroBIOS: Make a pack + + 4 files, 1.0 MB, for RetroArch. + Pack: ~/Downloads/ + RetroArch_Custom_BIOS_Pack.zip + One ZIP, installed with --from-pack. + + > Make the pack + Change where + + + + + + A Make B Back +=== pack-plan 80x24 + RetroBIOS: Make a pack + + 4 files, 1.0 MB, for RetroArch. + Pack: ~/Downloads/RetroArch_Custom_BIOS_Pack.zip + One ZIP, installed with --from-pack. + + > Make the pack + Change where + + + + + + + + + + + + + + + + A Make B Back +=== pack-plan-parts 40x12 + RetroBIOS: Make a pack + + 4 files, 1.0 MB, for RetroArch. + Pack: ~/Downloads/ + RetroArch_Custom_BIOS_Pack.part1of3. + zip + In 3 parts of at most 3.9 GB, as FAT32 + holds no file of 4 GB. + + > Make the pack + Change where + A Make B Back +=== pack-plan-parts 40x15 + RetroBIOS: Make a pack + + 4 files, 1.0 MB, for RetroArch. + Pack: ~/Downloads/ + RetroArch_Custom_BIOS_Pack.part1of3. + zip + In 3 parts of at most 3.9 GB, as FAT32 + holds no file of 4 GB. + + > Make the pack + Change where + + + + A Make B Back +=== pack-plan-parts 80x24 + RetroBIOS: Make a pack + + 4 files, 1.0 MB, for RetroArch. + Pack: ~/Downloads/RetroArch_Custom_BIOS_Pack.part1of3.zip + In 3 parts of at most 3.9 GB, as FAT32 holds no file of 4 GB. + + > Make the pack + Change where + + + + + + + + + + + + + + + + A Make B Back +=== pack-done 40x12 + RetroBIOS: Done + + Pack made: 4 files, 1023.4 KB, in 3 + parts. + Pack: ~/Downloads/ + RetroArch_Custom_BIOS_Pack.part1of3. + zip + On the other device, install from it + with --from-pack. + + > Close + A Close B Back +=== pack-done 40x15 + RetroBIOS: Done + + Pack made: 4 files, 1023.4 KB, in 3 + parts. + Pack: ~/Downloads/ + RetroArch_Custom_BIOS_Pack.part1of3. + zip + On the other device, install from it + with --from-pack. + + > Close + + + + A Close B Back +=== pack-done 80x24 + RetroBIOS: Done + + Pack made: 4 files, 1023.4 KB, in 3 parts. + Pack: ~/Downloads/RetroArch_Custom_BIOS_Pack.part1of3.zip + On the other device, install from it with --from-pack. + + > Close + + + + + + + + + + + + + + + + + A Close B Back diff --git a/tests/fixtures/tui/route-keys.txt b/tests/fixtures/tui/route-keys.txt index 18fad0816..f44cac139 100644 --- a/tests/fixtures/tui/route-keys.txt +++ b/tests/fixtures/tui/route-keys.txt @@ -382,12 +382,12 @@ 4 files to download, 1.0 MB BIOS folder: ~/.config/retroarch/system + > Install Choose systems Copy from an old card or a folder Details - Change - Quit + 1-4 of 7 Enter Install Esc Back o Change === plan 40x15 RetroBIOS: RetroArch @@ -401,9 +401,9 @@ Copy from an old card or a folder Details Change + More Quit - Enter Install Esc Back o Change === plan 80x24 RetroBIOS: RetroArch @@ -416,6 +416,7 @@ Copy the BIOS files from an old card or a folder Details Change + More Quit @@ -428,7 +429,6 @@ - Enter Install Esc Back o Change ? Help === plan-in-place 40x12 RetroBIOS: RetroArch @@ -440,7 +440,7 @@ > Close Details Change - + More Enter Close Esc Back o Change === plan-in-place 40x15 @@ -453,7 +453,7 @@ > Close Details Change - + More @@ -468,7 +468,7 @@ > Close Details Change - + More @@ -1251,7 +1251,7 @@ For the games on this card: yes 412 Only what starts: no Show the games - 1-4 of 9 + 1-4 of 10 Enter Install Esc Back o Change === plan-games 40x15 RetroBIOS: RetroArch @@ -1259,6 +1259,7 @@ 4 files to download, 1.0 MB BIOS folder: ~/.config/retroarch/system + > Install For the games on this card: yes 412 Only what starts: no @@ -1266,8 +1267,7 @@ Choose systems Copy from an old card or a folder Details - Change - Quit + 1-7 of 10 Enter Install Esc Back o Change === plan-games 80x24 RetroBIOS: RetroArch @@ -1284,6 +1284,7 @@ Copy the BIOS files from an old card or a folder Details Change + More Quit @@ -1292,7 +1293,6 @@ - Enter Install Esc Back o Change ? Help === games 40x12 RetroBIOS: Games on this card @@ -1517,7 +1517,7 @@ Backups Put back a backup Delete a backup - + Make a pack @@ -1530,7 +1530,7 @@ Backups Put back a backup Delete a backup - + Make a pack @@ -1546,7 +1546,7 @@ Backups Put back a backup Delete a backup - + Make a pack @@ -1834,3 +1834,165 @@ Enter Choose Esc Back ? Help +=== pack-plan 40x12 + RetroBIOS: Make a pack + + 4 files, 1.0 MB, for RetroArch. + Pack: ~/Downloads/ + RetroArch_Custom_BIOS_Pack.zip + One ZIP, installed with --from-pack. + + > Make the pack + Change where + + + Enter Make Esc Back ? Help +=== pack-plan 40x15 + RetroBIOS: Make a pack + + 4 files, 1.0 MB, for RetroArch. + Pack: ~/Downloads/ + RetroArch_Custom_BIOS_Pack.zip + One ZIP, installed with --from-pack. + + > Make the pack + Change where + + + + + + Enter Make Esc Back ? Help +=== pack-plan 80x24 + RetroBIOS: Make a pack + + 4 files, 1.0 MB, for RetroArch. + Pack: ~/Downloads/RetroArch_Custom_BIOS_Pack.zip + One ZIP, installed with --from-pack. + + > Make the pack + Change where + + + + + + + + + + + + + + + + Enter Make Esc Back ? Help +=== pack-plan-parts 40x12 + RetroBIOS: Make a pack + + 4 files, 1.0 MB, for RetroArch. + Pack: ~/Downloads/ + RetroArch_Custom_BIOS_Pack.part1of3. + zip + In 3 parts of at most 3.9 GB, as FAT32 + holds no file of 4 GB. + + > Make the pack + Change where + Enter Make Esc Back ? Help +=== pack-plan-parts 40x15 + RetroBIOS: Make a pack + + 4 files, 1.0 MB, for RetroArch. + Pack: ~/Downloads/ + RetroArch_Custom_BIOS_Pack.part1of3. + zip + In 3 parts of at most 3.9 GB, as FAT32 + holds no file of 4 GB. + + > Make the pack + Change where + + + + Enter Make Esc Back ? Help +=== pack-plan-parts 80x24 + RetroBIOS: Make a pack + + 4 files, 1.0 MB, for RetroArch. + Pack: ~/Downloads/RetroArch_Custom_BIOS_Pack.part1of3.zip + In 3 parts of at most 3.9 GB, as FAT32 holds no file of 4 GB. + + > Make the pack + Change where + + + + + + + + + + + + + + + + Enter Make Esc Back ? Help +=== pack-done 40x12 + RetroBIOS: Done + + Pack made: 4 files, 1023.4 KB, in 3 + parts. + Pack: ~/Downloads/ + RetroArch_Custom_BIOS_Pack.part1of3. + zip + On the other device, install from it + with --from-pack. + + > Close + Enter Close Esc Back ? Help +=== pack-done 40x15 + RetroBIOS: Done + + Pack made: 4 files, 1023.4 KB, in 3 + parts. + Pack: ~/Downloads/ + RetroArch_Custom_BIOS_Pack.part1of3. + zip + On the other device, install from it + with --from-pack. + + > Close + + + + Enter Close Esc Back ? Help +=== pack-done 80x24 + RetroBIOS: Done + + Pack made: 4 files, 1023.4 KB, in 3 parts. + Pack: ~/Downloads/RetroArch_Custom_BIOS_Pack.part1of3.zip + On the other device, install from it with --from-pack. + + > Close + + + + + + + + + + + + + + + + + Enter Close Esc Back ? Help diff --git a/tests/fixtures/tui/route-miyoo.txt b/tests/fixtures/tui/route-miyoo.txt index 6c7977088..e834baddb 100644 --- a/tests/fixtures/tui/route-miyoo.txt +++ b/tests/fixtures/tui/route-miyoo.txt @@ -436,12 +436,12 @@ 4 files to download, 1.0 MB BIOS folder: ~/.config/retroarch/system + > Install Choose systems Copy from an old card or a folder Details - Change - Quit + 1-4 of 7 A Install R2 Back L2 Change === plan 40x15 RetroBIOS: RetroArch @@ -455,9 +455,9 @@ Copy from an old card or a folder Details Change + More Quit - A Install R2 Back L2 Change === plan 80x24 RetroBIOS: RetroArch @@ -470,6 +470,7 @@ Copy the BIOS files from an old card or a folder Details Change + More Quit @@ -482,7 +483,6 @@ - A Install R2 Back L2 Change === plan-in-place 40x12 RetroBIOS: RetroArch @@ -494,7 +494,7 @@ > Close Details Change - + More A Close R2 Back L2 Change === plan-in-place 40x15 @@ -507,7 +507,7 @@ > Close Details Change - + More @@ -522,7 +522,7 @@ > Close Details Change - + More @@ -1247,7 +1247,7 @@ For the games on this card: yes 412 Only what starts: no Show the games - 1-4 of 9 + 1-4 of 10 A Install R2 Back L2 Change === plan-games 40x15 RetroBIOS: RetroArch @@ -1255,6 +1255,7 @@ 4 files to download, 1.0 MB BIOS folder: ~/.config/retroarch/system + > Install For the games on this card: yes 412 Only what starts: no @@ -1262,8 +1263,7 @@ Choose systems Copy from an old card or a folder Details - Change - Quit + 1-7 of 10 A Install R2 Back L2 Change === plan-games 80x24 RetroBIOS: RetroArch @@ -1280,6 +1280,7 @@ Copy the BIOS files from an old card or a folder Details Change + More Quit @@ -1288,7 +1289,6 @@ - A Install R2 Back L2 Change === games 80x24 RetroBIOS: Games on this card @@ -1455,7 +1455,7 @@ Backups Put back a backup Delete a backup - + Make a pack @@ -1468,7 +1468,7 @@ Backups Put back a backup Delete a backup - + Make a pack @@ -1484,7 +1484,7 @@ Backups Put back a backup Delete a backup - + Make a pack @@ -1772,3 +1772,165 @@ A Choose R2 Back +=== pack-plan 40x12 + RetroBIOS: Make a pack + + 4 files, 1.0 MB, for RetroArch. + Pack: ~/Downloads/ + RetroArch_Custom_BIOS_Pack.zip + One ZIP, installed with --from-pack. + + > Make the pack + Change where + + + A Make R2 Back +=== pack-plan 40x15 + RetroBIOS: Make a pack + + 4 files, 1.0 MB, for RetroArch. + Pack: ~/Downloads/ + RetroArch_Custom_BIOS_Pack.zip + One ZIP, installed with --from-pack. + + > Make the pack + Change where + + + + + + A Make R2 Back +=== pack-plan 80x24 + RetroBIOS: Make a pack + + 4 files, 1.0 MB, for RetroArch. + Pack: ~/Downloads/RetroArch_Custom_BIOS_Pack.zip + One ZIP, installed with --from-pack. + + > Make the pack + Change where + + + + + + + + + + + + + + + + A Make R2 Back +=== pack-plan-parts 40x12 + RetroBIOS: Make a pack + + 4 files, 1.0 MB, for RetroArch. + Pack: ~/Downloads/ + RetroArch_Custom_BIOS_Pack.part1of3. + zip + In 3 parts of at most 3.9 GB, as FAT32 + holds no file of 4 GB. + + > Make the pack + Change where + A Make R2 Back +=== pack-plan-parts 40x15 + RetroBIOS: Make a pack + + 4 files, 1.0 MB, for RetroArch. + Pack: ~/Downloads/ + RetroArch_Custom_BIOS_Pack.part1of3. + zip + In 3 parts of at most 3.9 GB, as FAT32 + holds no file of 4 GB. + + > Make the pack + Change where + + + + A Make R2 Back +=== pack-plan-parts 80x24 + RetroBIOS: Make a pack + + 4 files, 1.0 MB, for RetroArch. + Pack: ~/Downloads/RetroArch_Custom_BIOS_Pack.part1of3.zip + In 3 parts of at most 3.9 GB, as FAT32 holds no file of 4 GB. + + > Make the pack + Change where + + + + + + + + + + + + + + + + A Make R2 Back +=== pack-done 40x12 + RetroBIOS: Done + + Pack made: 4 files, 1023.4 KB, in 3 + parts. + Pack: ~/Downloads/ + RetroArch_Custom_BIOS_Pack.part1of3. + zip + On the other device, install from it + with --from-pack. + + > Close + A Close R2 Back +=== pack-done 40x15 + RetroBIOS: Done + + Pack made: 4 files, 1023.4 KB, in 3 + parts. + Pack: ~/Downloads/ + RetroArch_Custom_BIOS_Pack.part1of3. + zip + On the other device, install from it + with --from-pack. + + > Close + + + + A Close R2 Back +=== pack-done 80x24 + RetroBIOS: Done + + Pack made: 4 files, 1023.4 KB, in 3 parts. + Pack: ~/Downloads/RetroArch_Custom_BIOS_Pack.part1of3.zip + On the other device, install from it with --from-pack. + + > Close + + + + + + + + + + + + + + + + + A Close R2 Back diff --git a/tests/fixtures/tui/route-muxterm.txt b/tests/fixtures/tui/route-muxterm.txt index 9e9cf8ab4..0a532753b 100644 --- a/tests/fixtures/tui/route-muxterm.txt +++ b/tests/fixtures/tui/route-muxterm.txt @@ -436,12 +436,12 @@ 4 files to download, 1.0 MB BIOS folder: ~/.config/retroarch/system + > Install Choose systems Copy from an old card or a folder Details - Change - Quit + 1-4 of 7 Start Install B Back === plan 40x15 RetroBIOS: RetroArch @@ -455,9 +455,9 @@ Copy from an old card or a folder Details Change + More Quit - Start Install B Back === plan 80x24 RetroBIOS: RetroArch @@ -470,6 +470,7 @@ Copy the BIOS files from an old card or a folder Details Change + More Quit @@ -482,7 +483,6 @@ - Start Install B Back === plan-in-place 40x12 RetroBIOS: RetroArch @@ -494,7 +494,7 @@ > Close Details Change - + More Start Close B Back === plan-in-place 40x15 @@ -507,7 +507,7 @@ > Close Details Change - + More @@ -522,7 +522,7 @@ > Close Details Change - + More @@ -1305,7 +1305,7 @@ For the games on this card: yes 412 Only what starts: no Show the games - 1-4 of 9 + 1-4 of 10 Start Install B Back === plan-games 40x15 RetroBIOS: RetroArch @@ -1313,6 +1313,7 @@ 4 files to download, 1.0 MB BIOS folder: ~/.config/retroarch/system + > Install For the games on this card: yes 412 Only what starts: no @@ -1320,8 +1321,7 @@ Choose systems Copy from an old card or a folder Details - Change - Quit + 1-7 of 10 Start Install B Back === plan-games 80x24 RetroBIOS: RetroArch @@ -1338,6 +1338,7 @@ Copy the BIOS files from an old card or a folder Details Change + More Quit @@ -1346,7 +1347,6 @@ - Start Install B Back === games 40x12 RetroBIOS: Games on this card @@ -1571,7 +1571,7 @@ Backups Put back a backup Delete a backup - + Make a pack @@ -1584,7 +1584,7 @@ Backups Put back a backup Delete a backup - + Make a pack @@ -1600,7 +1600,7 @@ Backups Put back a backup Delete a backup - + Make a pack @@ -1888,3 +1888,165 @@ Start Choose B Back +=== pack-plan 40x12 + RetroBIOS: Make a pack + + 4 files, 1.0 MB, for RetroArch. + Pack: ~/Downloads/ + RetroArch_Custom_BIOS_Pack.zip + One ZIP, installed with --from-pack. + + > Make the pack + Change where + + + Start Make B Back +=== pack-plan 40x15 + RetroBIOS: Make a pack + + 4 files, 1.0 MB, for RetroArch. + Pack: ~/Downloads/ + RetroArch_Custom_BIOS_Pack.zip + One ZIP, installed with --from-pack. + + > Make the pack + Change where + + + + + + Start Make B Back +=== pack-plan 80x24 + RetroBIOS: Make a pack + + 4 files, 1.0 MB, for RetroArch. + Pack: ~/Downloads/RetroArch_Custom_BIOS_Pack.zip + One ZIP, installed with --from-pack. + + > Make the pack + Change where + + + + + + + + + + + + + + + + Start Make B Back +=== pack-plan-parts 40x12 + RetroBIOS: Make a pack + + 4 files, 1.0 MB, for RetroArch. + Pack: ~/Downloads/ + RetroArch_Custom_BIOS_Pack.part1of3. + zip + In 3 parts of at most 3.9 GB, as FAT32 + holds no file of 4 GB. + + > Make the pack + Change where + Start Make B Back +=== pack-plan-parts 40x15 + RetroBIOS: Make a pack + + 4 files, 1.0 MB, for RetroArch. + Pack: ~/Downloads/ + RetroArch_Custom_BIOS_Pack.part1of3. + zip + In 3 parts of at most 3.9 GB, as FAT32 + holds no file of 4 GB. + + > Make the pack + Change where + + + + Start Make B Back +=== pack-plan-parts 80x24 + RetroBIOS: Make a pack + + 4 files, 1.0 MB, for RetroArch. + Pack: ~/Downloads/RetroArch_Custom_BIOS_Pack.part1of3.zip + In 3 parts of at most 3.9 GB, as FAT32 holds no file of 4 GB. + + > Make the pack + Change where + + + + + + + + + + + + + + + + Start Make B Back +=== pack-done 40x12 + RetroBIOS: Done + + Pack made: 4 files, 1023.4 KB, in 3 + parts. + Pack: ~/Downloads/ + RetroArch_Custom_BIOS_Pack.part1of3. + zip + On the other device, install from it + with --from-pack. + + > Close + Start Close B Back +=== pack-done 40x15 + RetroBIOS: Done + + Pack made: 4 files, 1023.4 KB, in 3 + parts. + Pack: ~/Downloads/ + RetroArch_Custom_BIOS_Pack.part1of3. + zip + On the other device, install from it + with --from-pack. + + > Close + + + + Start Close B Back +=== pack-done 80x24 + RetroBIOS: Done + + Pack made: 4 files, 1023.4 KB, in 3 parts. + Pack: ~/Downloads/RetroArch_Custom_BIOS_Pack.part1of3.zip + On the other device, install from it with --from-pack. + + > Close + + + + + + + + + + + + + + + + + Start Close B Back diff --git a/tests/test_install_pack.py b/tests/test_install_pack.py new file mode 100644 index 000000000..7d410551c --- /dev/null +++ b/tests/test_install_pack.py @@ -0,0 +1,455 @@ +"""--pack: the choice downloaded into a pack ZIP for another device. + +The pack is read back by --from-pack, offline, and must install exactly +what a direct install of the same choice installs. Parts are each a whole +ZIP. Every member is checked against its SHA-1 before the ZIP is closed, +and a failure leaves no file behind. +""" + +from __future__ import annotations + +import tests # noqa: F401 offline, scratch under tmp/, the suite's own cache + +import functools +import hashlib +import http.server +import importlib.util +import io +import json +import os +import shutil +import socket +import subprocess +import sys +import tempfile +import threading +import unittest +import zipfile +from pathlib import Path +from unittest import mock + +REPO_ROOT = Path(__file__).resolve().parent.parent + +_spec = importlib.util.spec_from_file_location("install", REPO_ROOT / "install.py") +install = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(install) + + +def _sha1(data: bytes) -> str: + return hashlib.sha1(data).hexdigest() + + +def _noise(seed: str, size: int) -> bytes: + """Bytes deflate cannot shrink.""" + return b"".join(hashlib.sha256(f"{seed}{n}".encode()).digest() + for n in range(size // 32)) + + +# dest: (bytes, systems, regions, cores). Two dests share one file: the +# pack stores it once. +PAYLOADS = { + "scph5500.bin": (b"jp bios " * 64, ["sony-playstation"], ["japan"], None), + "scph5501.bin": (b"us bios " * 64, ["sony-playstation"], ["north-america"], None), + "gba_bios.bin": (b"gba bios" * 32, ["nintendo-gba"], None, None), + "pcsx/extra.bin": (b"pcsx extra", ["sony-playstation"], None, ["pcsx_rearmed"]), + "mgba/gba_bios.bin": (b"gba bios" * 32, ["nintendo-gba"], None, ["mgba"]), +} +TREE = {"Sys/GC/font.bin": b"font bytes", "Sys/Wii/setting.txt": b"setting"} +# Files too large for one part of MIN_PART_BYTES together. +BIG = {f"arcade/set{n}.zip": (_noise(str(n), 24 * 1024), ["arcade"], None, None) + for n in range(5)} + + +class _Quiet(http.server.SimpleHTTPRequestHandler): + def log_message(self, format, *args): # noqa: A002 - stdlib signature + return + + +def _closed_port() -> int: + with socket.socket() as sock: + sock.bind(("127.0.0.1", 0)) + return sock.getsockname()[1] + + +class Repository(unittest.TestCase): + """A loopback copy of the repository: a RetroArch list, its files and a + data tree's archive.""" + + payloads = PAYLOADS + tree = TREE + + def setUp(self): + scratch = REPO_ROOT / "tmp" + scratch.mkdir(exist_ok=True) + self.root = Path(tempfile.mkdtemp(dir=scratch)) + self.addCleanup(shutil.rmtree, self.root, True) + self.served = self.root / "served" + (self.served / "install").mkdir(parents=True) + (self.served / "bios").mkdir() + handler = functools.partial(_Quiet, directory=str(self.served)) + self.httpd = http.server.ThreadingHTTPServer(("127.0.0.1", 0), handler) + threading.Thread(target=self.httpd.serve_forever, daemon=True).start() + self.addCleanup(self.httpd.server_close) + self.addCleanup(self.httpd.shutdown) + self.base = f"http://127.0.0.1:{self.httpd.server_address[1]}" + self.out = self.root / "out" + self.out.mkdir() + self.write_list() + + def write_list(self) -> None: + files = [] + for dest, (payload, systems, regions, cores) in self.payloads.items(): + stored = dest.replace("/", "_") + (self.served / "bios" / stored).write_bytes(payload) + entry = {"dest": dest, "sha1": _sha1(payload), "size": len(payload), + "repo_path": f"bios/{stored}", "cores": cores, "systems": systems} + if regions: + entry.update(regions=regions, region_system_groups=systems) + files.append(entry) + listed: dict = {"manifest_version": 2, "platform": "retroarch", "files": files, + "system_cores": {"sony-playstation": ["pcsx_rearmed"], + "nintendo-gba": ["mgba"], "arcade": ["fbneo"]}} + if self.tree: + with zipfile.ZipFile(self.served / "tree.zip", "w") as archive: + for rel, data in self.tree.items(): + archive.writestr(rel, data) + listed["data_directories"] = [{ + "ref": "dolphin-sys", "dest": "dolphin-emu", "type": "zip", + "url": f"{self.base}/tree.zip", "systems": ["nintendo-gba"], + "files": {rel: {"sha1": _sha1(data), "size": len(data)} + for rel, data in self.tree.items()}}] + (self.served / "install" / "retroarch.json").write_text(json.dumps(listed)) + + def env(self, offline: bool = False) -> dict: + env = dict(os.environ) + env.pop(install.OFFLINE_VARIABLE, None) + env["RETROBIOS_BASE_URL"] = self.base + if offline: + env["RETROBIOS_BASE_URL"] = f"http://127.0.0.1:{_closed_port()}" + env["HTTPS_PROXY"] = env["HTTP_PROXY"] = f"http://127.0.0.1:{_closed_port()}" + env[install.OFFLINE_VARIABLE] = "1" + return env + + def run_installer(self, *options: str, offline: bool = False, + code: str | None = None) -> subprocess.CompletedProcess: + start = ([sys.executable, "-c", code] if code is not None + else [sys.executable, str(REPO_ROOT / "install.py")]) + return subprocess.run( + [*start, "--platform", "retroarch", *options], env=self.env(offline), + capture_output=True, text=True, timeout=120, check=False, + stdin=subprocess.DEVNULL, cwd=str(self.root)) + + def make(self, *options: str, into: Path | None = None) -> subprocess.CompletedProcess: + proc = self.run_installer("--pack", f"{into or self.out}{os.sep}", *options) + return proc + + def installed(self, folder: Path) -> set[tuple[str, str]]: + """(path, sha1) of every file below folder, the record and backups + the installer keeps beside its files left out.""" + return {(path.relative_to(folder).as_posix(), _sha1(path.read_bytes())) + for path in folder.rglob("*") + if path.is_file() and not any("retrobios" in part.lower() + for part in path.relative_to(folder).parts)} + + def direct(self, folder: Path, *options: str) -> set[tuple[str, str]]: + proc = self.run_installer("--dest", str(folder), "--yes", *options) + self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr) + return self.installed(folder) + + def from_pack(self, pack: Path, folder: Path, *options: str) -> set[tuple[str, str]]: + proc = self.run_installer("--dest", str(folder), "--from-pack", str(pack), "--yes", + *options, offline=True) + self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr) + return self.installed(folder) + + def packs(self, folder: Path | None = None) -> list[Path]: + return sorted((folder or self.out).iterdir()) + + +class APackInstallsWhatADirectInstallDoes(Repository): + def test_the_whole_list(self): + expected = self.direct(self.root / "direct") + self.assertIn(("dolphin-emu/Sys/GC/font.bin", _sha1(TREE["Sys/GC/font.bin"])), + expected) + proc = self.make() + self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr) + self.assertEqual([path.name for path in self.packs()], ["RetroArch_BIOS_Pack.zip"]) + self.assertIn("Pack made: 6 files", proc.stdout) + self.assertEqual(self.from_pack(self.packs()[0], self.root / "other"), expected) + + def test_a_narrowed_choice(self): + options = ("--system", "sony-playstation", "--region", "us") + expected = self.direct(self.root / "direct", *options) + self.assertNotIn("gba_bios.bin", {path for path, _sha1 in expected}) + proc = self.make(*options) + self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr) + pack = self.out / "RetroArch_Custom_BIOS_Pack.zip" + self.assertEqual(self.packs(), [pack]) + # The pack carries the choice: no option is needed on the other + # device, and the same options give the same files. + self.assertEqual(self.from_pack(pack, self.root / "plain"), expected) + self.assertEqual(self.from_pack(pack, self.root / "again", *options), expected) + + def test_a_file_two_dests_share_is_stored_once(self): + self.assertEqual(self.make().returncode, 0) + with zipfile.ZipFile(self.packs()[0]) as archive: + names = archive.namelist() + listed = json.loads(archive.read("manifest.json")) + self.assertEqual(names[0], "manifest.json") + self.assertIn("gba_bios.bin", names) + self.assertNotIn("mgba/gba_bios.bin", names) + self.assertEqual(listed["platform"], "retroarch") + self.assertEqual(sorted(entry["dest"] for entry in listed["install_list"]["files"]), + sorted(PAYLOADS)) + self.assertEqual([entry["ref"] for entry in + listed["install_list"]["data_directories"]], ["dolphin-sys"]) + + def test_a_pack_made_from_a_pack(self): + """No network is needed to make a pack of part of a pack.""" + self.assertEqual(self.make().returncode, 0) + whole = self.packs()[0] + smaller = self.root / "smaller" + smaller.mkdir() + proc = self.run_installer("--from-pack", str(whole), "--pack", f"{smaller}{os.sep}", + "--system", "nintendo-gba", offline=True) + self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr) + expected = self.direct(self.root / "direct", "--system", "nintendo-gba") + self.assertEqual(self.from_pack(self.packs(smaller)[0], self.root / "other"), + expected) + + def test_a_dry_run_lists_and_writes_nothing(self): + proc = self.make("--dry-run", "--verbose") + self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr) + self.assertIn("Pack for RetroArch: 6 files", proc.stdout) + self.assertIn("dolphin-emu/Sys/GC/font.bin", proc.stdout) + self.assertEqual(self.packs(), []) + + +class APackIsDeterministic(Repository): + def test_the_same_choice_gives_the_same_bytes(self): + again = self.root / "again" + again.mkdir() + self.assertEqual(self.make().returncode, 0) + self.assertEqual(self.make(into=again).returncode, 0) + first, second = self.packs()[0], self.packs(again)[0] + self.assertEqual(first.read_bytes(), second.read_bytes()) + with zipfile.ZipFile(first) as archive: + infos = archive.infolist() + self.assertEqual({info.date_time for info in infos}, {(1980, 1, 1, 0, 0, 0)}) + self.assertEqual({info.external_attr for info in infos}, {0o100644 << 16}) + names = [info.filename for info in infos] + self.assertEqual(names[1:], sorted(names[1:])) + + +class Parts(Repository): + payloads = {**PAYLOADS, **BIG} + + def test_each_part_is_a_whole_zip_and_their_union_is_the_pack(self): + whole_dir = self.root / "whole" + whole_dir.mkdir() + self.assertEqual(self.make(into=whole_dir).returncode, 0) + with zipfile.ZipFile(self.packs(whole_dir)[0]) as archive: + whole = {info.filename: archive.read(info) for info in archive.infolist()} + proc = self.make("--split", "64K") + self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr) + parts = self.packs() + self.assertGreater(len(parts), 1) + count = len(parts) + self.assertEqual([part.name for part in parts], + [f"RetroArch_BIOS_Pack.part{n}of{count}.zip" + for n in range(1, count + 1)]) + self.assertIn(f"In {count} parts of at most 64.0 KB.", proc.stdout) + union: dict[str, bytes] = {} + markers = self.root / "markers" + markers.mkdir() + for index, part in enumerate(parts, 1): + self.assertLess(part.stat().st_size, 64 * 1024) + with zipfile.ZipFile(part) as archive: + self.assertIsNone(archive.testzip()) + for info in archive.infolist(): + data = archive.read(info) + if install._PART_MARKER.match(info.filename): + (markers / info.filename).write_bytes(data) + continue + self.assertNotIn(info.filename, union) + union[info.filename] = data + marker = install.read_part_marker( + markers / f"RetroArch_BIOS_Pack.part{index}of{count}.txt") + self.assertIsNotNone(marker) + self.assertEqual(marker.parts, tuple((p.name, p.stat().st_size) for p in parts)) + self.assertEqual(union, whole) + expected = self.direct(self.root / "direct") + self.assertEqual(self.from_pack(parts[1], self.root / "other"), expected) + + def test_a_pack_under_the_size_stays_one_zip(self): + proc = self.make("--split", "100M") + self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr) + self.assertEqual([path.name for path in self.packs()], ["RetroArch_BIOS_Pack.zip"]) + + def test_a_pack_made_again_in_parts_replaces_the_whole_one(self): + self.assertEqual(self.make().returncode, 0) + self.assertEqual(self.make("--split", "64K").returncode, 0) + self.assertTrue(all(".part" in path.name for path in self.packs())) + + def test_a_file_larger_than_a_part_is_refused_before_any_download(self): + self.payloads = {"big.bin": (_noise("x", 80 * 1024), ["arcade"], None, None)} + self.write_list() + proc = self.make("--split", "64K") + self.assertEqual(proc.returncode, 2, proc.stdout + proc.stderr) + self.assertIn("big.bin (80.0 KB) does not fit in a part of 64.0 KB", proc.stderr) + self.assertEqual(self.packs(), []) + + +# The installer run in a child with FAT32 said of every drive and its +# limit made small: a real 4 GiB pack is out of reach of a test. +FAT_CHILD = """ +import importlib.util, sys +spec = importlib.util.spec_from_file_location("install", {script!r}) +install = importlib.util.module_from_spec(spec) +spec.loader.exec_module(install) +install.fat32_drive = lambda folder: {fat} +install.FAT_FILE_LIMIT = 100 * 1024 +install.FAT_PART_BYTES = 80 * 1024 +sys.argv = ["install.py", *sys.argv[1:]] +install.main() +""" + + +class Fat32(Repository): + payloads = {**PAYLOADS, **BIG} + + def child(self, fat: bool) -> str: + return FAT_CHILD.format(script=str(REPO_ROOT / "install.py"), fat=fat) + + def test_a_pack_past_the_limit_is_split_by_itself(self): + proc = self.run_installer("--pack", f"{self.out}{os.sep}", code=self.child(True)) + self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr) + parts = self.packs() + self.assertEqual(len(parts), 2) + self.assertIn("In 2 parts of at most 80.0 KB, as FAT32 holds no file of 4 GB.", + proc.stdout) + self.assertTrue(all(part.stat().st_size < 80 * 1024 for part in parts)) + + def test_another_drive_keeps_one_zip(self): + proc = self.run_installer("--pack", f"{self.out}{os.sep}", code=self.child(False)) + self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr) + self.assertEqual([path.name for path in self.packs()], ["RetroArch_BIOS_Pack.zip"]) + self.assertNotIn("FAT32", proc.stdout) + + def test_the_mount_table_names_the_drive(self): + table = ("22 1 8:1 / / rw - ext4 /dev/sda1 rw\n" + "36 22 179:1 / /media/me/SD\\040CARD rw,nosuid - vfat /dev/mmcblk0p1 rw\n" + "37 36 179:2 / /media/me/SD\\040CARD/inner rw - exfat /dev/mmcblk0p2 rw\n") + mounts = install.mountinfo_types(table) + self.assertEqual(mounts[1], ("/media/me/SD CARD", "vfat")) + self.assertTrue(install.fat_mounted(Path("/media/me/SD CARD/packs"), mounts)) + self.assertFalse(install.fat_mounted(Path("/media/me/SD CARD/inner/x"), mounts)) + self.assertFalse(install.fat_mounted(Path("/home/me"), mounts)) + listing = "/dev/disk4s1 on /Volumes/CARD (msdos, local, nodev, nosuid)\n" + self.assertTrue(install.fat_mounted(Path("/Volumes/CARD/x"), + install.mount_list_types(listing))) + + +class AFailureLeavesNothing(Repository): + def test_a_download_that_fails_leaves_no_file(self): + (self.served / "bios" / "scph5501.bin").write_bytes(b"changed on the server") + proc = self.make() + self.assertEqual(proc.returncode, 1, proc.stdout + proc.stderr) + self.assertIn("could not be had: no pack was written", proc.stderr) + self.assertEqual(self.packs(), []) + + def test_an_earlier_pack_of_the_name_stays_as_it_was(self): + self.assertEqual(self.make().returncode, 0) + before = self.packs()[0].read_bytes() + (self.served / "bios" / "gba_bios.bin").unlink() + proc = self.make() + self.assertEqual(proc.returncode, 1, proc.stdout + proc.stderr) + self.assertEqual([path.name for path in self.packs()], ["RetroArch_BIOS_Pack.zip"]) + self.assertEqual(self.packs()[0].read_bytes(), before) + + def test_a_member_whose_bytes_changed_is_refused_before_the_zip_closes(self): + source = self.root / "staged.bin" + source.write_bytes(b"other bytes") + member = install.PackMember("a.bin", _sha1(b"listed bytes"), 11, source) + with self.assertRaises(install.PackError): + install.write_pack(self.out / "RetroArch_BIOS_Pack.zip", b"{}", [member], None) + self.assertEqual(self.packs(), []) + + +class Events(Repository): + def events(self, *options: str) -> tuple[list[dict], int]: + proc = self.make("--events", *options) + return [json.loads(line) for line in proc.stdout.splitlines()], proc.returncode + + def test_the_pack_event(self): + events, code = self.events("--dry-run") + self.assertEqual(code, 0) + self.assertEqual(events[0]["mode"], "pack") + pack = next(event for event in events if event["event"] == "pack") + self.assertEqual(list(pack)[1:], list(install.EVENT_KEYS["pack"])) + self.assertEqual(pack["status"], "planned") + self.assertEqual(pack["files"], 6) + self.assertEqual(pack["size"], 0) + self.assertEqual(self.packs(), []) + events, code = self.events() + self.assertEqual(code, 0) + pack = next(event for event in events if event["event"] == "pack") + self.assertEqual(pack["status"], "written") + self.assertEqual(pack["parts"], [str(self.out / "RetroArch_BIOS_Pack.zip")]) + self.assertEqual(pack["size"], self.packs()[0].stat().st_size) + self.assertEqual(events[-1], {"event": "end", "code": 0}) + + def test_a_failure_is_an_event(self): + (self.served / "bios" / "scph5500.bin").unlink() + events, code = self.events() + self.assertEqual(code, 1) + pack = next(event for event in events if event["event"] == "pack") + self.assertEqual((pack["status"], pack["parts"]), ("failed", [])) + self.assertEqual(events[-1], {"event": "end", "code": 1}) + + +class Refusals(Repository): + def test_options_of_this_machine_s_folder_are_refused(self): + for options in (("--check",), ("--dest", str(self.root / "x")), + ("--installed-cores",), ("--for-games",), ("--list-systems",)): + with self.subTest(options=options): + proc = self.make(*options) + self.assertEqual(proc.returncode, 2, proc.stderr) + self.assertIn("install.py: error:", proc.stderr) + + def test_split_needs_pack_and_a_size(self): + proc = self.run_installer("--split", "1G") + self.assertEqual(proc.returncode, 2) + self.assertIn("--split applies to --pack", proc.stderr) + proc = self.make("--split", "1K") + self.assertEqual(proc.returncode, 2) + self.assertIn("too small", proc.stderr) + + def test_a_name_the_reader_would_not_find_is_refused(self): + proc = self.run_installer("--pack", str(self.out / "mine.zip")) + self.assertEqual(proc.returncode, 2) + self.assertIn("_BIOS_Pack.zip", proc.stderr) + + def test_a_pack_named_by_the_user_reads_its_platform_inside(self): + named = self.out / "Living_Room_BIOS_Pack.zip" + proc = self.run_installer("--pack", str(named)) + self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr) + pack = install.PackSource([named]) + self.addCleanup(pack.close) + self.assertEqual(pack.platforms(), ["retroarch"]) + + +class PartSizes(unittest.TestCase): + def test_a_size_reads_as_bytes_or_with_its_unit(self): + self.assertEqual(install.parse_part_size("1900M"), 1900 * 1024 ** 2) + self.assertEqual(install.parse_part_size("4g"), 4 * 1024 ** 3) + self.assertEqual(install.parse_part_size("70000"), 70000) + for text in ("big", "1K", "-5M"): + with self.subTest(text=text), \ + mock.patch("sys.stderr", io.StringIO()), \ + self.assertRaises(Exception): + install.parse_part_size(text) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_install_tui.py b/tests/test_install_tui.py index 0c99e2528..de37081ec 100644 --- a/tests/test_install_tui.py +++ b/tests/test_install_tui.py @@ -1070,6 +1070,9 @@ def golden_states() -> dict: install.tui_update(states["removal-confirm"], Key("enter")) states["removal-done"] = removal_done_state() states["backups"] = backups_state() + states["pack-plan"] = pack_plan_state() + states["pack-plan-parts"] = pack_plan_state(parts=3) + states["pack-done"] = pack_done_state() return states @@ -1140,6 +1143,51 @@ def backups_state(purpose: str = "backups") -> install.TuiState: return state +PACK_PATH = HOME / "Downloads" / "RetroArch_Custom_BIOS_Pack.zip" + + +def pack_event(status: str, parts: int = 1, size: int = 0) -> dict: + """The pack event of a dry run (planned) or a run (written), the pack + whole or in parts on a FAT32 card.""" + names = ([PACK_PATH] if parts == 1 else + [PACK_PATH.with_name(f"RetroArch_Custom_BIOS_Pack.part{n}of{parts}.zip") + for n in range(1, parts + 1)]) + message = ("One ZIP." if parts == 1 else + f"In {parts} parts of at most 3.9 GB, as FAT32 holds no file of 4 GB.") + return {"event": "pack", "platform": "retroarch", "path": str(PACK_PATH), "files": 4, + "bytes": 1049604, "size": size, "parts": [str(name) for name in names], + "status": status, "message": message} + + +def pack_plan_state(parts: int = 1) -> install.TuiState: + """More, Make a pack, its dry run read.""" + state = checked_state() + rows = install.tui_rows(state) + state.focus["plan"] = [row.action for row in rows].index("more") + assert install.tui_update(state, Key("enter")) == [] + rows = install.tui_rows(state) + state.focus["more"] = [row.action for row in rows].index("packmake") + effects = install.tui_update(state, Key("enter")) + assert effects == [("run", "pack_plan")], effects + install.tui_receive(state, ("event", state.run_id, pack_event("planned", parts))) + install.tui_receive(state, ("ended", state.run_id, 0, [])) + return state + + +def pack_done_state() -> install.TuiState: + """The pack made, in three parts on a FAT32 card.""" + state = pack_plan_state(parts=3) + effects = install.tui_update(state, Key("enter")) + assert effects == [("run", "pack")], effects + install.tui_receive(state, ("event", state.run_id, { + "event": "progress", "files_done": 4, "files_total": 4, "bytes_done": 1049604, + "bytes_total": 1049604})) + install.tui_receive(state, ("event", state.run_id, + pack_event("written", 3, size=1048000))) + install.tui_receive(state, ("ended", state.run_id, 0, [])) + return state + + # A board list as install/targets/ publishes it, read by Device: the boards # by the names the list gives them, the device images each one runs. TARGETS = {"bcm2711": {"cores": ["pcsx_rearmed"], "images": ["rpi4"]}, @@ -15246,12 +15294,12 @@ class GamesEndToEnd(unittest.TestCase): SCREEN_WORDS = { "setup": (29, 36, 34, 34), "platforms": (23, 27, 89, 225), "folder": (27, 27, 25, 25), "folder-card": (52, 52, 50, 50), "browse": (17, 17, 15, 15), "path": (23, 23, 25, 25), - "create": (23, 23, 21, 21), "checking": (18, 18, 17, 17), "plan": (31, 31, 31, 31), - "plan-in-place": (22, 22, 19, 19), "systems": (36, 37, 36, 36), + "create": (23, 23, 21, 21), "checking": (18, 18, 17, 17), "plan": (32, 32, 32, 32), + "plan-in-place": (23, 23, 20, 20), "systems": (36, 37, 36, 36), "regions": (45, 44, 42, 42), "cores": (47, 47, 45, 45), "preview": (29, 29, 28, 28), "command": (22, 22, 16, 16), "confirm": (22, 22, 20, 20), "installing": (32, 32, 31, 31), "result": (33, 33, 31, 31), "error": (37, 34, 32, 31), - "quit": (14, 14, 12, 12), "help": (24, 26, 26, 26), "plan-games": (36, 46, 54, 54), + "quit": (14, 14, 12, 12), "help": (24, 26, 26, 26), "plan-games": (36, 47, 55, 55), "games": (36, 45, 44, 44), "plan-details": (30, 30, 29, 29), "result-details": (30, 30, 19, 19), # The plan's words, plus the recorded choice by name, its row (the one @@ -15266,14 +15314,18 @@ SCREEN_WORDS = { # A list of boards and one of emulators, each with the line that says # what the choice does and the gloss of "board". "device": (35, 35, 33, 33), "emulators": (29, 29, 27, 27), - # A plan names More (one word) where the folder has a record or a - # backup (design 4.3), the first install's plan unchanged. More's - # four rows, Remove files with each system the record holds and its + # Every plan names More (one word, counted in the plan budgets above): + # a pack can always be made. More's four rows where the folder has a + # record or a backup, then Make a pack (three words), Remove files with each system the record holds and its # size, the removal plan (what goes, the space freed, the folder, what # stays and why), its confirm and result, and the backups newest first. - "more": (17, 17, 15, 15), "remove": (31, 31, 29, 29), "removal": (34, 34, 32, 32), + "more": (20, 20, 18, 18), "remove": (31, 31, 29, 29), "removal": (34, 34, 32, 32), "removal-confirm": (18, 18, 16, 16), "removal-done": (18, 18, 16, 16), "backups": (24, 24, 22, 22), + # Make a pack: what goes in, its size and setup, where it goes, how it + # is written (one ZIP, or the parts and why), then the result. + "pack-plan": (27, 27, 24, 24), "pack-plan-parts": (39, 39, 35, 35), + "pack-done": (29, 29, 25, 25), } @@ -15293,12 +15345,12 @@ class MoreScreens(unittest.TestCase): self.addCleanup(patcher.stop) def test_a_plan_names_more_where_it_has_something_to_act_on(self): - self.assertNotIn("more", [row.action for row in install.tui_rows(checked_state())]) self.assertEqual([row.action for row in install.tui_rows(more_state())][-2:], ["more", "quit"]) done = golden_states()["plan-in-place"] - done.has_backups = True self.assertEqual(install.tui_rows(done)[-1].action, "more") + self.assertEqual([row.action for row in install.tui_rows(more_state("more"))], + ["remove", "backups", "putback", "dropbackup", "packmake"]) def test_the_removal_plan_asks_its_own_child(self): state = removal_state() @@ -15398,6 +15450,85 @@ class MoreScreens(unittest.TestCase): self.assertIn("scph5501.bin: changed since it was installed", text) +class PackScreens(unittest.TestCase): + """More, Make a pack: a dry run says what goes in, the run makes it, + each a child given the plan's choice and none of the folder's options.""" + + def setUp(self): + patcher = mock.patch.object(install, "_mounted_cards", return_value=[]) + patcher.start() + self.addCleanup(patcher.stop) + + def test_more_is_on_every_plan_with_make_a_pack(self): + state = checked_state() + self.assertEqual([row.action for row in install.tui_rows(state)][-2:], + ["more", "quit"]) + state.stack.append("more") + self.assertEqual([row.action for row in install.tui_rows(state)], ["packmake"]) + self.assertEqual([row.action for row in install.tui_rows(more_state("more"))][-1], + "packmake") + + def test_the_dry_run_takes_the_choice_and_not_the_folder(self): + state = pack_plan_state() + state.regions = ["japan"] + state.passthrough = [("--save-dir", "/saves")] + argv = install.tui_argv(state, "pack_plan", "python", "install.py") + self.assertIn("--region=japan", argv) + self.assertFalse([arg for arg in argv if arg.startswith(("--dest", "--save-dir"))]) + # No Downloads folder here: the home folder. + self.assertEqual(argv[-3:], [f"--pack={HOME}{os.sep}", "--dry-run", "--events"]) + with mock.patch.object(install, "_is_dir", return_value=True): + self.assertEqual(install.tui_pack_dir(state), HOME / "Downloads") + self.assertEqual([row.action for row in install.tui_rows(state)], + ["packgo", "packwhere"]) + + def test_make_the_pack_runs_it_and_close_ends_on_its_code(self): + state = pack_plan_state() + self.assertEqual(install.tui_update(state, Key("enter")), [("run", "pack")]) + self.assertEqual(install.tui_argv(state, "pack", "python", "install.py")[-2:], + ["--events", "--yes"]) + self.assertIn("Making the pack...", screen_text(install.tui_view(state, 80, 24))) + install.tui_receive(state, ("event", state.run_id, pack_event("written", size=900))) + install.tui_receive(state, ("ended", state.run_id, 0, [])) + self.assertIn("Pack made: 4 files, 900 B.", screen_text(install.tui_view(state, 80, 24))) + install.tui_update(state, Key("enter")) + self.assertEqual(state.exit_code, 0) + + def test_a_pack_not_made_says_so_and_back_returns_to_more(self): + state = pack_plan_state() + install.tui_update(state, Key("enter")) + failed = {**pack_event("failed"), "parts": [], + "message": "1 file could not be had: no pack was written."} + install.tui_receive(state, ("event", state.run_id, failed)) + install.tui_receive(state, ("ended", state.run_id, 1, [])) + text = screen_text(install.tui_view(state, 80, 24)) + self.assertIn("No pack was made.", text) + self.assertIn("1 file could not be had", text) + install.tui_update(state, Key("esc")) + self.assertEqual(state.screen, "more") + + def test_change_where_browses_and_reads_the_plan_again(self): + state = pack_plan_state() + state.focus["packplan"] = 1 + with mock.patch.object(install, "_browse_rows", return_value=( + [install.TuiRow("use", "Use this folder")], "")): + install.tui_update(state, Key("enter")) + self.assertEqual((state.screen, state.browse_for), ("browse", "packto")) + state.browse_dir = Path("/media/card") + self.assertEqual(install.tui_update(state, Key("enter")), [("run", "pack_plan")]) + self.assertEqual(state.screen, "packplan") + self.assertEqual(install.tui_argv(state, "pack_plan", "python", "install.py")[-3], + f"--pack={Path('/media/card')}{os.sep}") + + def test_a_dry_run_that_ends_without_its_event_is_an_error(self): + state = checked_state() + state.stack += ["more"] + state.focus["more"] = 0 + install.tui_update(state, Key("enter")) + install.tui_receive(state, ("ended", state.run_id, 2, ["install.py: error: no"])) + self.assertEqual(state.screen, "error") + + class ScreenWordBudgets(unittest.TestCase): def setUp(self): patcher = mock.patch.object(install, "_mounted_cards", return_value=[]) From 209dc1b662457e3892a8149753177168253f8e73 Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Wed, 11 Nov 2026 17:22:51 +0100 Subject: [PATCH 2/6] chore: pin the installer and write the pack event --- install.ps1 | 2 +- install.sh | 2 +- install/launchers/index.json | 16 +++--- schemas/install-events.schema.json | 79 ++++++++++++++++++++++++++++-- scripts/generate_event_schema.py | 7 +-- 5 files changed, 89 insertions(+), 17 deletions(-) diff --git a/install.ps1 b/install.ps1 index f56972656..7e80b09a6 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 = "26fef8daf6087201d43e1c1cb5b69e255358f38f28ca1e45782984a0240dc7d3" + $defaultInstallSha256 = "e9e2ecce0d716d7ec6035a580eb2fff1fcd207f6b323752a360d4c666afe2b9f" # 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.sh b/install.sh index ea37f4b62..969043a8d 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="26fef8daf6087201d43e1c1cb5b69e255358f38f28ca1e45782984a0240dc7d3" +DEFAULT_INSTALL_SHA256="e9e2ecce0d716d7ec6035a580eb2fff1fcd207f6b323752a360d4c666afe2b9f" # 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 c4d06bada..79211db27 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": 1285762, - "sha256": "26fef8daf6087201d43e1c1cb5b69e255358f38f28ca1e45782984a0240dc7d3", + "size": 1329027, + "sha256": "e9e2ecce0d716d7ec6035a580eb2fff1fcd207f6b323752a360d4c666afe2b9f", "executable": false }, { @@ -71,8 +71,8 @@ "muos": { "archive": { "dest": "ARCHIVE/RetroBIOS.muxapp", - "size": 1339387, - "sha256": "7060180b1a8d93573eee7a7a083a3903822743f52d8a06a9691b40a04ecbafb6" + "size": 1382652, + "sha256": "8ed6c5418093bf40bec41197b99a67c1f244100dc1eba51a83e456620fb434b4" }, "members": [ { @@ -92,8 +92,8 @@ { "name": "RetroBIOS/install.py", "repo_path": "install.py", - "size": 1285762, - "sha256": "26fef8daf6087201d43e1c1cb5b69e255358f38f28ca1e45782984a0240dc7d3", + "size": 1329027, + "sha256": "e9e2ecce0d716d7ec6035a580eb2fff1fcd207f6b323752a360d4c666afe2b9f", "executable": false }, { @@ -166,8 +166,8 @@ { "dest": ".config/modules/retrobios/install.py", "repo_path": "install.py", - "size": 1285762, - "sha256": "26fef8daf6087201d43e1c1cb5b69e255358f38f28ca1e45782984a0240dc7d3", + "size": 1329027, + "sha256": "e9e2ecce0d716d7ec6035a580eb2fff1fcd207f6b323752a360d4c666afe2b9f", "executable": false }, { diff --git a/schemas/install-events.schema.json b/schemas/install-events.schema.json index 3dd4d5f56..83e21f173 100644 --- a/schemas/install-events.schema.json +++ b/schemas/install-events.schema.json @@ -43,6 +43,7 @@ "removed", "restored", "backup", + "pack", "end" ] } @@ -147,6 +148,9 @@ { "$ref": "#/$defs/backup" }, + { + "$ref": "#/$defs/pack" + }, { "$ref": "#/$defs/end" } @@ -178,7 +182,8 @@ "dry-run", "list", "remove", - "restore" + "restore", + "pack" ] } } @@ -1022,7 +1027,8 @@ "dry-run", "list", "remove", - "restore" + "restore", + "pack" ] }, "installed": { @@ -1151,7 +1157,9 @@ "listed", "made", "deleted", - "not_deleted" + "not_deleted", + "planned", + "failed" ] }, "choice": { @@ -1352,7 +1360,70 @@ "listed", "made", "deleted", - "not_deleted" + "not_deleted", + "planned", + "failed" + ] + }, + "message": { + "type": "string" + } + } + }, + "pack": { + "type": "object", + "additionalProperties": false, + "required": [ + "event", + "platform", + "path", + "files", + "bytes", + "size", + "parts", + "status", + "message" + ], + "properties": { + "event": { + "const": "pack" + }, + "platform": { + "type": "string" + }, + "path": { + "type": "string" + }, + "files": { + "type": "integer", + "minimum": 0 + }, + "bytes": { + "type": "integer", + "minimum": 0 + }, + "size": { + "type": "integer", + "minimum": 0 + }, + "parts": { + "type": "array", + "items": { + "type": "string" + } + }, + "status": { + "enum": [ + "applied", + "written", + "unreadable", + "not_written", + "listed", + "made", + "deleted", + "not_deleted", + "planned", + "failed" ] }, "message": { diff --git a/scripts/generate_event_schema.py b/scripts/generate_event_schema.py index f10f73021..78167681b 100644 --- a/scripts/generate_event_schema.py +++ b/scripts/generate_event_schema.py @@ -39,11 +39,11 @@ KEY_TYPES: dict[str, dict] = { "folder", "dest", "system", "name", "bios_dir", "path", "member", "list_version", "installed_version", "board", "core", "date", "moved_to", ), _TEXT), - "mode": {"enum": ["install", "check", "dry-run", "list", "remove", "restore"]}, + "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"]}, + "deleted", "not_deleted", "planned", "failed"]}, **dict.fromkeys(( "files", "files_done", "files_total", "bytes", "bytes_done", "bytes_total", "bytes_local", "bytes_network", "size", "present", "missing", "wrong_hash", @@ -52,7 +52,8 @@ KEY_TYPES: dict[str, dict] = { ), _COUNT), **dict.fromkeys(("truncated", "ok", "interrupted", "required_only", "applied", "info", "backup"), _FLAG), - **dict.fromkeys(("systems", "other_drives", "dests", "written", "choice"), _NAMES), + **dict.fromkeys(("systems", "other_drives", "dests", "written", "choice", "parts"), + _NAMES), **dict.fromkeys(("platforms", "failed", "skipped", "left_out", "kept", "found", "fallback"), _RECORDS), } From 2e1f70af1efdbb2f4fc57dc1e5005a653cf8e111 Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Wed, 11 Nov 2026 17:22:51 +0100 Subject: [PATCH 3/6] docs: describe making a pack --- scripts/sitediagrams.py | 1 + wiki/installer.md | 65 ++++++++++++++++++++++++++++++++++++++--- wiki/testing-guide.md | 2 +- 3 files changed, 63 insertions(+), 5 deletions(-) diff --git a/scripts/sitediagrams.py b/scripts/sitediagrams.py index c62fd7017..f29061ca5 100644 --- a/scripts/sitediagrams.py +++ b/scripts/sitediagrams.py @@ -905,6 +905,7 @@ GLANCE_GROUPS: tuple[tuple[str, tuple[str, ...]], ...] = ( ("Look first", ("--check", "--dry-run", "--list-platforms", "--list-targets", "--list-systems", "--list-cores", "--list-emulators")), ("From files on hand", ("--from", "--from-pack", "--manifest", "--offline")), + ("Make a pack", ("--pack", "--split")), ("Remove and put back", ("--remove", "--file", "--backup", "--backups", "--restore", "--delete-backup")), ("How the run talks", ("--tui", "--plain", "--no-input", "--yes", "--quiet", "--verbose", diff --git a/wiki/installer.md b/wiki/installer.md index 0db0fdb6d..72403a1ae 100644 --- a/wiki/installer.md +++ b/wiki/installer.md @@ -876,6 +876,60 @@ without a terminal, or no at the question). With `--events` the run writes `removal_plan`, `removed`, `backup` and `restored` events, see [Machine-readable events](#machine-readable-events). +## Making a pack { #making-a-pack } + +`--pack PATH` downloads the files of the choice into a pack ZIP instead of a +BIOS folder, for another device or an install without the internet. Every +narrowing option applies as for an install (`--system`, `--core`, +`--emulator`, `--region`, `--target`, `--no-game-data`, and `--for-games +FOLDER` with `--required-only`), and `--dry-run` says what would go in, +`--verbose` listing each file: + +``` +python3 install.py --platform retroarch --system sony-playstation --pack ~/Downloads/ --dry-run +Pack for RetroArch: 108 files (324.0 MB). +Pack: ~/Downloads/RetroArch_Custom_BIOS_Pack.zip + --verbose lists the files. +``` + +Without `--dry-run` the run downloads the files, writes the pack and ends on +`Pack made:` with the count and the size of the ZIP. + +A folder takes the name `_BIOS_Pack.zip`, with `_Custom` when the +choice narrows the list. A file name must end with `_BIOS_Pack.zip`, the +name `--from-pack` and the parts read. On the other device, +`--from-pack` on the pack installs the same files at the same places, with no +network and no option: the pack's `manifest.json` carries the list narrowed +to the choice, the cores per board and every file's SHA-1. A file two places +share is stored once, and each data tree sits where the reader looks for it. + +Every file is checked against its SHA-1 as it is written into the ZIP, before +the ZIP is closed. The pack is written beside its final name and renamed only +once complete, so a download that fails, a file that does not match or a stop +leaves no file behind, and a pack of the same name written before stays as it +was. The bytes depend on the choice alone: members in a fixed order, a fixed +date and mode, one compression level. Making the pack needs room for the files +and the ZIP together on the drive it goes to. + +`--split SIZE` (`1900M`, `4G`) writes parts of at most that size, each a whole +ZIP named `.part1of3.zip`, as release packs are split, with the marker +`--check` reads. On a FAT32 drive, which holds no file of 4 GB or more, a pack +that would pass that is split by itself, and the run says so in one line. +`--from-pack` takes any one of the parts and finds the others beside it. + +On the full screen, **More** on the plan holds **Make a pack**. Its plan names +the files, their size, where the pack goes (Downloads, else the home folder, +**Change where** to browse) and how it is written, then **Make the pack** +gives the result. The plan's choice is the pack's, and the options of the +folder of this machine (the save directory, the installed cores, the card's +own games) are left out. + +Exit codes: `0` once written, or listed with `--dry-run`, `1` when a file +could not be had or the pack could not be written, `2` when nothing was tried +(an option refused, a choice that keeps no file, a file larger than a part, +too little room). With `--events` the run writes a `pack` event, see +[Machine-readable events](#machine-readable-events). + ## Copy from an old card { #copy-from-an-old-card } The card a handheld came with, a backup of an old BIOS folder, a Downloads @@ -1196,6 +1250,8 @@ what the options name, everything by default. | `--backup` | With `--remove`, move the files into a dated folder of `retrobios-backup` instead of deleting them, for `--restore` to put back | | `--backups` | List the backups of the BIOS folder, newest first, with the date, the files and the size of each | | `--delete-backup FOLDER` | Delete one backup listed by `--backups`, after one question that names its date and size (`--yes` skips it) | +| `--pack PATH` | Download the choice into a pack ZIP at PATH instead of a BIOS folder, for another device or an install without the internet: a folder takes `_BIOS_Pack.zip`. The narrowing options apply, `--dry-run` lists what would go in, and `--from-pack` installs from it. See [Making a pack](#making-a-pack) | +| `--split SIZE` | With `--pack`, write parts of at most SIZE (`1900M`, `4G`), each a whole ZIP. A pack that would pass 4 GB on a FAT32 drive is split by itself | | `--tui` | Open the full-screen interface, or stop with the reason it cannot open here (code 2) instead of falling back to the questions. Wins over `RETROBIOS_PLAIN` and `ACCESSIBLE`. See [The full-screen interface](#the-full-screen-interface) | | `--plain` | Ask the questions line by line instead of the full-screen interface, the mode for a screen reader. See [The full-screen interface](#the-full-screen-interface) | | `--version` | Print the installer's identity, the first 12 hex digits of the SHA-256 the bootstraps pin | @@ -1976,8 +2032,8 @@ fields, the installer refuses to narrow rather than install everything. | Code | Meaning | |------|---------| | `0` | everything asked for is installed or already in place, or removed, put back or deleted | -| `1` | a failure: the one-liner could not download or verify `install.py`, or found no Python 3.8 with its ssl, unicodedata and zlib modules (nothing was run), an unusable base URL, `--installed-cores` with no core found, a manifest that fails validation, a fetch that never succeeded, no platform to install for in a non-interactive run, some files failed or were left out by `--offline` while others installed, a `--from-pack` pack that cannot be read, lacks a part or is for another platform, a `--from` folder that does not exist or cannot be read, a BIOS folder that is a file or lies under one, a `--dest` that is not the card of the system named (another system's card, a folder inside one, a drive with none of its files where its card always has them, or a folder that does not exist), `--restore` could not put a file back, `--remove` or `--delete-backup` could not delete a file or update the install record, or `--add-app` could not put every file of the app on the card | -| `2` | nothing was installed: every file the run tried failed (a BIOS folder that cannot be written, for one), or `--offline` left every file out, the drive has too little free space for the download (checked before any folder is created), or the question about a folder that does not exist, named with `--dest` or typed at the folder question, was answered no. Also an option the installer refused before any download: an unknown option, `--jobs` outside 1 to 32, `--target` with `--every-board`, `--target` with `--from-pack` or `--offline` (or `RETROBIOS_INSTALL_OFFLINE` set) when no core list per board is at hand (the pack carries none and none is beside `--manifest` as `targets/.json`), or for a platform that publishes none, which is said to have no hardware targets, `--list-targets` with `--offline` and neither, `--add-app` with `--check`, `--dry-run`, a listing, `--from-pack` or `--offline`. The message then starts with `install.py: error:`. Also an unknown platform, target, system, core or emulator, said in an `Error:` or `Unknown platform` line and an `error` event whose `stage` is `option`. Also `--add-app` for a folder on no card that takes the app, said in an `Error:` line and an `app` event before anything is written. With `--restore` or `--delete-backup`, a folder that is not a dated folder inside `retrobios-backup`. With `--remove`, nothing removed: no install record of the setup, nothing it can remove, no `--yes` without a terminal, or no at its question, and the same for `--delete-backup`. Also a quit chosen before the install, as `gh` ends a cancelled prompt: `q` at a question, `q` or **Quit** on the full screen, which then keeps `RetroBIOS: quit. Nothing was installed.`, and the full screen closed with no button pressed (`RETROBIOS_IDLE_EXIT`). No code but `0` closes a Windows Terminal tab started on the installer itself, so such a tab stays open on a quit | +| `1` | a failure: the one-liner could not download or verify `install.py`, or found no Python 3.8 with its ssl, unicodedata and zlib modules (nothing was run), an unusable base URL, `--installed-cores` with no core found, a manifest that fails validation, a fetch that never succeeded, no platform to install for in a non-interactive run, some files failed or were left out by `--offline` while others installed, a `--from-pack` pack that cannot be read, lacks a part or is for another platform, a `--from` folder that does not exist or cannot be read, a BIOS folder that is a file or lies under one, a `--dest` that is not the card of the system named (another system's card, a folder inside one, a drive with none of its files where its card always has them, or a folder that does not exist), `--restore` could not put a file back, `--remove` or `--delete-backup` could not delete a file or update the install record, `--pack` could not get a file or write the pack (nothing is left behind), or `--add-app` could not put every file of the app on the card | +| `2` | nothing was installed: every file the run tried failed (a BIOS folder that cannot be written, for one), or `--offline` left every file out, the drive has too little free space for the download (checked before any folder is created), or the question about a folder that does not exist, named with `--dest` or typed at the folder question, was answered no. Also an option the installer refused before any download: an unknown option, `--jobs` outside 1 to 32, `--target` with `--every-board`, `--target` with `--from-pack` or `--offline` (or `RETROBIOS_INSTALL_OFFLINE` set) when no core list per board is at hand (the pack carries none and none is beside `--manifest` as `targets/.json`), or for a platform that publishes none, which is said to have no hardware targets, `--list-targets` with `--offline` and neither, `--add-app` with `--check`, `--dry-run`, a listing, `--from-pack` or `--offline`. The message then starts with `install.py: error:`. Also an unknown platform, target, system, core or emulator, said in an `Error:` or `Unknown platform` line and an `error` event whose `stage` is `option`. Also `--add-app` for a folder on no card that takes the app, said in an `Error:` line and an `app` event before anything is written. With `--restore` or `--delete-backup`, a folder that is not a dated folder inside `retrobios-backup`. With `--pack`, no pack tried: a choice that keeps no file, a file larger than a part of `--split`, too little room, or `--pack` with an option that reads the BIOS folder of this machine. With `--remove`, nothing removed: no install record of the setup, nothing it can remove, no `--yes` without a terminal, or no at its question, and the same for `--delete-backup`. Also a quit chosen before the install, as `gh` ends a cancelled prompt: `q` at a question, `q` or **Quit** on the full screen, which then keeps `RetroBIOS: quit. Nothing was installed.`, and the full screen closed with no button pressed (`RETROBIOS_IDLE_EXIT`). No code but `0` closes a Windows Terminal tab started on the installer itself, so such a tab stays open on a quit | | `3` | `--check` ran and found files to fetch or wrong copies, nothing having failed. A failure takes `1` as before: a manifest refused, a `--from` folder that does not exist. Until November 2026 this case also ended on `1`, so a script that reads any code but `0` as "not ready" needs no change | | `130` | stopped with Ctrl+C, or with Ctrl+C or Ctrl+D at a question, the terminal keeping `RetroBIOS: stopped. Nothing was installed.` before an install. Run the same command again to carry on | | `141` | the output was piped to a reader that closed early (`--list-platforms \| head`) | @@ -2021,7 +2077,7 @@ other schemas under `api/v1/schemas/`. | Kind | Keys | When | |------|------|------| -| `start` | `schema`, `installer`, `mode` | First line. `schema` is 1, `installer` the identity `--version` prints, `mode` one of `install`, `check`, `dry-run`, `list` (also `--backups`), `remove` (`--remove`, `--delete-backup`), `restore` | +| `start` | `schema`, `installer`, `mode` | First line. `schema` is 1, `installer` the identity `--version` prints, `mode` one of `install`, `check`, `dry-run`, `list` (also `--backups`), `remove` (`--remove`, `--delete-backup`), `restore`, `pack` (`--pack`, with `--dry-run` too) | | `unsearched` | `folder`, `reason`, `message` | Before `detect`, once for each folder the search for setups could not look in, this user being refused it or a read failing there (a failing card, a link that loops), or under WSL the Windows side when Windows did not answer (`folder` is then the drive mount, `/mnt`). What it would hold counts as absent, and the other places are still searched: `detect` then lists what they hold, and an empty `platforms` after an `unsearched` line means nothing was found where the installer could look. `reason` says why in words (`Permission denied`), `message` says it in a sentence | | `detect` | `os`, `os_name`, `platforms` | Once the platforms are known. `os_name` comes from `/etc/os-release`. `platforms` lists `{platform, name, bios_dir}`, and is empty when nothing supported was found | | `error` | `stage`, `reason`, `platform`, `message` | The file list could not be read (`stage` is `manifest`): `reason` is `network`, `not_found` or `invalid`, `clock` when the server's certificate was refused and the system clock reads a date before the installer was written, `no_ca` when the machine holds no list of trusted certificates (`SSL_CERT_FILE` names one), `no_ssl` when this Python was built without its `ssl` module and cannot use HTTPS, or `offline` when `--offline` forbids the request. A folder named with `--from` cannot be read (`stage` is `from`, `reason` `not_found`, `not_a_folder` for a file that is no ZIP, `unreadable`, or `system` for the root of the system, `/proc`, `/sys` or `/dev`). The BIOS folder sits under a folder this user cannot open (`stage` is `dest`, `reason` `unreadable`), or is a file or lies under one (`reason` `not_a_folder`), and the run ends with code 1 before anything is written. A platform, target, system, core or emulator named on the command line is unknown or cannot be used here (`stage` is `option`, `reason` `unknown`, `platform` the platform it was checked against or the name typed), refused before any download with code 2. The BIOS folder cannot be created (`stage` is `dest`, `reason` `not_writable`): a `summary` follows with what the run installed before it. Two systems are detected on one machine and no `--dest` names the folder (`stage` is `detect`, `reason` `conflict`). The platform named with `--platform` is found nowhere and no folder can be assumed for it: a card system with no card named, a portable emulator, Batocera or Recalbox named on a computer (their folder is the `bios` folder of their SHARE drive), or no usual folder on this system or one set aside behind a folder this user cannot open (`stage` is `detect`, `reason` `not_found`). So is a platform named by a file list or a pack, in a run without questions where it is found nowhere here. A `--dest` refused as the card of the system named carries the same `stage` and `reason`: another system's card, a folder inside a card, a drive with none of the files its card always has, or a folder that does not exist. `message` says it in words, and is the only thing that tells these cases apart | @@ -2054,11 +2110,12 @@ other schemas under `api/v1/schemas/`. | `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` | | `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)) | -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, `version` with the list's version, `record` with the install record, `removal_plan`, `removed`, `restored` and `backup` with removal), 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, `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 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 diff --git a/wiki/testing-guide.md b/wiki/testing-guide.md index a31eb1127..bc8b80a10 100644 --- a/wiki/testing-guide.md +++ b/wiki/testing-guide.md @@ -59,7 +59,7 @@ Every module in `tests/`, by the area it guards. | Packs and manifests | synthetic + real packs | `test_artifact_lock`, `test_atomic_artifacts`, `test_batocera_cores`, `test_core_data_trees`, `test_deterministic_zip`, `test_emulator_pack_counts`, `test_finalize_pack_names`, `test_large_file_cache`, `test_libretro_layout`, `test_manifest_entry`, `test_minui_platform`, `test_no_game_data`, `test_pack_conformance_dirs`, `test_pack_core_extras`, `test_pack_counts`, `test_pack_destinations`, `test_pack_failures`, `test_pack_file_names`, `test_pack_grouping`, `test_pack_integrity`, `test_pack_member_identity`, `test_pack_readme`, `test_platform_inheritance`, `test_platform_keys`, `test_release_packs`, `test_required_only_archives`, `test_required_only_twins`, `test_save_root`, `test_split_extras`, `test_split_names`, `test_split_pack`, `test_system_pack_extras`, `test_system_pack_parity`, `test_torrentzip`, `test_which_pack` | | Slots and regions | synthetic + profiles | `test_region`, `test_region_agnostic_scan`, `test_region_groups`, `test_region_held`, `test_region_platform_index`, `test_region_required_only`, `test_slot`, `test_slots`, `test_slots_shipped_file` | | Hardware targets and systems | synthetic + target files | `test_amberelec_targets`, `test_emuelec_targets`, `test_extract_targets`, `test_lakka_targets`, `test_libretro_slugs`, `test_system_ids`, `test_system_selection`, `test_target_names`, `test_target_scrapers`, `test_target_systems`, `test_target_verify` | -| Installer and downloads | loopback server | `test_check_release`, `test_download`, `test_install`, `test_install_cores`, `test_install_experience`, `test_install_filesystems`, `test_install_app`, `test_install_from`, `test_install_games`, `test_install_journeys`, `test_install_offline`, `test_install_removal`, `test_install_selection`, `test_install_tui`, `test_pypi_package` | +| Installer and downloads | loopback server | `test_check_release`, `test_download`, `test_install`, `test_install_cores`, `test_install_experience`, `test_install_filesystems`, `test_install_app`, `test_install_from`, `test_install_games`, `test_install_journeys`, `test_install_offline`, `test_install_pack`, `test_install_removal`, `test_install_selection`, `test_install_tui`, `test_pypi_package` | | Handheld launchers | a pty as the console, fake installer and firmware tools, stubbed PortMaster dialogs | `test_handheld_launchers`, `test_port` | | Running cores | parsers on fixed inputs, a libretro core built from C in the test when a compiler exists | `test_core_probe` | | Measurement records | synthetic record files, the committed `measurements/` against HEAD, the **Proof** line naming the BIOS a core ran, and that no page shows a Tested block, a region outcome or a time per frame | `test_measurements` | From 475b6acf83faf8f8da654a6abc998d0de840244e Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Wed, 11 Nov 2026 17:41:53 +0100 Subject: [PATCH 4/6] fix: keep case variants and types in a pack run --- install.ps1 | 2 +- install.py | 18 +++++++++++------- install.sh | 2 +- install/launchers/index.json | 16 ++++++++-------- tests/test_install_journeys.py | 12 +++++++----- 5 files changed, 28 insertions(+), 22 deletions(-) diff --git a/install.ps1 b/install.ps1 index 7e80b09a6..ae4c13a39 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 = "e9e2ecce0d716d7ec6035a580eb2fff1fcd207f6b323752a360d4c666afe2b9f" + $defaultInstallSha256 = "367c20d31846e626baf9ed356bc9456d7a8e35d183ac3f376e4d9b9ba8a5763d" # 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 29a15ae79..4facdc149 100644 --- a/install.py +++ b/install.py @@ -14044,11 +14044,11 @@ def write_pack(path: Path, manifest: bytes, members: list[PackMember], scratches: list[Path] = [] try: for index, (final, chosen) in enumerate(zip(finals, plan), 1): - handle, scratch = tempfile.mkstemp(prefix=f".{final.name}.", suffix=".partial", - dir=str(path.parent)) + handle, made = tempfile.mkstemp(prefix=f".{final.name}.", suffix=".partial", + dir=str(path.parent)) os.close(handle) - scratches.append(Path(scratch)) - with zipfile.ZipFile(scratch, "w", zipfile.ZIP_DEFLATED, + scratches.append(Path(made)) + with zipfile.ZipFile(made, "w", zipfile.ZIP_DEFLATED, compresslevel=PACK_COMPRESSLEVEL) as archive: if count > 1: archive.writestr( @@ -18439,12 +18439,16 @@ def _install(args: argparse.Namespace, real_stdout: TextIO) -> None: files = manifest.get("files", []) omitted_files = manifest.get("omitted_files", []) variants = manifest.get("case_variants", []) - # A ZIP keeps both spellings: the device installing it folds them. - case_kept = packing or keeps_case(bios_path) + case_kept = keeps_case(bios_path) if variants and case_kept: # The list is folded for Windows and macOS, but here bios.col and # BIOS.col are two files that two cores open. files = files + [{**variant, "case_variant": True} for variant in variants] + elif packing: + # A ZIP keeps both spellings, whatever drive it is written to: + # the device installing it folds them. + files = files + [{**variant, "case_variant": True} for variant in variants] + case_kept = True if not case_kept: files, folded = fold_case_twins(files) if folded: @@ -18600,7 +18604,7 @@ def _install(args: argparse.Namespace, real_stdout: TextIO) -> None: # one read from an unknown save directory left out. Said once the # choice is made, over the files it keeps (say_saves). display = display_name(plat_name, manifest) - unplaced = [] + unplaced: list[dict] = [] if not packing: # A pack keeps every root's files: the device installing it # places them. diff --git a/install.sh b/install.sh index 969043a8d..d059c2f9c 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="e9e2ecce0d716d7ec6035a580eb2fff1fcd207f6b323752a360d4c666afe2b9f" +DEFAULT_INSTALL_SHA256="367c20d31846e626baf9ed356bc9456d7a8e35d183ac3f376e4d9b9ba8a5763d" # 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 79211db27..0bf3b3e9d 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": 1329027, - "sha256": "e9e2ecce0d716d7ec6035a580eb2fff1fcd207f6b323752a360d4c666afe2b9f", + "size": 1329206, + "sha256": "367c20d31846e626baf9ed356bc9456d7a8e35d183ac3f376e4d9b9ba8a5763d", "executable": false }, { @@ -71,8 +71,8 @@ "muos": { "archive": { "dest": "ARCHIVE/RetroBIOS.muxapp", - "size": 1382652, - "sha256": "8ed6c5418093bf40bec41197b99a67c1f244100dc1eba51a83e456620fb434b4" + "size": 1382831, + "sha256": "8de74ce7b0554380b4d2b3ec2702b70c3acdd0b8f8d20cba040366746eac2562" }, "members": [ { @@ -92,8 +92,8 @@ { "name": "RetroBIOS/install.py", "repo_path": "install.py", - "size": 1329027, - "sha256": "e9e2ecce0d716d7ec6035a580eb2fff1fcd207f6b323752a360d4c666afe2b9f", + "size": 1329206, + "sha256": "367c20d31846e626baf9ed356bc9456d7a8e35d183ac3f376e4d9b9ba8a5763d", "executable": false }, { @@ -166,8 +166,8 @@ { "dest": ".config/modules/retrobios/install.py", "repo_path": "install.py", - "size": 1329027, - "sha256": "e9e2ecce0d716d7ec6035a580eb2fff1fcd207f6b323752a360d4c666afe2b9f", + "size": 1329206, + "sha256": "367c20d31846e626baf9ed356bc9456d7a8e35d183ac3f376e4d9b9ba8a5763d", "executable": false }, { diff --git a/tests/test_install_journeys.py b/tests/test_install_journeys.py index 35a3bf388..3e0fa7351 100644 --- a/tests/test_install_journeys.py +++ b/tests/test_install_journeys.py @@ -61,21 +61,23 @@ JOURNEY_KEYS = { # word: its length is the machine's. A change that adds words raises a # number here and says why. JOURNEY_WORDS = { - "first_install": 47, - "card_with_games": 87, + # Every plan names More (one word, Make a pack being always there): one + # word per plan a journey stops on. + "first_install": 48, + "card_with_games": 88, # A plan whose folder has a record names More (one word): an update # and a second run of one system. "update": 71, - "one_system": 179, + "one_system": 181, "one_system_again": 68, # Change holds every option one level down now (design 4.4): its # headings and the rows for Emulators, a pack, the device and the # internet, the intro sentence dropped, 10 words on each of its two # frames. - "what_is_missing": 227, + "what_is_missing": 228, # The plan of the setup found comes first now (33 words), the setups # one Esc away, and the last plan names Change where (2 words). - "another_device": 265, + "another_device": 267, } # Which setup? names every setup, Preview every file: lists, not prose. SCREEN_CEILING = 90 From ba2df77698ce1c5338f17006b002d1ea8083a82a Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Wed, 11 Nov 2026 18:06:16 +0100 Subject: [PATCH 5/6] fix: swap a pack in whole and name its platform The earlier pack of the name is set aside while the new files take their names and put back if one cannot, so the folder never holds a mix of parts. A scratch file that cannot be deleted is named, and a cleanup that fails keeps a written pack at exit 0. Only a file whose marker or manifest names the pack is removed, each one said. Each member is deflated at level 9 and the ZIP is read back with testzip. The space check counts the largest data tree archive. A pack name that spells another platform is refused, and the reader trusts the platform the manifest names. --- install.ps1 | 2 +- install.py | 203 +++++++++++++++++++++++++++++------ install.sh | 2 +- install/launchers/index.json | 16 +-- tests/test_install_pack.py | 185 +++++++++++++++++++++++++++++++ 5 files changed, 364 insertions(+), 44 deletions(-) diff --git a/install.ps1 b/install.ps1 index ae4c13a39..5c54d346c 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 = "367c20d31846e626baf9ed356bc9456d7a8e35d183ac3f376e4d9b9ba8a5763d" + $defaultInstallSha256 = "0eb4260d873e9fa9186fec264a0f4d484707d58daf432d5addbe65feb4912ae2" # 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 4facdc149..4e0586f56 100644 --- a/install.py +++ b/install.py @@ -13513,11 +13513,12 @@ class PackSource: def platforms(self) -> list[str]: """The platforms the pack's name spells, several for a grouped pack.""" spelled = pack_name_platforms(self.name) - if spelled: - return spelled - # A pack made by --pack under a name of the user's says it inside. + # A pack made by --pack says its platform inside, which a name of + # the user's, or a file renamed, does not change. named = (self.install_list or {}).get("platform") - return [named] if named in AVAILABLE_PLATFORMS else [] + if named in AVAILABLE_PLATFORMS and named not in spelled: + return [named] + return spelled def manifest(self, plat: str) -> dict: """A file list for plat: the install list the pack carries, else one @@ -13650,9 +13651,10 @@ def pack_lacks_words(count: int, total: int) -> str: # --pack writes the narrowed choice as a pack --from-pack reads: each file # once by its SHA-1, at its destination (a file of another root under that # root's name), each data tree at its place, and manifest.json carrying the -# list narrowed to the choice. The bytes depend on the inputs alone: members -# in a fixed order, a fixed date and mode, one compression level, as -# generate_pack.py writes its packs. +# list narrowed to the choice. For one zlib the bytes depend on the inputs +# alone: members in a fixed order, a fixed date and mode, one compression +# level set on each member. Another deflate gives other bytes for the same +# members (zlib-ng, which CPython 3.14 on Windows ships). PACK_NAME_END = "_BIOS_Pack.zip" PACK_MEMBER_DATE = (1980, 1, 1, 0, 0, 0) PACK_COMPRESSLEVEL = 9 @@ -13675,7 +13677,22 @@ _ZIP_END_BYTES = 22 + 56 + 20 class PackError(Exception): - """A pack that cannot be made as asked: nothing is written.""" + """A pack that cannot be made as asked. left names the files a failure + could not take away, none when nothing was left behind.""" + + def __init__(self, words: str, left: list[Path] | None = None) -> None: + super().__init__(words) + self.left = list(left or []) + + +class PackWritten(NamedTuple): + """What write_pack did: the files of the pack, the earlier files of + its name it removed, and those it could not remove or left as they + are, each with the reason.""" + + files: list[Path] + removed: list[Path] + kept: list[tuple[Path, str]] class PackMember(NamedTuple): @@ -13963,6 +13980,10 @@ def _pack_info(name: str, compress: int = zipfile.ZIP_DEFLATED) -> zipfile.ZipIn """A member header that depends on its name alone.""" info = zipfile.ZipInfo(name, date_time=PACK_MEMBER_DATE) info.compress_type = compress + # A ZipInfo given to writestr or open keeps its own level, the + # archive's left unread: without it every member was deflated at 6. + info._compresslevel = ( # type: ignore[attr-defined] + PACK_COMPRESSLEVEL if compress == zipfile.ZIP_DEFLATED else None) info.create_system = 3 info.external_attr = 0o100644 << 16 return info @@ -14024,17 +14045,56 @@ def _part_contents(name: str, index: int, count: int, manifest: bytes, return held + [(member.name, member.size) for member in chosen] -def write_pack(path: Path, manifest: bytes, members: list[PackMember], - limit: int | None) -> list[Path]: - """Write the pack at path, or in parts beside it when a limit is given - and the pack would pass it. Returns the files written. +def _discard(paths: Iterable[Path]) -> list[Path]: + """Delete each file, the ones that could not be deleted returned.""" + left = [] + for path in paths: + try: + path.unlink(missing_ok=True) + except OSError: + left.append(path) + return left - Each file is written beside its final name and renamed only once every - member was checked against its SHA-1 and the archives read back: a - failure leaves no file behind, and a pack of that name written before - stays as it was. An earlier pack of that name in another layout (whole, - or in another count of parts) goes once the new one is in place: - --from-pack would otherwise find both.""" + +def _of_this_pack(path: Path, name: str) -> bool: + """Whether path is a regular file that is a pack of this name: a part + whose marker names it, or a ZIP holding a manifest.json.""" + try: + if not stat.S_ISREG(os.lstat(path).st_mode): + return False + with zipfile.ZipFile(path) as archive: + names = archive.namelist() + markers = [member for member in names if _PART_MARKER.match(member)] + if markers: + text = archive.read(markers[0])[:MAX_MARKER_BYTES].decode("utf-8", "replace") + return f"pack: {name}" in text.splitlines() + return "manifest.json" in names + except (OSError, zipfile.BadZipFile, ValueError): + return False + + +def _aside_name(path: Path) -> Path: + """A name beside path no file holds, for the earlier pack while the + new one takes its place.""" + for number in range(1000): + aside = path.with_name(f".{path.name}.{os.getpid()}.{number}.old") + if not os.path.lexists(aside): + return aside + raise PackError(f"no free name beside {path.name} to set it aside") + + +def write_pack(path: Path, manifest: bytes, members: list[PackMember], + limit: int | None) -> PackWritten: + """Write the pack at path, or in parts beside it when a limit is given + and the pack would pass it. + + Each file is written beside its final name, every member checked + against its SHA-1 and the archive read back with its CRCs. Then the + earlier files of this pack (whole, or in parts) are set aside, the new + ones renamed in, and the earlier ones deleted. A failure before the new + set is whole puts the earlier set back and deletes the new files: the + folder holds the pack before or the pack after, never a mix. A file + deleted at the end that cannot be is reported, the pack being written.""" name = path.name plan = plan_pack_parts(name, len(manifest), members, limit) count = len(plan) @@ -14069,6 +14129,9 @@ def write_pack(path: Path, manifest: bytes, members: list[PackMember], shown = finals[index - 1].name with zipfile.ZipFile(scratch) as archive: held = [(info.filename, info.file_size) for info in archive.infolist()] + damaged = archive.testzip() + if damaged is not None: + raise PackError(f"{shown}: {damaged} does not read back") if count > 1 and archive.read(part_marker_name(name, index, count)) != \ part_marker_text(name, index, sizes): raise PackError(f"{shown}: its marker does not read back") @@ -14076,20 +14139,69 @@ def write_pack(path: Path, manifest: bytes, members: list[PackMember], raise PackError(f"{shown} does not read back as written") if limit is not None and count > 1 and sizes[index - 1] >= limit: raise PackError(f"{shown} reached the limit of {format_size(limit)}") - except BaseException: - for scratch in scratches: - scratch.unlink(missing_ok=True) + except BaseException as exc: + left = _discard(scratches) + if left and isinstance(exc, (OSError, PackError)): + raise PackError(str(exc), left) from exc raise + return _swap_in(path, scratches, finals) + + +def _swap_in(path: Path, scratches: list[Path], finals: list[Path]) -> PackWritten: + """Put the new files in place of the earlier pack of this name.""" + name = path.name stem = name[: -len(".zip")] - stale = [old for old in _listed_paths(path.parent) - if old not in finals and (old == path or ( + named = [old for old in _listed_paths(path.parent) + if old == path or old in finals or ( _PART_FILE.match(old.name) is not None - and _PART_FILE.match(old.name)["stem"] == stem))] # type: ignore[index] - for scratch, final in zip(scratches, finals): - os.replace(scratch, final) - for old in stale: - old.unlink(missing_ok=True) - return finals + and _PART_FILE.match(old.name)["stem"] == stem)] # type: ignore[index] + kept: list[tuple[Path, str]] = [] + earlier: list[Path] = [] + aside: list[tuple[Path, Path]] = [] + placed: list[Path] = [] + try: + for old in named: + if old in finals: + if not stat.S_ISREG(os.lstat(old).st_mode): + raise PackError(f"{old.name} is in the way and is not a file") + earlier.append(old) + elif _of_this_pack(old, name): + earlier.append(old) + else: + kept.append((old, "it is not a part of this pack, left as it is")) + for old in earlier: + moved = _aside_name(old) + os.replace(old, moved) + aside.append((old, moved)) + for scratch, final in zip(scratches, finals): + os.replace(scratch, final) + placed.append(final) + except (OSError, PackError) as exc: + left = _discard([*placed, *(scratch for scratch, final in zip(scratches, finals) + if final not in placed)]) + unrestored = [] + for old, moved in reversed(aside): + try: + os.replace(moved, old) + except OSError: + unrestored.append((old, moved)) + words = f"{name} could not be put in place: {exc.strerror or exc}" \ + if isinstance(exc, OSError) else str(exc) + if unrestored: + words += ". The earlier pack is set aside as " + ", ".join( + f"{moved.name} (was {old.name})" for old, moved in unrestored) + raise PackError(words, [*left, *(moved for _old, moved in unrestored)]) from exc + removed = [] + for old, moved in aside: + if old in finals: + if _discard([moved]): + kept.append((moved, "the earlier copy could not be deleted")) + continue + if _discard([moved]): + kept.append((moved, f"the earlier {old.name}, set aside, could not be deleted")) + else: + removed.append(old) + return PackWritten(finals, removed, kept) def _listed_paths(folder: Path) -> list[Path]: @@ -14132,6 +14244,16 @@ def pack_parts_words(count: int, limit: int | None, fat: bool) -> str: return f"{each}, as FAT32 holds no file of 4 GB." if fat else f"{each}." +def pack_space_bytes(files: int, bound: int, data_dirs: list[dict]) -> int: + """What making a pack takes on its drive: the files fetched, the ZIP at + its largest, and the largest source archive of a data tree, which is + downloaded whole beside its tree until the tree is read. A pack read + as the source fetches no archive.""" + archives = [int(entry.get("archive_size") or 0) for entry in data_dirs + if entry.get("files") and isinstance(entry.get("archive_size"), int)] + return files + bound + (max(archives, default=0) if LOCAL.pack is None else 0) + + def run_pack(args: argparse.Namespace, plat: str, manifest: dict, files: list[dict], omitted: list[dict], data_dirs: list[dict], narrowed: bool, term: Terminal) -> int: @@ -14147,6 +14269,11 @@ def run_pack(args: argparse.Namespace, plat: str, manifest: dict, files: list[di if not _is_dir(path.parent): return _pack_refused(plat, path, f"the folder {shown_path(path.parent)} does not " "exist", 2) + spelled = pack_name_platforms(path.name) + if spelled and plat not in spelled: + return _pack_refused(plat, path, f"{path.name} names a pack for " + f"{' and '.join(display_name(name) for name in spelled)}, and " + f"this one is for {display_name(plat)}", 2) members, rows, sources = pack_layout(files, data_dirs) if not members: return _pack_refused(plat, path, "the choice keeps no file to put in a pack", 2) @@ -14180,7 +14307,7 @@ def run_pack(args: argparse.Namespace, plat: str, manifest: dict, files: list[di print(" --verbose lists the files.") _pack_event(plat, path, members, finals, "planned", how) return 0 - needed = total + pack_bound(len(body), planned) + needed = pack_space_bytes(total, pack_bound(len(body), planned), data_dirs) try: free = shutil.disk_usage(path.parent).free except OSError: @@ -14257,15 +14384,23 @@ def _fill_pack(args: argparse.Namespace, plat: str, path: Path, body: bytes, for name, (sha1, size) in sorted(members.items())] detail(f"\nWriting {path.name}...") try: - written = write_pack(path, body, ordered, limit) + result = write_pack(path, body, ordered, limit) except (OSError, PackError) as exc: words = (DRIVE_FULL if isinstance(exc, OSError) and _drive_full(exc) else exc.strerror if isinstance(exc, OSError) and exc.strerror else str(exc)) - print(f"\n {path.name} could not be written: {screen_text(str(words))}. No pack " - "was left behind.", file=sys.stderr) + left = exc.left if isinstance(exc, PackError) else [] + after = ("Left behind, to delete: " + ", ".join(shown_path(f) for f in left) + "." + if left else "No pack was left behind.") + print(f"\n {path.name} could not be written: {screen_text(str(words))}. " + f"{screen_text(after)}", file=sys.stderr) _pack_event(plat, path, members, [], "failed", - f"{path.name} could not be written: {words}.") + f"{path.name} could not be written: {words}. {after}") return 1 + written = result.files + for old in result.removed: + print(f" Removed the earlier {shown_path(old)}.") + for old, why in result.kept: + print(f" {shown_path(old)}: {why}.") size = sum(part.stat().st_size for part in written) print(f"\nPack made: {_plural(len(members), 'file')}, {format_size(size)}" + (f", in {len(written)} parts" if len(written) > 1 else "") + ".") diff --git a/install.sh b/install.sh index d059c2f9c..88de277fe 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="367c20d31846e626baf9ed356bc9456d7a8e35d183ac3f376e4d9b9ba8a5763d" +DEFAULT_INSTALL_SHA256="0eb4260d873e9fa9186fec264a0f4d484707d58daf432d5addbe65feb4912ae2" # 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 0bf3b3e9d..8267e8624 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": 1329206, - "sha256": "367c20d31846e626baf9ed356bc9456d7a8e35d183ac3f376e4d9b9ba8a5763d", + "size": 1335308, + "sha256": "0eb4260d873e9fa9186fec264a0f4d484707d58daf432d5addbe65feb4912ae2", "executable": false }, { @@ -71,8 +71,8 @@ "muos": { "archive": { "dest": "ARCHIVE/RetroBIOS.muxapp", - "size": 1382831, - "sha256": "8de74ce7b0554380b4d2b3ec2702b70c3acdd0b8f8d20cba040366746eac2562" + "size": 1388933, + "sha256": "803dad00f4a44c66d7d6623c8b722ce7797cedb4252ce30283f8cec932b24f16" }, "members": [ { @@ -92,8 +92,8 @@ { "name": "RetroBIOS/install.py", "repo_path": "install.py", - "size": 1329206, - "sha256": "367c20d31846e626baf9ed356bc9456d7a8e35d183ac3f376e4d9b9ba8a5763d", + "size": 1335308, + "sha256": "0eb4260d873e9fa9186fec264a0f4d484707d58daf432d5addbe65feb4912ae2", "executable": false }, { @@ -166,8 +166,8 @@ { "dest": ".config/modules/retrobios/install.py", "repo_path": "install.py", - "size": 1329206, - "sha256": "367c20d31846e626baf9ed356bc9456d7a8e35d183ac3f376e4d9b9ba8a5763d", + "size": 1335308, + "sha256": "0eb4260d873e9fa9186fec264a0f4d484707d58daf432d5addbe65feb4912ae2", "executable": false }, { diff --git a/tests/test_install_pack.py b/tests/test_install_pack.py index 7d410551c..e77b068a9 100644 --- a/tests/test_install_pack.py +++ b/tests/test_install_pack.py @@ -25,6 +25,7 @@ import tempfile import threading import unittest import zipfile +import zlib from pathlib import Path from unittest import mock @@ -439,6 +440,190 @@ class Refusals(Repository): self.assertEqual(pack.platforms(), ["retroarch"]) +def _members(folder: Path, sizes: dict[str, int]) -> list: + """PackMembers of noise files written in folder.""" + folder.mkdir(parents=True, exist_ok=True) + members = [] + for name, size in sorted(sizes.items()): + data = _noise(name, size) + source = folder / name.replace("/", "_") + source.write_bytes(data) + members.append(install.PackMember(name, _sha1(data), len(data), source)) + return members + + +def _folder(path: Path) -> dict[str, bytes]: + return {child.name: child.read_bytes() for child in sorted(path.iterdir())} + + +class TheSwapIsWhole(unittest.TestCase): + """The new files replace the earlier pack of the name as one set: a + failure puts the earlier set back, a cleanup that fails keeps the pack.""" + + def setUp(self): + scratch = REPO_ROOT / "tmp" + scratch.mkdir(exist_ok=True) + self.root = Path(tempfile.mkdtemp(dir=scratch)) + self.addCleanup(shutil.rmtree, self.root, True) + self.out = self.root / "out" + self.out.mkdir() + self.path = self.out / "RetroArch_BIOS_Pack.zip" + + def test_a_rename_that_fails_puts_the_earlier_pack_back(self): + old = install.write_pack(self.path, b"{}", _members(self.root / "a", { + f"f{n}.bin": 24 * 1024 for n in range(3)}), 64 * 1024) + self.assertEqual(len(old.files), 2) + before = _folder(self.out) + real = os.replace + renamed: list[str] = [] + + def refuse_the_second_part(source, target): + if str(source).endswith(".partial"): + renamed.append(str(target)) + if len(renamed) == 2: + raise PermissionError(13, "Permission denied") + return real(source, target) + + new = _members(self.root / "b", {f"g{n}.bin": 24 * 1024 for n in range(5)}) + with mock.patch.object(install.os, "replace", refuse_the_second_part), \ + self.assertRaises(install.PackError) as raised: + install.write_pack(self.path, b"{}", new, 64 * 1024) + self.assertEqual(raised.exception.left, []) + self.assertEqual(_folder(self.out), before) + + def test_a_scratch_file_that_cannot_be_deleted_is_named(self): + source = self.root / "a.bin" + source.write_bytes(b"other bytes") + member = install.PackMember("a.bin", _sha1(b"listed bytes"), 11, source) + real = Path.unlink + + def refuse_partial(path, missing_ok=False): + if path.name.endswith(".partial"): + raise PermissionError(13, "Permission denied") + return real(path, missing_ok=missing_ok) + + with mock.patch.object(install.Path, "unlink", refuse_partial), \ + self.assertRaises(install.PackError) as raised: + install.write_pack(self.path, b"{}", [member], None) + self.assertEqual([path.name.endswith(".partial") for path in raised.exception.left], + [True]) + + def test_a_cleanup_that_fails_keeps_the_pack_written(self): + install.write_pack(self.path, b"{}", _members(self.root / "a", {"a.bin": 1000}), None) + real = Path.unlink + + def refuse_old(path, missing_ok=False): + if path.name.endswith(".old"): + raise PermissionError(13, "Permission denied") + return real(path, missing_ok=missing_ok) + + new = _members(self.root / "b", {f"g{n}.bin": 24 * 1024 for n in range(3)}) + with mock.patch.object(install.Path, "unlink", refuse_old): + written = install.write_pack(self.path, b"{}", new, 64 * 1024) + self.assertEqual(len(written.files), 2) + self.assertTrue(all(path.is_file() for path in written.files)) + self.assertEqual(written.removed, []) + self.assertEqual(len(written.kept), 1) + self.assertTrue(written.kept[0][0].name.endswith(".old")) + + def test_the_earlier_layout_is_removed_and_said(self): + install.write_pack(self.path, b"{}", _members(self.root / "a", {"a.bin": 1000}), None) + written = install.write_pack(self.path, b"{}", _members( + self.root / "b", {f"g{n}.bin": 24 * 1024 for n in range(3)}), 64 * 1024) + self.assertEqual(written.removed, [self.path]) + self.assertEqual(sorted(_folder(self.out)), sorted(f.name for f in written.files)) + + def test_a_file_of_another_pack_under_a_part_name_stays(self): + stranger = self.out / "RetroArch_BIOS_Pack.part1of5.zip" + stranger.write_bytes(b"not a zip") + written = install.write_pack(self.path, b"{}", _members(self.root / "a", + {"a.bin": 1000}), None) + self.assertEqual(stranger.read_bytes(), b"not a zip") + self.assertEqual([path for path, _why in written.kept], [stranger]) + + def test_a_crc_that_does_not_read_back_writes_nothing(self): + with mock.patch.object(install.zipfile.ZipFile, "testzip", return_value="a.bin"), \ + self.assertRaises(install.PackError): + install.write_pack(self.path, b"{}", _members(self.root / "a", + {"a.bin": 1000}), None) + self.assertEqual(_folder(self.out), {}) + + def test_members_are_deflated_at_the_level_named(self): + text = " ".join(f"word{(n * 7919) % 1013}" for n in range(40000)).encode() + source = self.root / "text.bin" + source.write_bytes(text) + + def raw(level: int) -> int: + packer = zlib.compressobj(level, zlib.DEFLATED, -15) + return len(packer.compress(text) + packer.flush()) + + self.assertNotEqual(raw(6), raw(install.PACK_COMPRESSLEVEL)) + install.write_pack(self.path, b"{}", [install.PackMember( + "text.bin", _sha1(text), len(text), source)], None) + with zipfile.ZipFile(self.path) as archive: + self.assertEqual(archive.getinfo("text.bin").compress_size, + raw(install.PACK_COMPRESSLEVEL)) + + +# A drive with little room, the list's tree declaring a large archive. +SPACE_CHILD = """ +import collections, importlib.util, sys +spec = importlib.util.spec_from_file_location("install", {script!r}) +install = importlib.util.module_from_spec(spec) +spec.loader.exec_module(install) +usage = collections.namedtuple("usage", "total used free") +install.shutil.disk_usage = lambda folder: usage(1 << 40, 0, 10 * 1024 * 1024) +sys.argv = ["install.py", *sys.argv[1:]] +install.main() +""" + + +class TheSpaceCountsTheTreeArchive(Repository): + def write_list(self) -> None: + super().write_list() + listed_path = self.served / "install" / "retroarch.json" + listed = json.loads(listed_path.read_text()) + listed["data_directories"][0]["archive_size"] = 50 * 1024 * 1024 + listed_path.write_text(json.dumps(listed)) + + def test_a_drive_without_room_for_the_archive_is_refused(self): + proc = self.run_installer("--pack", f"{self.out}{os.sep}", code=SPACE_CHILD.format( + script=str(REPO_ROOT / "install.py"))) + self.assertEqual(proc.returncode, 2, proc.stdout + proc.stderr) + self.assertIn("has 10.0 MB free", proc.stderr) + self.assertEqual(self.packs(), []) + + def test_the_largest_archive_counts_once(self): + trees = [{"files": {"a": {}}, "archive_size": 300}, + {"files": {"b": {}}, "archive_size": 500}, {"files": {}, "archive_size": 9000}] + self.assertEqual(install.pack_space_bytes(10, 20, trees), 530) + + +class ThePackNamesItsPlatform(Repository): + tree: dict = {} + + def test_a_name_that_spells_another_platform_is_refused(self): + proc = self.run_installer("--pack", str(self.out / "Batocera_BIOS_Pack.zip")) + self.assertEqual(proc.returncode, 2, proc.stdout + proc.stderr) + self.assertIn("names a pack for Batocera, and this one is for RetroArch", proc.stderr) + self.assertEqual(self.packs(), []) + + def test_a_pack_renamed_for_another_platform_is_read_by_its_manifest(self): + self.assertEqual(self.make().returncode, 0) + renamed = self.out / "Batocera_BIOS_Pack.zip" + self.packs()[0].rename(renamed) + pack = install.PackSource([renamed]) + self.addCleanup(pack.close) + self.assertEqual(pack.platforms(), ["retroarch"]) + proc = subprocess.run( + [sys.executable, str(REPO_ROOT / "install.py"), "--platform", "batocera", + "--dest", str(self.root / "x"), "--from-pack", str(renamed), "--yes"], + env=self.env(offline=True), capture_output=True, text=True, timeout=120, + check=False, stdin=subprocess.DEVNULL) + self.assertEqual(proc.returncode, 1, proc.stdout + proc.stderr) + self.assertIn("is a pack for RetroArch, not Batocera", proc.stderr) + + class PartSizes(unittest.TestCase): def test_a_size_reads_as_bytes_or_with_its_unit(self): self.assertEqual(install.parse_part_size("1900M"), 1900 * 1024 ** 2) From b6495f3d59cfc676bc1b59244fe4652609e1021e Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Wed, 11 Nov 2026 18:06:16 +0100 Subject: [PATCH 6/6] docs: describe how a pack takes its name --- wiki/installer.md | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/wiki/installer.md b/wiki/installer.md index 72403a1ae..d5e10633e 100644 --- a/wiki/installer.md +++ b/wiki/installer.md @@ -897,19 +897,27 @@ Without `--dry-run` the run downloads the files, writes the pack and ends on A folder takes the name `_BIOS_Pack.zip`, with `_Custom` when the choice narrows the list. A file name must end with `_BIOS_Pack.zip`, the -name `--from-pack` and the parts read. On the other device, +name `--from-pack` and the parts read, and must not name another platform +(`Batocera_BIOS_Pack.zip` for a RetroArch pack is refused). The reader trusts +the platform the pack's own list names over its file name. On the other device, `--from-pack` on the pack installs the same files at the same places, with no network and no option: the pack's `manifest.json` carries the list narrowed to the choice, the cores per board and every file's SHA-1. A file two places share is stored once, and each data tree sits where the reader looks for it. -Every file is checked against its SHA-1 as it is written into the ZIP, before -the ZIP is closed. The pack is written beside its final name and renamed only -once complete, so a download that fails, a file that does not match or a stop -leaves no file behind, and a pack of the same name written before stays as it -was. The bytes depend on the choice alone: members in a fixed order, a fixed -date and mode, one compression level. Making the pack needs room for the files -and the ZIP together on the drive it goes to. +Every file is checked against its SHA-1 as it is written into the ZIP, and the +ZIP is read back with its CRCs before it takes its name. The pack is written +beside its final name, so a download that fails, a file that does not match or +a stop leaves no file behind. An earlier pack of the same name, whole or in +parts, is set aside while the new files take their names, and put back if one +of them cannot: the folder holds the old pack or the new one, never a mix of +their parts. The earlier files are then deleted and each one is named. A file +of that name that is not a part of this pack stays and is named too. With one +zlib the bytes depend on the choice alone: members in a fixed order, a fixed +date and mode, deflate level 9 on each member. Another deflate (zlib-ng, which +CPython 3.14 ships on Windows) gives other bytes for the same members. Making +the pack needs room for the files, the ZIP and the largest data tree archive +together on the drive it goes to. `--split SIZE` (`1900M`, `4G`) writes parts of at most that size, each a whole ZIP named `.part1of3.zip`, as release packs are split, with the marker