1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
|
import os
import shutil
import tempfile
from typing import Any
import confuse
def _root(*sources: dict[str, Any]) -> confuse.RootView:
return confuse.RootView([confuse.ConfigSource.of(s) for s in sources])
class TempDir:
"""Context manager that creates and destroys a temporary directory."""
def __init__(self):
self.path = tempfile.mkdtemp()
def __enter__(self):
return self
def __exit__(self, *errstuff):
shutil.rmtree(self.path)
def sub(self, name, contents=None):
"""Get a path to a file named `name` inside this temporary
directory. If `contents` is provided, then the bytestring is
written to the file.
"""
path = os.path.join(self.path, name)
if contents:
with open(path, "wb") as f:
f.write(contents)
return path
|