Debian Codegraph @

Lib/test/test_importlib/metadata/_path.py

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