Coverage for src/romfarmer/engine/scratch.py: 100%
17 statements
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-05 02:19 -0700
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-05 02:19 -0700
1"""Scratch directory lifecycle for per-unit work areas.
3Each :class:`ScratchDir` context manager creates a temporary directory,
4yields it to the caller, and deletes it on exit — regardless of whether
5the unit succeeded or failed. The peak-disk cap from the legacy pipeline
6is preserved via the optional *peak_cap* argument (enforcement is the
7caller's responsibility; ``ScratchDir`` only deletes the directory on
8exit, it does not enforce limits mid-run).
9"""
11from __future__ import annotations
13import shutil
14from pathlib import Path
15from types import TracebackType
18class ScratchDir:
19 """Context manager for a per-unit scratch directory.
21 Example::
23 with ScratchDir(base, unit_id) as scratch:
24 output = transform.run(inputs, params, scratch)
25 """
27 def __init__(
28 self,
29 base_dir: Path,
30 unit_id: str,
31 *,
32 peak_cap: int | None = None,
33 ) -> None:
34 """
35 Args:
36 base_dir: Parent directory under which the scratch dir is created.
37 unit_id: Stable identifier (e.g. ``unit.unit_id``) used to name
38 the scratch dir. Sanitized to be filesystem-safe.
39 peak_cap: Soft maximum bytes allowed in ``base_dir`` while this
40 scratch dir exists. Not enforced by ``ScratchDir``
41 itself — intended for callers to check before invoking
42 transforms.
43 """
44 safe_id = unit_id[:64].replace("/", "_").replace("\x00", "_")
45 self.path: Path = base_dir / f"scratch_{safe_id}"
46 self.peak_cap = peak_cap
47 self._entered = False
49 def __enter__(self) -> Path:
50 self.path.mkdir(parents=True, exist_ok=True)
51 self._entered = True
52 return self.path
54 def __exit__(
55 self,
56 exc_type: type[BaseException] | None,
57 exc_val: BaseException | None,
58 exc_tb: TracebackType | None,
59 ) -> None:
60 if self._entered:
61 shutil.rmtree(self.path, ignore_errors=True)