Miss Islington (bot) | 9cf1be4 | 2020-06-07 18:30:08 -0700 | [diff] [blame^] | 1 | import zipfile |
| 2 | import pathlib |
| 3 | from . import abc |
| 4 | |
| 5 | |
| 6 | class FileReader(abc.TraversableResources): |
| 7 | def __init__(self, loader): |
| 8 | self.path = pathlib.Path(loader.path).parent |
| 9 | |
| 10 | def files(self): |
| 11 | return self.path |
| 12 | |
| 13 | |
| 14 | class ZipReader(FileReader): |
| 15 | def __init__(self, loader, module): |
| 16 | _, _, name = module.rpartition('.') |
| 17 | prefix = loader.prefix.replace('\\', '/') + name + '/' |
| 18 | self.path = zipfile.Path(loader.archive, prefix) |
| 19 | |
| 20 | def open_resource(self, resource): |
| 21 | try: |
| 22 | return super().open_resource(resource) |
| 23 | except KeyError as exc: |
| 24 | raise FileNotFoundError(exc.args[0]) |
| 25 | |
| 26 | def is_resource(self, path): |
| 27 | # workaround for `zipfile.Path.is_file` returning true |
| 28 | # for non-existent paths. |
| 29 | target = self.files().joinpath(path) |
| 30 | return target.is_file() and target.exists() |