7 from ._itertools import unique_everseen
8 from ._compat import ZipPath
11 def remove_duplicates(items):
12 return iter(collections.OrderedDict.fromkeys(items))
15 class FileReader(abc.TraversableResources):
16 def __init__(self, loader):
17 self.path = pathlib.Path(loader.path).parent
19 def resource_path(self, resource):
21 Return the file system path to prevent
22 `resources.path()` from creating a temporary
25 return str(self.path.joinpath(resource))
31 class ZipReader(abc.TraversableResources):
32 def __init__(self, loader, module):
33 _, _, name = module.rpartition('.')
34 self.prefix = loader.prefix.replace('\\', '/') + name + '/'
35 self.archive = loader.archive
37 def open_resource(self, resource):
39 return super().open_resource(resource)
40 except KeyError as exc:
41 raise FileNotFoundError(exc.args[0])
43 def is_resource(self, path):
44 # workaround for `zipfile.Path.is_file` returning true
45 # for non-existent paths.
46 target = self.files().joinpath(path)
47 return target.is_file() and target.exists()
50 return ZipPath(self.archive, self.prefix)
53 class MultiplexedPath(abc.Traversable):
55 Given a series of Traversable objects, implement a merged
56 version of the interface across all objects. Useful for
57 namespace packages which may be multihomed at a single
61 def __init__(self, *paths):
62 self._paths = list(map(pathlib.Path, remove_duplicates(paths)))
64 message = 'MultiplexedPath must contain at least one path'
65 raise FileNotFoundError(message)
66 if not all(path.is_dir() for path in self._paths):
67 raise NotADirectoryError('MultiplexedPath only supports directories')
70 files = (file for path in self._paths for file in path.iterdir())
71 return unique_everseen(files, key=operator.attrgetter('name'))
74 raise FileNotFoundError(f'{self} is not a file')
76 def read_text(self, *args, **kwargs):
77 raise FileNotFoundError(f'{self} is not a file')
85 def joinpath(self, child):
86 # first try to find child in current paths
87 for file in self.iterdir():
88 if file.name == child:
90 # if it does not exist, construct it with the first path
91 return self._paths[0] / child
93 __truediv__ = joinpath
95 def open(self, *args, **kwargs):
96 raise FileNotFoundError(f'{self} is not a file')
100 return self._paths[0].name
103 paths = ', '.join(f"'{path}'" for path in self._paths)
104 return f'MultiplexedPath({paths})'
107 class NamespaceReader(abc.TraversableResources):
108 def __init__(self, namespace_path):
109 if 'NamespacePath' not in str(namespace_path):
110 raise ValueError('Invalid path')
111 self.path = MultiplexedPath(*list(namespace_path))
113 def resource_path(self, resource):
115 Return the file system path to prevent
116 `resources.path()` from creating a temporary
119 return str(self.path.joinpath(resource))