Barry Warsaw | deae6b4 | 2017-12-30 15:18:06 -0500 | [diff] [blame] | 1 | import os |
Jason R. Coombs | df8d4c8 | 2020-10-25 14:21:46 -0400 | [diff] [blame] | 2 | import io |
Barry Warsaw | deae6b4 | 2017-12-30 15:18:06 -0500 | [diff] [blame] | 3 | |
Jason R. Coombs | 7f7e706 | 2020-05-08 19:20:26 -0400 | [diff] [blame] | 4 | from . import _common |
Jason R. Coombs | 843c277 | 2020-06-07 21:00:51 -0400 | [diff] [blame] | 5 | from ._common import as_file, files |
Jason R. Coombs | df8d4c8 | 2020-10-25 14:21:46 -0400 | [diff] [blame] | 6 | from contextlib import suppress |
Barry Warsaw | deae6b4 | 2017-12-30 15:18:06 -0500 | [diff] [blame] | 7 | from importlib.abc import ResourceLoader |
| 8 | from io import BytesIO, TextIOWrapper |
| 9 | from pathlib import Path |
| 10 | from types import ModuleType |
Jason R. Coombs | 843c277 | 2020-06-07 21:00:51 -0400 | [diff] [blame] | 11 | from typing import ContextManager, Iterable, Union |
Barry Warsaw | deae6b4 | 2017-12-30 15:18:06 -0500 | [diff] [blame] | 12 | from typing import cast |
| 13 | from typing.io import BinaryIO, TextIO |
Jason R. Coombs | df8d4c8 | 2020-10-25 14:21:46 -0400 | [diff] [blame] | 14 | from collections.abc import Sequence |
| 15 | from functools import singledispatch |
Barry Warsaw | deae6b4 | 2017-12-30 15:18:06 -0500 | [diff] [blame] | 16 | |
| 17 | |
Barry Warsaw | 0ed66df | 2018-05-17 11:41:53 -0400 | [diff] [blame] | 18 | __all__ = [ |
| 19 | 'Package', |
| 20 | 'Resource', |
Jason R. Coombs | 7f7e706 | 2020-05-08 19:20:26 -0400 | [diff] [blame] | 21 | 'as_file', |
Barry Warsaw | 0ed66df | 2018-05-17 11:41:53 -0400 | [diff] [blame] | 22 | 'contents', |
Jason R. Coombs | 7f7e706 | 2020-05-08 19:20:26 -0400 | [diff] [blame] | 23 | 'files', |
Barry Warsaw | 0ed66df | 2018-05-17 11:41:53 -0400 | [diff] [blame] | 24 | 'is_resource', |
| 25 | 'open_binary', |
| 26 | 'open_text', |
| 27 | 'path', |
| 28 | 'read_binary', |
| 29 | 'read_text', |
| 30 | ] |
| 31 | |
| 32 | |
Barry Warsaw | deae6b4 | 2017-12-30 15:18:06 -0500 | [diff] [blame] | 33 | Package = Union[str, ModuleType] |
| 34 | Resource = Union[str, os.PathLike] |
| 35 | |
| 36 | |
Barry Warsaw | deae6b4 | 2017-12-30 15:18:06 -0500 | [diff] [blame] | 37 | def open_binary(package: Package, resource: Resource) -> BinaryIO: |
| 38 | """Return a file-like object opened for binary reading of the resource.""" |
Jason R. Coombs | 843c277 | 2020-06-07 21:00:51 -0400 | [diff] [blame] | 39 | resource = _common.normalize_path(resource) |
| 40 | package = _common.get_package(package) |
| 41 | reader = _common.get_resource_reader(package) |
Barry Warsaw | deae6b4 | 2017-12-30 15:18:06 -0500 | [diff] [blame] | 42 | if reader is not None: |
| 43 | return reader.open_resource(resource) |
Jason R. Coombs | 7f7e706 | 2020-05-08 19:20:26 -0400 | [diff] [blame] | 44 | absolute_package_path = os.path.abspath( |
| 45 | package.__spec__.origin or 'non-existent file') |
Barry Warsaw | deae6b4 | 2017-12-30 15:18:06 -0500 | [diff] [blame] | 46 | package_path = os.path.dirname(absolute_package_path) |
| 47 | full_path = os.path.join(package_path, resource) |
| 48 | try: |
Barry Warsaw | 0ed66df | 2018-05-17 11:41:53 -0400 | [diff] [blame] | 49 | return open(full_path, mode='rb') |
Barry Warsaw | deae6b4 | 2017-12-30 15:18:06 -0500 | [diff] [blame] | 50 | except OSError: |
| 51 | # Just assume the loader is a resource loader; all the relevant |
| 52 | # importlib.machinery loaders are and an AttributeError for |
| 53 | # get_data() will make it clear what is needed from the loader. |
| 54 | loader = cast(ResourceLoader, package.__spec__.loader) |
| 55 | data = None |
| 56 | if hasattr(package.__spec__.loader, 'get_data'): |
| 57 | with suppress(OSError): |
| 58 | data = loader.get_data(full_path) |
| 59 | if data is None: |
| 60 | package_name = package.__spec__.name |
| 61 | message = '{!r} resource not found in {!r}'.format( |
| 62 | resource, package_name) |
| 63 | raise FileNotFoundError(message) |
Jason R. Coombs | 7f7e706 | 2020-05-08 19:20:26 -0400 | [diff] [blame] | 64 | return BytesIO(data) |
Barry Warsaw | deae6b4 | 2017-12-30 15:18:06 -0500 | [diff] [blame] | 65 | |
| 66 | |
| 67 | def open_text(package: Package, |
| 68 | resource: Resource, |
| 69 | encoding: str = 'utf-8', |
| 70 | errors: str = 'strict') -> TextIO: |
| 71 | """Return a file-like object opened for text reading of the resource.""" |
Jason R. Coombs | 7f7e706 | 2020-05-08 19:20:26 -0400 | [diff] [blame] | 72 | return TextIOWrapper( |
| 73 | open_binary(package, resource), encoding=encoding, errors=errors) |
Barry Warsaw | deae6b4 | 2017-12-30 15:18:06 -0500 | [diff] [blame] | 74 | |
| 75 | |
| 76 | def read_binary(package: Package, resource: Resource) -> bytes: |
| 77 | """Return the binary contents of the resource.""" |
Barry Warsaw | deae6b4 | 2017-12-30 15:18:06 -0500 | [diff] [blame] | 78 | with open_binary(package, resource) as fp: |
| 79 | return fp.read() |
| 80 | |
| 81 | |
| 82 | def read_text(package: Package, |
| 83 | resource: Resource, |
| 84 | encoding: str = 'utf-8', |
| 85 | errors: str = 'strict') -> str: |
| 86 | """Return the decoded string of the resource. |
| 87 | |
| 88 | The decoding-related arguments have the same semantics as those of |
| 89 | bytes.decode(). |
| 90 | """ |
Barry Warsaw | deae6b4 | 2017-12-30 15:18:06 -0500 | [diff] [blame] | 91 | with open_text(package, resource, encoding, errors) as fp: |
| 92 | return fp.read() |
| 93 | |
| 94 | |
Jason R. Coombs | 7f7e706 | 2020-05-08 19:20:26 -0400 | [diff] [blame] | 95 | def path( |
| 96 | package: Package, resource: Resource, |
| 97 | ) -> 'ContextManager[Path]': |
Barry Warsaw | deae6b4 | 2017-12-30 15:18:06 -0500 | [diff] [blame] | 98 | """A context manager providing a file path object to the resource. |
| 99 | |
| 100 | If the resource does not already exist on its own on the file system, |
| 101 | a temporary file will be created. If the file was created, the file |
| 102 | will be deleted upon exiting the context manager (no exception is |
| 103 | raised if the file was deleted prior to the context manager |
| 104 | exiting). |
| 105 | """ |
Jason R. Coombs | 843c277 | 2020-06-07 21:00:51 -0400 | [diff] [blame] | 106 | reader = _common.get_resource_reader(_common.get_package(package)) |
Jason R. Coombs | 7f7e706 | 2020-05-08 19:20:26 -0400 | [diff] [blame] | 107 | return ( |
Jason R. Coombs | df8d4c8 | 2020-10-25 14:21:46 -0400 | [diff] [blame] | 108 | _path_from_reader(reader, _common.normalize_path(resource)) |
Jason R. Coombs | 7f7e706 | 2020-05-08 19:20:26 -0400 | [diff] [blame] | 109 | if reader else |
Jason R. Coombs | 843c277 | 2020-06-07 21:00:51 -0400 | [diff] [blame] | 110 | _common.as_file( |
| 111 | _common.files(package).joinpath(_common.normalize_path(resource))) |
Jason R. Coombs | 7f7e706 | 2020-05-08 19:20:26 -0400 | [diff] [blame] | 112 | ) |
| 113 | |
| 114 | |
Jason R. Coombs | 7f7e706 | 2020-05-08 19:20:26 -0400 | [diff] [blame] | 115 | def _path_from_reader(reader, resource): |
Jason R. Coombs | df8d4c8 | 2020-10-25 14:21:46 -0400 | [diff] [blame] | 116 | return _path_from_resource_path(reader, resource) or \ |
| 117 | _path_from_open_resource(reader, resource) |
| 118 | |
| 119 | |
| 120 | def _path_from_resource_path(reader, resource): |
Jason R. Coombs | 7f7e706 | 2020-05-08 19:20:26 -0400 | [diff] [blame] | 121 | with suppress(FileNotFoundError): |
Jason R. Coombs | df8d4c8 | 2020-10-25 14:21:46 -0400 | [diff] [blame] | 122 | return Path(reader.resource_path(resource)) |
| 123 | |
| 124 | |
| 125 | def _path_from_open_resource(reader, resource): |
| 126 | saved = io.BytesIO(reader.open_resource(resource).read()) |
| 127 | return _common._tempfile(saved.read, suffix=resource) |
Barry Warsaw | deae6b4 | 2017-12-30 15:18:06 -0500 | [diff] [blame] | 128 | |
| 129 | |
| 130 | def is_resource(package: Package, name: str) -> bool: |
| 131 | """True if 'name' is a resource inside 'package'. |
| 132 | |
| 133 | Directories are *not* resources. |
| 134 | """ |
Jason R. Coombs | 843c277 | 2020-06-07 21:00:51 -0400 | [diff] [blame] | 135 | package = _common.get_package(package) |
| 136 | _common.normalize_path(name) |
| 137 | reader = _common.get_resource_reader(package) |
Barry Warsaw | deae6b4 | 2017-12-30 15:18:06 -0500 | [diff] [blame] | 138 | if reader is not None: |
| 139 | return reader.is_resource(name) |
Jason R. Coombs | 7f7e706 | 2020-05-08 19:20:26 -0400 | [diff] [blame] | 140 | package_contents = set(contents(package)) |
Barry Warsaw | deae6b4 | 2017-12-30 15:18:06 -0500 | [diff] [blame] | 141 | if name not in package_contents: |
| 142 | return False |
Jason R. Coombs | 7f7e706 | 2020-05-08 19:20:26 -0400 | [diff] [blame] | 143 | return (_common.from_package(package) / name).is_file() |
Barry Warsaw | deae6b4 | 2017-12-30 15:18:06 -0500 | [diff] [blame] | 144 | |
| 145 | |
Brett Cannon | 3ab9365 | 2018-04-30 11:31:45 -0700 | [diff] [blame] | 146 | def contents(package: Package) -> Iterable[str]: |
| 147 | """Return an iterable of entries in 'package'. |
Barry Warsaw | deae6b4 | 2017-12-30 15:18:06 -0500 | [diff] [blame] | 148 | |
| 149 | Note that not all entries are resources. Specifically, directories are |
| 150 | not considered resources. Use `is_resource()` on each entry returned here |
| 151 | to check if it is a resource or not. |
| 152 | """ |
Jason R. Coombs | 843c277 | 2020-06-07 21:00:51 -0400 | [diff] [blame] | 153 | package = _common.get_package(package) |
| 154 | reader = _common.get_resource_reader(package) |
Barry Warsaw | deae6b4 | 2017-12-30 15:18:06 -0500 | [diff] [blame] | 155 | if reader is not None: |
Jason R. Coombs | df8d4c8 | 2020-10-25 14:21:46 -0400 | [diff] [blame] | 156 | return _ensure_sequence(reader.contents()) |
Barry Warsaw | deae6b4 | 2017-12-30 15:18:06 -0500 | [diff] [blame] | 157 | # Is the package a namespace package? By definition, namespace packages |
Jason R. Coombs | 7f7e706 | 2020-05-08 19:20:26 -0400 | [diff] [blame] | 158 | # cannot have resources. |
| 159 | namespace = ( |
| 160 | package.__spec__.origin is None or |
| 161 | package.__spec__.origin == 'namespace' |
| 162 | ) |
| 163 | if namespace or not package.__spec__.has_location: |
Brett Cannon | 3ab9365 | 2018-04-30 11:31:45 -0700 | [diff] [blame] | 164 | return () |
Jason R. Coombs | 7f7e706 | 2020-05-08 19:20:26 -0400 | [diff] [blame] | 165 | return list(item.name for item in _common.from_package(package).iterdir()) |
Jason R. Coombs | df8d4c8 | 2020-10-25 14:21:46 -0400 | [diff] [blame] | 166 | |
| 167 | |
| 168 | @singledispatch |
| 169 | def _ensure_sequence(iterable): |
| 170 | return list(iterable) |
| 171 | |
| 172 | |
| 173 | @_ensure_sequence.register(Sequence) |
| 174 | def _(iterable): |
| 175 | return iterable |