launcher: Clear shader cache resolves a relative cache dir as the runtime does and never deletes saves, the game or Mandy

merzleckeier's P1 on 29085dbf2: an Advanced LEONIDA_CACHE_DIR that is
relative was resolved from the GUI's working directory, while the runtime
resolves it from where it starts (d3d12 on Windows, where play-nvidia.ps1
pushes; the checkout on Linux, where play-linux.sh starts), so Tools could
pick another existing folder; and the typed value was the recursive
deletion target as it stood.

- shader_cache_dir makes a typed value absolute from that base (~ expanded),
  one path for the confirmation and the deletion.
- cache_dir_problem refuses a drive's root, a folder that holds the home
  folder or the data folder, and any folder that holds or sits in the saves
  (<data>/data), the game folder or Mandy's own folder. The default cache
  (<data>/cache-2, beside the saves) stays allowed. Clear shader cache says
  why and deletes nothing; the window warns before any confirmation.

Tests: CacheDirGuardTests (a relative value made absolute per system and,
being inside Mandy's folder, refused; Data, Data/data, the saves, Game, a
folder under Game, the parent of both, Mandy's folder, d3d12, the home
folder and the root all refused with the saves and the game file intact; a
cache elsewhere cleared; the default cache allowed). 141 OK; new texts in
de/es/fr/pt. Counter-test with the guard off (removal stubbed, nothing
deleted): both tests fail.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
OreoFR
2026-12-03 04:46:07 +01:00
parent 29085dbf2b
commit 69925a7c0c
6 changed files with 98 additions and 5 deletions

View File

@ -1012,6 +1012,53 @@ class NoControlCharactersTests(unittest.TestCase):
self.assertEqual(found, [])
class CacheDirGuardTests(unittest.TestCase):
"""Clear shader cache with an Advanced LEONIDA_CACHE_DIR (review of #3272, P1): a relative value is made absolute
from where the runtime starts, and a path that holds or sits in the saves, the game, Mandy's folder, the data
folder or the home folder, or a drive's root, is never deleted."""
def settings(self, tmp, cache):
return launcher.normalise({"data_dir": os.path.join(tmp, "Data"), "game_dir": os.path.join(tmp, "Game"),
"advanced": f"LEONIDA_CACHE_DIR={cache}"})
def test_relative_is_made_absolute_from_where_the_runtime_starts(self):
with tempfile.TemporaryDirectory() as tmp:
s = self.settings(tmp, "my-cache")
self.assertEqual(launcher.shader_cache_dir(s, windows=True),
os.path.normpath(os.path.join(launcher.REPO, "d3d12", "my-cache")))
self.assertEqual(launcher.shader_cache_dir(s, windows=False),
os.path.normpath(os.path.join(launcher.REPO, "my-cache")))
# Inside Mandy's own folder: refused, nothing deleted.
done, message = launcher.clear_shader_cache(s, running=lambda: False, windows=True)
self.assertFalse(done)
self.assertIn("not deleted", message)
def test_overlapping_folders_are_refused(self):
with tempfile.TemporaryDirectory() as tmp:
for rel in ("Data/data/saves/x/0", "Game/game_scarlett_master.exe", "elsewhere/cache/a.bin"):
path = os.path.join(tmp, *rel.split("/"))
os.makedirs(os.path.dirname(path), exist_ok=True)
open(path, "wb").close()
for cache in (os.path.join(tmp, "Data"), os.path.join(tmp, "Data", "data"),
os.path.join(tmp, "Data", "data", "saves"), os.path.join(tmp, "Game"),
os.path.join(tmp, "Game", "sub"), tmp, launcher.REPO,
os.path.join(launcher.REPO, "d3d12"), os.path.expanduser("~"),
os.path.abspath(os.sep)):
s = self.settings(tmp, cache)
done, message = launcher.clear_shader_cache(s, running=lambda: False, windows=True)
self.assertFalse(done, cache)
self.assertTrue(os.path.isfile(os.path.join(tmp, "Data", "data", "saves", "x", "0")), cache)
self.assertTrue(os.path.isfile(os.path.join(tmp, "Game", "game_scarlett_master.exe")), cache)
# A cache of its own elsewhere is cleared.
s = self.settings(tmp, os.path.join(tmp, "elsewhere", "cache"))
done, message = launcher.clear_shader_cache(s, running=lambda: False, windows=True)
self.assertTrue(done, message)
self.assertFalse(os.path.exists(os.path.join(tmp, "elsewhere", "cache")))
# The default cache beside the saves stays allowed.
self.assertIsNone(launcher.cache_dir_problem(os.path.join(tmp, "Data", "cache-2"),
launcher.normalise({"data_dir": os.path.join(tmp, "Data")})))
class OutputPumpTests(unittest.TestCase):
"""Issue #3175: with -Log off the runtime's stderr comes through the pipe, and the window's pump drained the whole
queue in one turn with one insert per line, so the window stopped answering clicks while it caught up."""

View File

@ -397,5 +397,7 @@
"AMD's FidelityFX files": "AMDs FidelityFX-Dateien",
"Not every file could be downloaded: the game starts without them (Tools can fetch them later).": "Nicht alle Dateien konnten geladen werden: das Spiel startet ohne sie (Werkzeuge kann sie später holen).",
"AMD's FSR 3 files are not here yet: PLAY downloads them first (about 29 MB).": "AMDs FSR-3-Dateien sind noch nicht da: PLAY lädt sie zuerst (etwa 29 MB).",
"AMD's FSR 3 files are not here, so FSR 3 stays off: Tools > Fetch AMD FidelityFX files.": "AMDs FSR-3-Dateien sind nicht da, also bleibt FSR 3 aus: Werkzeuge > AMD-FidelityFX-Dateien holen."
"AMD's FSR 3 files are not here, so FSR 3 stays off: Tools > Fetch AMD FidelityFX files.": "AMDs FSR-3-Dateien sind nicht da, also bleibt FSR 3 aus: Werkzeuge > AMD-FidelityFX-Dateien holen.",
"{path} is a drive's root.": "{path} ist das Stammverzeichnis eines Laufwerks.",
"{path} holds or is inside {folder}: it is not deleted. Clear it by hand if you are sure.": "{path} enthält {folder} oder liegt darin: es wird nicht gelöscht. Leere es von Hand, wenn du sicher bist."
}

View File

@ -397,5 +397,7 @@
"AMD's FidelityFX files": "los archivos FidelityFX de AMD",
"Not every file could be downloaded: the game starts without them (Tools can fetch them later).": "No se pudieron descargar todos los archivos: el juego empieza sin ellos (Herramientas puede obtenerlos luego).",
"AMD's FSR 3 files are not here yet: PLAY downloads them first (about 29 MB).": "Los archivos FSR 3 de AMD aún no están: PLAY los descarga primero (unos 29 MB).",
"AMD's FSR 3 files are not here, so FSR 3 stays off: Tools > Fetch AMD FidelityFX files.": "Los archivos FSR 3 de AMD no están, así que FSR 3 sigue desactivado: Herramientas > Obtener los archivos AMD FidelityFX."
"AMD's FSR 3 files are not here, so FSR 3 stays off: Tools > Fetch AMD FidelityFX files.": "Los archivos FSR 3 de AMD no están, así que FSR 3 sigue desactivado: Herramientas > Obtener los archivos AMD FidelityFX.",
"{path} is a drive's root.": "{path} es la raíz de una unidad.",
"{path} holds or is inside {folder}: it is not deleted. Clear it by hand if you are sure.": "{path} contiene {folder} o está dentro: no se borra. Vacíalo a mano si estás seguro."
}

View File

@ -397,5 +397,7 @@
"AMD's FidelityFX files": "les fichiers FidelityFX d'AMD",
"Not every file could be downloaded: the game starts without them (Tools can fetch them later).": "Tous les fichiers n'ont pas pu être téléchargés : le jeu démarre sans eux (Outils peut les récupérer plus tard).",
"AMD's FSR 3 files are not here yet: PLAY downloads them first (about 29 MB).": "Les fichiers FSR 3 d'AMD ne sont pas encore là : PLAY les télécharge d'abord (environ 29 Mo).",
"AMD's FSR 3 files are not here, so FSR 3 stays off: Tools > Fetch AMD FidelityFX files.": "Les fichiers FSR 3 d'AMD ne sont pas là, donc FSR 3 reste désactivé : Outils > Récupérer les fichiers AMD FidelityFX."
"AMD's FSR 3 files are not here, so FSR 3 stays off: Tools > Fetch AMD FidelityFX files.": "Les fichiers FSR 3 d'AMD ne sont pas là, donc FSR 3 reste désactivé : Outils > Récupérer les fichiers AMD FidelityFX.",
"{path} is a drive's root.": "{path} est la racine d'un disque.",
"{path} holds or is inside {folder}: it is not deleted. Clear it by hand if you are sure.": "{path} contient {folder} ou se trouve dedans : il n'est pas supprimé. Videz-le à la main si vous êtes sûr."
}

View File

@ -397,5 +397,7 @@
"AMD's FidelityFX files": "os arquivos FidelityFX da AMD",
"Not every file could be downloaded: the game starts without them (Tools can fetch them later).": "Nem todos os arquivos puderam ser baixados: o jogo começa sem eles (Ferramentas pode obtê-los depois).",
"AMD's FSR 3 files are not here yet: PLAY downloads them first (about 29 MB).": "Os arquivos FSR 3 da AMD ainda não estão aqui: o PLAY os baixa primeiro (cerca de 29 MB).",
"AMD's FSR 3 files are not here, so FSR 3 stays off: Tools > Fetch AMD FidelityFX files.": "Os arquivos FSR 3 da AMD não estão aqui, então o FSR 3 fica desligado: Ferramentas > Obter os arquivos AMD FidelityFX."
"AMD's FSR 3 files are not here, so FSR 3 stays off: Tools > Fetch AMD FidelityFX files.": "Os arquivos FSR 3 da AMD não estão aqui, então o FSR 3 fica desligado: Ferramentas > Obter os arquivos AMD FidelityFX.",
"{path} is a drive's root.": "{path} é a raiz de uma unidade.",
"{path} holds or is inside {folder}: it is not deleted. Clear it by hand if you are sure.": "{path} contém {folder} ou está dentro dele: não é apagado. Limpe-o à mão se tiver certeza."
}

View File

@ -1789,7 +1789,11 @@ def shader_cache_dir(settings: dict, windows: bool = WINDOWS, environ=None) -> s
# value; the environment of play-linux.sh), so the cache PLAY uses is that one (review of #3272).
typed = parse_advanced(settings.get("advanced", ""))[0].get("LEONIDA_CACHE_DIR", "").strip()
if typed:
return typed
# Relative to where the runtime starts: play-nvidia.ps1 pushes into d3d12\ before it (Windows), the launcher
# starts play-linux.sh in the checkout (Linux). One absolute path for the confirmation and the deletion
# (review of #3272).
base = os.path.join(REPO, "d3d12") if windows else REPO
return os.path.normpath(os.path.join(base, os.path.expanduser(typed)))
if windows:
return os.path.join(data_root(settings), SHADER_CACHE)
env = os.environ if environ is None else environ
@ -1819,12 +1823,42 @@ def size_text(n: int) -> str:
return f"{n} B"
def _inside(path: str, folder: str) -> bool:
"""Whether `path` is `folder` or under it (both made absolute, links resolved, case as the system compares)."""
a, b = (os.path.normcase(os.path.realpath(x)) for x in (path, folder))
try:
return os.path.commonpath([a, b]) == b
except ValueError: # other drives
return False
def cache_dir_problem(path: str, settings: dict, windows: bool = WINDOWS) -> str | None:
"""Why `path` must not be deleted as the shader cache, or None. Clear shader cache deletes it whole, and an
Advanced LEONIDA_CACHE_DIR makes it whatever was typed: a drive's root, the home folder, or a folder that holds or
sits in the saves, the game, Mandy's own folder or the data folder is refused (review of #3272)."""
full = os.path.realpath(path)
if os.path.dirname(full) == full:
return t("{path} is a drive's root.", path=full)
guarded = [(os.path.expanduser("~"), False), (REPO, True), (settings.get("game_dir", "").strip(), True),
(os.path.join(data_root(settings), "data"), True), (data_root(settings), False)]
for folder, both_ways in guarded:
if not folder:
continue
if _inside(folder, full) or (both_ways and _inside(full, folder)):
return t("{path} holds or is inside {folder}: it is not deleted. Clear it by hand if you are sure.",
path=full, folder=os.path.realpath(folder))
return None
def clear_shader_cache(settings: dict, running=None, windows: bool = WINDOWS) -> tuple[bool, str]:
"""Tools > Clear shader cache: deletes the data folder's cache-2 (shader_cache_dir), nothing else, the saves in
<data>/data included; the next start makes it again. Refused while the game runs. (done, message)."""
if (running or game_running)():
return False, t("Close the game first: its cache is in use.")
path = shader_cache_dir(settings, windows=windows)
problem = cache_dir_problem(path, settings, windows=windows)
if problem:
return False, problem
if not os.path.isdir(path):
return True, t("The shader cache is already empty.")
try:
@ -4915,6 +4949,10 @@ def run_gui() -> int:
messagebox.showinfo(t("Clear shader cache"), t("Close the game first: its cache is in use."))
return
path = shader_cache_dir(self.settings)
problem = cache_dir_problem(path, self.settings)
if problem:
messagebox.showwarning(t("Clear shader cache"), problem)
return
if not os.path.isdir(path):
messagebox.showinfo(t("Clear shader cache"), t("The shader cache is already empty."))
return