Coverage for src/lilbee/runtime/onefile_cache.py: 100%
36 statements
« prev ^ index » next coverage.py v7.15.2, created at 2026-09-17 10:02 +0000
« prev ^ index » next coverage.py v7.15.2, created at 2026-09-17 10:02 +0000
1"""Startup sweep of the onefile extraction directories left by older releases."""
3from __future__ import annotations
5import logging
6import shutil
7from pathlib import Path
9import lilbee
10from lilbee._frozen import is_frozen
12logger = logging.getLogger(__name__)
14# Written by tools/wheel-build/onefile-bootstrap-lilbee.patch into every payload directory.
15BOOTSTRAP_MANIFEST_NAME = ".lilbee-bootstrap-manifest"
16# Payload directories are named ``{VERSION}-<build key>`` by the build script.
17_BUILD_KEY_SEPARATOR = "-"
20def _extraction_dir() -> Path:
21 """The payload directory of the running binary; the compiled package sits directly inside it."""
22 return Path(lilbee.__file__).resolve().parent.parent
25def _release_version(directory: Path) -> str:
26 return directory.name.partition(_BUILD_KEY_SEPARATOR)[0]
29def _stale_siblings(running: Path) -> list[Path]:
30 """Payload directories beside *running* that another release wrote."""
31 running_version = _release_version(running)
32 return [
33 path
34 for path in running.parent.iterdir()
35 if path != running
36 and _release_version(path) != running_version
37 and (path / BOOTSTRAP_MANIFEST_NAME).is_file()
38 ]
41def _remove(path: Path) -> bool:
42 try:
43 shutil.rmtree(path)
44 except OSError as exc:
45 logger.debug("Left the onefile cache %s in place: %s", path, exc)
46 return False
47 return True
50def remove_stale_extractions(running: Path) -> list[Path]:
51 """Delete the payload directories of other releases beside *running*; never raises."""
52 try:
53 stale = _stale_siblings(running)
54 except OSError as exc:
55 logger.debug("Skipped the onefile cache sweep of %s: %s", running.parent, exc)
56 return []
57 removed = [path for path in stale if _remove(path)]
58 if removed:
59 logger.info("Removed the onefile cache of older releases: %s", ", ".join(map(str, removed)))
60 return removed
63def cleanup_stale_onefile_caches() -> None:
64 """Startup hook; a no-op outside the compiled binary."""
65 if is_frozen():
66 remove_stale_extractions(_extraction_dir())