Skip to content

Commit 0cad9c5

Browse files
committed
feat(processing): add unblob dedicated temporary directory handling
1 parent 1965107 commit 0cad9c5

File tree

3 files changed

+23
-0
lines changed

3 files changed

+23
-0
lines changed

python/unblob/processing.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
1+
import atexit
12
import multiprocessing
3+
import os
24
import shutil
35
from collections.abc import Iterable, Sequence
46
from operator import attrgetter
57
from pathlib import Path
8+
import tempfile
69
from typing import Optional, Union
710

811
import attrs
@@ -100,6 +103,21 @@ class ExtractionConfig:
100103
dir_handlers: DirectoryHandlers = BUILTIN_DIR_HANDLERS
101104
verbose: int = 1
102105
progress_reporter: type[ProgressReporter] = NullProgressReporter
106+
tmp_dir: Path = attrs.field(factory=lambda: Path(tempfile.mkdtemp(prefix="unblob-tmp-")))
107+
108+
def __attrs_post_init__(self):
109+
"""Set environment variables so all subprocesses and handlers use our temp dir"""
110+
for var in ("TMP", "TMPDIR", "TEMP", "TEMPDIR"):
111+
os.environ[var] = self.tmp_dir.as_posix()
112+
atexit.register(self._cleanup_tmp_dir)
113+
114+
def _cleanup_tmp_dir(self):
115+
"""Remove the temp directory and its contents at the end of the run"""
116+
if self.tmp_dir.exists():
117+
try:
118+
shutil.rmtree(self.tmp_dir)
119+
except Exception as e:
120+
logger.warning("Failed to clean up tmp_dir", tmp_dir=self.tmp_dir, exc_info=e)
103121

104122
def _get_output_path(self, path: Path) -> Path:
105123
"""Return path under extract root."""

python/unblob/sandbox.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,10 @@ def __init__(
5555
AccessFS.remove_file(config.extract_root),
5656
AccessFS.make_dir(config.extract_root.parent),
5757
AccessFS.read_write(log_path),
58+
# Allow access to the managed temp directory for handlers
59+
AccessFS.read_write(config.tmp_dir),
60+
AccessFS.remove_dir(config.tmp_dir),
61+
AccessFS.remove_file(config.tmp_dir),
5862
*extra_passthrough,
5963
]
6064

tests/test_cli.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
from collections.abc import Iterable
22
from pathlib import Path
3+
import tempfile
34
from typing import Optional
45
from unittest import mock
56

0 commit comments

Comments
 (0)