_path.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import pathlib
  2. import functools
  3. from typing import Dict, Union
  4. ####
  5. # from jaraco.path 3.4.1
  6. FilesSpec = Dict[str, Union[str, bytes, 'FilesSpec']] # type: ignore
  7. def build(spec: FilesSpec, prefix=pathlib.Path()):
  8. """
  9. Build a set of files/directories, as described by the spec.
  10. Each key represents a pathname, and the value represents
  11. the content. Content may be a nested directory.
  12. >>> spec = {
  13. ... 'README.txt': "A README file",
  14. ... "foo": {
  15. ... "__init__.py": "",
  16. ... "bar": {
  17. ... "__init__.py": "",
  18. ... },
  19. ... "baz.py": "# Some code",
  20. ... }
  21. ... }
  22. >>> target = getfixture('tmp_path')
  23. >>> build(spec, target)
  24. >>> target.joinpath('foo/baz.py').read_text(encoding='utf-8')
  25. '# Some code'
  26. """
  27. for name, contents in spec.items():
  28. create(contents, pathlib.Path(prefix) / name)
  29. @functools.singledispatch
  30. def create(content: Union[str, bytes, FilesSpec], path):
  31. path.mkdir(exist_ok=True)
  32. build(content, prefix=path) # type: ignore
  33. @create.register
  34. def _(content: bytes, path):
  35. path.write_bytes(content)
  36. @create.register
  37. def _(content: str, path):
  38. path.write_text(content, encoding='utf-8')
  39. # end from jaraco.path
  40. ####