blob: 74a63e4a7535bddb458e9bd2d06401816658481d [file] [log] [blame]
Jason R. Coombs843c2772020-06-07 21:00:51 -04001import zipfile
2import pathlib
3from . import abc
4
5
6class FileReader(abc.TraversableResources):
7 def __init__(self, loader):
8 self.path = pathlib.Path(loader.path).parent
9
Jason R. Coombs2fb5f032020-06-29 16:59:22 -040010 def resource_path(self, resource):
11 """
12 Return the file system path to prevent
13 `resources.path()` from creating a temporary
14 copy.
15 """
16 return str(self.path.joinpath(resource))
17
Jason R. Coombs843c2772020-06-07 21:00:51 -040018 def files(self):
19 return self.path
20
21
Jason R. Coombs2fb5f032020-06-29 16:59:22 -040022class ZipReader(abc.TraversableResources):
Jason R. Coombs843c2772020-06-07 21:00:51 -040023 def __init__(self, loader, module):
24 _, _, name = module.rpartition('.')
Jason R. Coombsdf8d4c82020-10-25 14:21:46 -040025 self.prefix = loader.prefix.replace('\\', '/') + name + '/'
26 self.archive = loader.archive
Jason R. Coombs843c2772020-06-07 21:00:51 -040027
28 def open_resource(self, resource):
29 try:
30 return super().open_resource(resource)
31 except KeyError as exc:
32 raise FileNotFoundError(exc.args[0])
33
34 def is_resource(self, path):
35 # workaround for `zipfile.Path.is_file` returning true
36 # for non-existent paths.
37 target = self.files().joinpath(path)
38 return target.is_file() and target.exists()
Jason R. Coombs2fb5f032020-06-29 16:59:22 -040039
40 def files(self):
Jason R. Coombsdf8d4c82020-10-25 14:21:46 -040041 return zipfile.Path(self.archive, self.prefix)