-
Notifications
You must be signed in to change notification settings - Fork 802
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Signed-off-by: Frost Ming <[email protected]>
- Loading branch information
Showing
3 changed files
with
53 additions
and
5 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
from __future__ import annotations | ||
|
||
import shutil | ||
import tempfile | ||
from collections import deque | ||
from functools import partial | ||
from pathlib import Path | ||
from threading import Lock | ||
|
||
|
||
class TempfilePool: | ||
"""A simple pool to get temp directories | ||
so they are reused as most as possible. | ||
""" | ||
|
||
def __init__( | ||
self, | ||
suffix: str | None = None, | ||
prefix: str | None = None, | ||
dir: str | None = None, | ||
) -> None: | ||
self._pool: deque[str] = deque([]) | ||
self._lock = Lock() | ||
self._new = partial(tempfile.mkdtemp, suffix=suffix, prefix=prefix, dir=dir) | ||
|
||
def cleanup(self) -> None: | ||
while len(self._pool): | ||
dir = self._pool.popleft() | ||
shutil.rmtree(dir, ignore_errors=True) | ||
|
||
def acquire(self) -> str: | ||
with self._lock: | ||
if not len(self._pool): | ||
return self._new() | ||
else: | ||
return self._pool.popleft() | ||
|
||
def release(self, dir: str) -> None: | ||
with self._lock: | ||
for child in Path(dir).iterdir(): | ||
if child.is_dir(): | ||
shutil.rmtree(child) | ||
else: | ||
child.unlink() | ||
self._pool.append(dir) |