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] 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)