Last active
April 19, 2024 09:10
-
-
Save rindeal/d4915319199b60041f06d6b786759ce6 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env python3.6 | |
## | |
# Copyright 2018 Jan Chren (rindeal) | |
# Distributed under the terms of the GNU General Public License v3 | |
## | |
class _FilesAndDirsGen: | |
_root_tmpdir: tempfile.TemporaryDirectory | |
_defs: typing.Union[dict, set] | |
def __init__(self, defs: typing.Union[dict, set]): | |
self._root_tmpdir = tempfile.TemporaryDirectory() | |
self._defs = defs | |
def __del__(self): | |
self._root_tmpdir.cleanup() | |
def generate(self): | |
def gen_recurse(root: str, defs: typing.Union[dict, set]): | |
if isinstance(defs, set): | |
for f in defs: | |
pathlib.Path(root, f).touch() | |
elif isinstance(defs, dict): | |
for name, val in defs.items(): | |
full_path = os.path.join(root, name) | |
if isinstance(val, dict) or isinstance(val, set): | |
os.mkdir(full_path) | |
gen_recurse(full_path, val) | |
else: | |
with open(full_path, "w") as f: | |
f.write(val) | |
else: | |
raise TypeError("defs") | |
gen_recurse(self._root_tmpdir.name, self._defs) | |
def __enter__(self): | |
self.generate() | |
return self._root_tmpdir.name | |
def __exit__(self, *args): | |
pass | |
defs = { | |
"/foo/bar": "Content written to this file", | |
"/bar/baz": "", | |
} | |
with _FilesAndDirsGen(defs): | |
pass | |
defs = {"/foo/bar", "/bar/baz"} | |
with _FilesAndDirsGen(defs): | |
pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment