| 1 |
import pathlib |
| 2 |
import functools |
| 3 |
|
| 4 |
from typing import Dict, Union |
| 5 |
from typing import runtime_checkable |
| 6 |
from typing import Protocol |
| 7 |
|
| 8 |
|
| 9 |
#### |
| 10 |
# from jaraco.path 3.7.1 |
| 11 |
|
| 12 |
|
| 13 |
class Symlink(str): |
| 14 |
""" |
| 15 |
A string indicating the target of a symlink. |
| 16 |
""" |
| 17 |
|
| 18 |
|
| 19 |
FilesSpec = Dict[str, Union[str, bytes, Symlink, 'FilesSpec']] |
| 20 |
|
| 21 |
|
| 22 |
@runtime_checkable |
| 23 |
class TreeMaker(Protocol): |
| 24 |
def __truediv__(self, *args, **kwargs): ... # pragma: no cover |
| 25 |
|
| 26 |
def mkdir(self, **kwargs): ... # pragma: no cover |
| 27 |
|
| 28 |
def write_text(self, content, **kwargs): ... # pragma: no cover |
| 29 |
|
| 30 |
def write_bytes(self, content): ... # pragma: no cover |
| 31 |
|
| 32 |
def symlink_to(self, target): ... # pragma: no cover |
| 33 |
|
| 34 |
|
| 35 |
def _ensure_tree_maker(obj: Union[str, TreeMaker]) -> TreeMaker: |
| 36 |
return obj if isinstance(obj, TreeMaker) else pathlib.Path(obj) # type: ignore[return-value] |
| 37 |
|
| 38 |
|
| 39 |
def build( |
| 40 |
spec: FilesSpec, |
| 41 |
prefix: Union[str, TreeMaker] = pathlib.Path(), # type: ignore[assignment] |
| 42 |
): |
| 43 |
""" |
| 44 |
Build a set of files/directories, as described by the spec. |
| 45 |
|
| 46 |
Each key represents a pathname, and the value represents |
| 47 |
the content. Content may be a nested directory. |
| 48 |
|
| 49 |
>>> spec = { |
| 50 |
... 'README.txt': "A README file", |
| 51 |
... "foo": { |
| 52 |
... "__init__.py": "", |
| 53 |
... "bar": { |
| 54 |
... "__init__.py": "", |
| 55 |
... }, |
| 56 |
... "baz.py": "# Some code", |
| 57 |
... "bar.py": Symlink("baz.py"), |
| 58 |
... }, |
| 59 |
... "bing": Symlink("foo"), |
| 60 |
... } |
| 61 |
>>> target = getfixture('tmp_path') |
| 62 |
>>> build(spec, target) |
| 63 |
>>> target.joinpath('foo/baz.py').read_text(encoding='utf-8') |
| 64 |
'# Some code' |
| 65 |
>>> target.joinpath('bing/bar.py').read_text(encoding='utf-8') |
| 66 |
'# Some code' |
| 67 |
""" |
| 68 |
for name, contents in spec.items(): |
| 69 |
create(contents, _ensure_tree_maker(prefix) / name) |
| 70 |
|
| 71 |
|
| 72 |
@functools.singledispatch |
| 73 |
def create(content: Union[str, bytes, FilesSpec], path): |
| 74 |
path.mkdir(exist_ok=True) |
| 75 |
build(content, prefix=path) # type: ignore[arg-type] |
| 76 |
|
| 77 |
|
| 78 |
@create.register |
| 79 |
def _(content: bytes, path): |
| 80 |
path.write_bytes(content) |
| 81 |
|
| 82 |
|
| 83 |
@create.register |
| 84 |
def _(content: str, path): |
| 85 |
path.write_text(content, encoding='utf-8') |
| 86 |
|
| 87 |
|
| 88 |
@create.register |
| 89 |
def _(content: Symlink, path): |
| 90 |
path.symlink_to(content) |
| 91 |
|
| 92 |
|
| 93 |
# end from jaraco.path |
| 94 |
#### |