From bf34e7180442ccd0ff021970acf9a470f0e075bf Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Sat, 21 Nov 2026 04:41:18 +0100 Subject: [PATCH] fix: remove the games cache scratch on a failure A cache write that failed left index.json..part behind, one more on each run. The cache and the install record now write through one scratch file beside the target, removed when the write fails and named when it cannot be. --- install.ps1 | 2 +- install.py | 35 ++++++++++++++++++++--------------- install.sh | 2 +- install/launchers/index.json | 16 ++++++++-------- installer/game_files.py | 6 ++---- installer/host_fs.py | 18 ++++++++++++++++++ installer/install_record.py | 16 ++-------------- tests/test_install_games.py | 7 +++++++ 8 files changed, 59 insertions(+), 43 deletions(-) diff --git a/install.ps1 b/install.ps1 index ff222eb4f..fc91e983c 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 = "7dc0b3fa8d59860c05a42e79baffa3e68fea70e5b2204de274d6ccf6ae424171" + $defaultInstallSha256 = "5921275690dded6744c4cc13a2c471cb47e2fe1bac7e8121b285aa0d3973a36b" # 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 f561c5f04..6f448ae4c 100644 --- a/install.py +++ b/install.py @@ -1816,6 +1816,24 @@ def _replace_with_copy(src: Path, dest: Path) -> None: raise +def write_atomically(path: Path, data: bytes) -> None: + """Write data at path through a scratch file beside it, removed when the + write fails; a scratch that cannot be removed is named in the error.""" + fd, scratch = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.", suffix=".part") + try: + with os.fdopen(fd, "wb") as handle: + handle.write(data) + os.replace(scratch, path) + except OSError as exc: + if os.path.lexists(scratch): + try: + os.unlink(scratch) + except OSError as left: + exc.strerror = (f"{exc.strerror or exc}, and {scratch} stays " + f"({left.strerror or left})") + raise + + # FILE_ATTRIBUTE_REPARSE_POINT: a junction, a mount point or a link on Windows. # Before Python 3.12 lstat does not report a junction as a link, and # os.walk(followlinks=False) descends into it. @@ -7890,9 +7908,7 @@ def _cache_write(path: Path, data: bytes) -> None: costs a second read, never the run.""" try: path.parent.mkdir(parents=True, exist_ok=True) - scratch = path.with_name(f"{path.name}.{os.getpid()}.part") - scratch.write_bytes(data) - os.replace(scratch, path) + write_atomically(path, data) except OSError as exc: if os.environ.get("RETROBIOS_DEBUG"): print(f" Not cached: {path} ({exc.strerror or exc})", file=sys.stderr) @@ -9839,23 +9855,12 @@ def _save_record(folder: Path, data: dict, found: Path | None) -> tuple[Path | N places = [found] + [place for place in places if place != found] failure = "nothing could be written beside the folder" for path in places: - scratch: Path | None = None try: path.parent.mkdir(exist_ok=True) _check_holder(path.parent) - with tempfile.NamedTemporaryFile( - "w", encoding="utf-8", dir=path.parent, prefix=f".{path.name}.", - suffix=".part", delete=False) as handle: - scratch = Path(handle.name) - handle.write(text) - os.replace(scratch, path) + write_atomically(path, text.encode("utf-8")) except OSError as exc: failure = exc.strerror or str(exc) - if scratch is not None and os.path.lexists(scratch): - try: - scratch.unlink() - except OSError as left: - failure += f", and {scratch} stays ({left.strerror or left})" continue return path, "" return None, failure diff --git a/install.sh b/install.sh index 72843a1ea..3a71bebe3 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="7dc0b3fa8d59860c05a42e79baffa3e68fea70e5b2204de274d6ccf6ae424171" +DEFAULT_INSTALL_SHA256="5921275690dded6744c4cc13a2c471cb47e2fe1bac7e8121b285aa0d3973a36b" # 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 4b7d4857a..38e45bc16 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": 1450806, - "sha256": "7dc0b3fa8d59860c05a42e79baffa3e68fea70e5b2204de274d6ccf6ae424171", + "size": 1450902, + "sha256": "5921275690dded6744c4cc13a2c471cb47e2fe1bac7e8121b285aa0d3973a36b", "executable": false }, { @@ -71,8 +71,8 @@ "muos": { "archive": { "dest": "ARCHIVE/RetroBIOS.muxapp", - "size": 1504431, - "sha256": "ae2c3d83d3ef556166787f9d86ff3aa4aa51fd069211c2052c9935f2c1e29219" + "size": 1504527, + "sha256": "657b9c3a63251ef77487ca4e819a66b48219163c36e46d4e53f503f16d9d7ade" }, "members": [ { @@ -92,8 +92,8 @@ { "name": "RetroBIOS/install.py", "repo_path": "install.py", - "size": 1450806, - "sha256": "7dc0b3fa8d59860c05a42e79baffa3e68fea70e5b2204de274d6ccf6ae424171", + "size": 1450902, + "sha256": "5921275690dded6744c4cc13a2c471cb47e2fe1bac7e8121b285aa0d3973a36b", "executable": false }, { @@ -166,8 +166,8 @@ { "dest": ".config/modules/retrobios/install.py", "repo_path": "install.py", - "size": 1450806, - "sha256": "7dc0b3fa8d59860c05a42e79baffa3e68fea70e5b2204de274d6ccf6ae424171", + "size": 1450902, + "sha256": "5921275690dded6744c4cc13a2c471cb47e2fe1bac7e8121b285aa0d3973a36b", "executable": false }, { diff --git a/installer/game_files.py b/installer/game_files.py index dde494c8f..1bcfa2d56 100644 --- a/installer/game_files.py +++ b/installer/game_files.py @@ -12,7 +12,7 @@ from pathlib import Path from typing import NamedTuple from installer.cards import games_part -from installer.host_fs import _is_dir +from installer.host_fs import _is_dir, write_atomically from installer.network import _read_capped CACHE_VARIABLE = "RETROBIOS_CACHE" @@ -64,9 +64,7 @@ def _cache_write(path: Path, data: bytes) -> None: costs a second read, never the run.""" try: path.parent.mkdir(parents=True, exist_ok=True) - scratch = path.with_name(f"{path.name}.{os.getpid()}.part") - scratch.write_bytes(data) - os.replace(scratch, path) + write_atomically(path, data) except OSError as exc: if os.environ.get("RETROBIOS_DEBUG"): print(f" Not cached: {path} ({exc.strerror or exc})", file=sys.stderr) diff --git a/installer/host_fs.py b/installer/host_fs.py index 7969ca331..7659ffed2 100644 --- a/installer/host_fs.py +++ b/installer/host_fs.py @@ -239,6 +239,24 @@ def _replace_with_copy(src: Path, dest: Path) -> None: raise +def write_atomically(path: Path, data: bytes) -> None: + """Write data at path through a scratch file beside it, removed when the + write fails; a scratch that cannot be removed is named in the error.""" + fd, scratch = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.", suffix=".part") + try: + with os.fdopen(fd, "wb") as handle: + handle.write(data) + os.replace(scratch, path) + except OSError as exc: + if os.path.lexists(scratch): + try: + os.unlink(scratch) + except OSError as left: + exc.strerror = (f"{exc.strerror or exc}, and {scratch} stays " + f"({left.strerror or left})") + raise + + # FILE_ATTRIBUTE_REPARSE_POINT: a junction, a mount point or a link on Windows. # Before Python 3.12 lstat does not report a junction as a link, and # os.walk(followlinks=False) descends into it. diff --git a/installer/install_record.py b/installer/install_record.py index 4860e443b..51c7767f2 100644 --- a/installer/install_record.py +++ b/installer/install_record.py @@ -9,14 +9,13 @@ import os import re import stat import sys -import tempfile from collections.abc import Callable, Iterable from pathlib import Path, PurePosixPath from typing import NamedTuple from installer.arguments import build_parser from installer.events import EVENTS -from installer.host_fs import _clear_read_only, _is_dir, _is_link, _replace_with_copy +from installer.host_fs import _clear_read_only, _is_dir, _is_link, _replace_with_copy, write_atomically from installer.invocation import _INVOCATION, _VALUED_OPTIONS, _command_rank, installer_id from installer.local_check import _digest_file from installer.offline import LOCAL @@ -345,23 +344,12 @@ def _save_record(folder: Path, data: dict, found: Path | None) -> tuple[Path | N places = [found] + [place for place in places if place != found] failure = "nothing could be written beside the folder" for path in places: - scratch: Path | None = None try: path.parent.mkdir(exist_ok=True) _check_holder(path.parent) - with tempfile.NamedTemporaryFile( - "w", encoding="utf-8", dir=path.parent, prefix=f".{path.name}.", - suffix=".part", delete=False) as handle: - scratch = Path(handle.name) - handle.write(text) - os.replace(scratch, path) + write_atomically(path, text.encode("utf-8")) except OSError as exc: failure = exc.strerror or str(exc) - if scratch is not None and os.path.lexists(scratch): - try: - scratch.unlink() - except OSError as left: - failure += f", and {scratch} stays ({left.strerror or left})" continue return path, "" return None, failure diff --git a/tests/test_install_games.py b/tests/test_install_games.py index 2bc52809d..d82ec5f22 100644 --- a/tests/test_install_games.py +++ b/tests/test_install_games.py @@ -758,6 +758,13 @@ class Cache(GamesTestCase): self.assertEqual(len(counted), 2) self.assertEqual(plan.games[0].dat_regions, frozenset({"japan"})) + def test_a_cache_write_that_fails_leaves_no_scratch(self): + # Each failing run left one index.json..part beside the cache. + cached = self.card.cache / "games" + (cached / "index.json").mkdir(parents=True) + install._cache_write(cached / "index.json", b"{}") + self.assertEqual([p.name for p in cached.iterdir()], ["index.json"]) + def test_the_index_is_cached_and_read_offline_without_the_list_beside_it(self): self.card.game("MD", "eu.md", MD_EU) index = (self.card.lists / "games" / "index.json").read_bytes()