pferd/PFERD/tmp_dir.py

80 lines
2.3 KiB
Python
Raw Normal View History

2020-04-20 12:08:52 +02:00
"""Helper functions and classes for temporary folders."""
import logging
2020-04-20 12:08:52 +02:00
import shutil
2020-04-20 14:28:22 +02:00
from pathlib import Path
from types import TracebackType
from typing import Optional, Type
2020-04-20 12:08:52 +02:00
2020-04-23 19:38:28 +02:00
from .location import Location
2020-04-20 15:39:52 +02:00
2020-04-20 19:27:26 +02:00
LOGGER = logging.getLogger(__name__)
2020-04-20 12:08:52 +02:00
2020-04-20 19:27:26 +02:00
class TmpDir(Location):
2020-04-20 12:08:52 +02:00
"""A temporary folder that can create files or nested temp folders."""
2020-04-20 14:28:22 +02:00
def __init__(self, path: Path):
2020-04-20 12:08:52 +02:00
"""Create a new temporary folder for the given path."""
2020-04-20 19:27:26 +02:00
super().__init__(path)
2020-04-20 14:28:22 +02:00
self._counter = 0
self.cleanup()
2020-04-20 19:27:26 +02:00
self.path.mkdir(parents=True, exist_ok=True)
2020-04-20 12:08:52 +02:00
def __str__(self) -> str:
"""Format the folder as a string."""
return f"Folder at {self.path}"
2020-04-20 14:28:22 +02:00
def __enter__(self) -> 'TmpDir':
2020-04-20 12:08:52 +02:00
"""Context manager entry function."""
return self
2020-04-20 19:27:26 +02:00
# pylint: disable=useless-return
def __exit__(
self,
exc_type: Optional[Type[BaseException]],
exc_value: Optional[BaseException],
traceback: Optional[TracebackType],
) -> Optional[bool]:
2020-04-20 12:08:52 +02:00
"""Context manager exit function. Calls cleanup()."""
self.cleanup()
return None
2020-04-23 11:44:13 +02:00
def new_path(self, prefix: Optional[str] = None) -> Path:
"""
Return a unique path inside the directory. Doesn't create a file or
directory.
"""
2020-04-20 14:28:22 +02:00
name = f"{prefix if prefix else 'tmp'}-{self._inc_and_get_counter():03}"
2020-04-20 19:27:26 +02:00
LOGGER.debug("Creating temp file %s", name)
2020-04-20 15:39:52 +02:00
return self.resolve(Path(name))
2020-04-20 12:08:52 +02:00
2020-04-23 11:44:13 +02:00
def new_subdir(self, prefix: Optional[str] = None) -> 'TmpDir':
"""
Create a new nested temporary folder and return it.
"""
2020-04-20 12:08:52 +02:00
2020-04-23 11:44:13 +02:00
name = f"{prefix if prefix else 'tmp'}-{self._inc_and_get_counter():03}"
2020-04-20 15:39:52 +02:00
sub_path = self.resolve(Path(name))
2020-04-20 12:08:52 +02:00
sub_path.mkdir(parents=True)
2020-04-20 19:27:26 +02:00
LOGGER.debug("Creating temp dir %s at %s", name, sub_path)
2020-04-20 14:28:22 +02:00
return TmpDir(sub_path)
2020-04-20 12:08:52 +02:00
def cleanup(self) -> None:
"""Delete this folder and all contained files."""
2020-04-20 19:27:26 +02:00
LOGGER.debug("Deleting temp folder %s", self.path)
if self.path.resolve().exists():
shutil.rmtree(self.path.resolve())
2020-04-20 12:08:52 +02:00
2020-04-20 14:28:22 +02:00
def _inc_and_get_counter(self) -> int:
2020-04-20 12:08:52 +02:00
"""Get and increment the counter by one."""
2020-04-20 14:28:22 +02:00
counter = self._counter
self._counter += 1
2020-04-20 12:08:52 +02:00
return counter