Add a simple temporary folder

This commit is contained in:
I-Al-Istannen 2020-04-20 12:08:52 +02:00
parent d5dd5aac06
commit 8c431c7d81
3 changed files with 65 additions and 5 deletions

2
.gitignore vendored
View File

@ -2,3 +2,5 @@ __pycache__/
.venv/ .venv/
.mypy_cache/ .mypy_cache/
.tmp/ .tmp/
.env
.vscode

View File

@ -1,7 +1,8 @@
import logging import logging
from .ilias import * # from .ilias import *
from .utils import * # from .utils import *
from .temp_folder import *
STYLE = "{" STYLE = "{"
FORMAT = "[{levelname:<7}] {message}" FORMAT = "[{levelname:<7}] {message}"
@ -13,6 +14,7 @@ FORMATTER = logging.Formatter(
style=STYLE, style=STYLE,
) )
def enable_logging(name: str = "PFERD", level: int = logging.INFO) -> None: def enable_logging(name: str = "PFERD", level: int = logging.INFO) -> None:
handler = logging.StreamHandler() handler = logging.StreamHandler()
handler.setFormatter(FORMATTER) handler.setFormatter(FORMATTER)

56
PFERD/temp_folder.py Normal file
View File

@ -0,0 +1,56 @@
"""Helper functions and classes for temporary folders."""
from typing import Optional, Type
from types import TracebackType
import pathlib
import shutil
class TempFolder():
"""A temporary folder that can create files or nested temp folders."""
def __init__(self, path: pathlib.Path):
"""Create a new temporary folder for the given path."""
self.counter = 0
self.path = path
def __str__(self) -> str:
"""Format the folder as a string."""
return f"Folder at {self.path}"
def __enter__(self) -> 'TempFolder':
"""Context manager entry function."""
return self
def __exit__(self,
type: Optional[Type[BaseException]],
value: Optional[BaseException],
traceback: Optional[TracebackType]) -> Optional[bool]:
"""Context manager exit function. Calls cleanup()."""
self.cleanup()
return None
def new_file(self) -> pathlib.Path:
"""Return a unique path inside the folder, but don't create a file."""
name = f"tmp-{self.__inc_and_get_counter():03}"
return self.path.joinpath(name)
def new_folder(self, prefix: str = "") -> 'TempFolder':
"""Create a new nested temporary folder and return its path."""
name = f"{prefix if prefix else 'tmp'}-{self.__inc_and_get_counter():03}"
sub_path = self.path.joinpath(name)
sub_path.mkdir(parents=True)
return TempFolder(sub_path)
def cleanup(self) -> None:
"""Delete this folder and all contained files."""
shutil.rmtree(self.path.absolute())
def __inc_and_get_counter(self) -> int:
"""Get and increment the counter by one."""
counter = self.counter
self.counter += 1
return counter