|
1 | 1 | """Read resources contained within a package."""
|
2 |
| -__version__ = '0.1.0' |
3 | 2 |
|
4 |
| -import builtins |
5 |
| -import contextlib |
6 |
| -import importlib |
7 |
| -import importlib.abc |
8 |
| -import io |
9 |
| -import os.path |
10 |
| -import pathlib |
11 | 3 | import sys
|
12 |
| -import tempfile |
13 |
| -import types |
14 |
| -import typing |
15 |
| -from typing import Iterator, Union |
16 |
| -from typing.io import BinaryIO |
17 | 4 |
|
18 |
| -from . import abc as resources_abc |
| 5 | +__version__ = '0.1.0' |
19 | 6 |
|
20 | 7 |
|
21 |
| -Package = Union[types.ModuleType, str] |
22 |
| -if sys.version_info >= (3, 6): |
23 |
| - FileName = Union[str, os.PathLike] # pragma: ge36 |
| 8 | +if sys.version_info >= (3,): |
| 9 | + from importlib_resources._py3 import open, path, read |
24 | 10 | else:
|
25 |
| - FileName = str # pragma: le35 |
26 |
| - |
27 |
| - |
28 |
| -def _get_package(package) -> types.ModuleType: |
29 |
| - if hasattr(package, '__spec__'): |
30 |
| - if package.__spec__.submodule_search_locations is None: |
31 |
| - raise TypeError("{!r} is not a package".format( |
32 |
| - package.__spec__.name)) |
33 |
| - else: |
34 |
| - return package |
35 |
| - else: |
36 |
| - module = importlib.import_module(package) |
37 |
| - if module.__spec__.submodule_search_locations is None: |
38 |
| - raise TypeError("{!r} is not a package".format(package)) |
39 |
| - else: |
40 |
| - return module |
41 |
| - |
42 |
| - |
43 |
| -def _normalize_path(path) -> str: |
44 |
| - str_path = str(path) |
45 |
| - parent, file_name = os.path.split(str_path) |
46 |
| - if parent: |
47 |
| - raise ValueError("{!r} must be only a file name".format(path)) |
48 |
| - else: |
49 |
| - return file_name |
50 |
| - |
51 |
| - |
52 |
| -def open(package: Package, file_name: FileName) -> BinaryIO: |
53 |
| - """Return a file-like object opened for binary-reading of the resource.""" |
54 |
| - file_name = _normalize_path(file_name) |
55 |
| - package = _get_package(package) |
56 |
| - if hasattr(package.__spec__.loader, 'open_resource'): |
57 |
| - reader = typing.cast(resources_abc.ResourceReader, |
58 |
| - package.__spec__.loader) |
59 |
| - return reader.open_resource(file_name) |
60 |
| - else: |
61 |
| - # Using pathlib doesn't work well here due to the lack of 'strict' |
62 |
| - # argument for pathlib.Path.resolve() prior to Python 3.6. |
63 |
| - absolute_package_path = os.path.abspath(package.__spec__.origin) |
64 |
| - package_path = os.path.dirname(absolute_package_path) |
65 |
| - full_path = os.path.join(package_path, file_name) |
66 |
| - try: |
67 |
| - return builtins.open(full_path, 'rb') |
68 |
| - except IOError: |
69 |
| - # Just assume the loader is a resource loader; all the relevant |
70 |
| - # importlib.machinery loaders are and an AttributeError for |
71 |
| - # get_data() will make it clear what is needed from the loader. |
72 |
| - loader = typing.cast(importlib.abc.ResourceLoader, |
73 |
| - package.__spec__.loader) |
74 |
| - try: |
75 |
| - data = loader.get_data(full_path) |
76 |
| - except IOError: |
77 |
| - package_name = package.__spec__.name |
78 |
| - message = '{!r} resource not found in {!r}'.format( |
79 |
| - file_name, package_name) |
80 |
| - raise FileNotFoundError(message) |
81 |
| - else: |
82 |
| - return io.BytesIO(data) |
83 |
| - |
84 |
| - |
85 |
| -def read(package: Package, file_name: FileName, encoding: str = 'utf-8', |
86 |
| - errors: str = 'strict') -> str: |
87 |
| - """Return the decoded string of the resource. |
88 |
| -
|
89 |
| - The decoding-related arguments have the same semantics as those of |
90 |
| - bytes.decode(). |
91 |
| - """ |
92 |
| - file_name = _normalize_path(file_name) |
93 |
| - package = _get_package(package) |
94 |
| - # Note this is **not** builtins.open()! |
95 |
| - with open(package, file_name) as binary_file: |
96 |
| - # Decoding from io.TextIOWrapper() instead of str.decode() in hopes |
97 |
| - # that the former will be smarter about memory usage. |
98 |
| - text_file = io.TextIOWrapper(binary_file, encoding=encoding, |
99 |
| - errors=errors) |
100 |
| - return text_file.read() |
101 |
| - |
102 |
| - |
103 |
| -@contextlib.contextmanager |
104 |
| -def path(package: Package, file_name: FileName) -> Iterator[pathlib.Path]: |
105 |
| - """A context manager providing a file path object to the resource. |
106 |
| -
|
107 |
| - If the resource does not already exist on its own on the file system, |
108 |
| - a temporary file will be created. If the file was created, the file |
109 |
| - will be deleted upon exiting the context manager (no exception is |
110 |
| - raised if the file was deleted prior to the context manager |
111 |
| - exiting). |
112 |
| - """ |
113 |
| - file_name = _normalize_path(file_name) |
114 |
| - package = _get_package(package) |
115 |
| - if hasattr(package.__spec__.loader, 'resource_path'): |
116 |
| - reader = typing.cast(resources_abc.ResourceReader, |
117 |
| - package.__spec__.loader) |
118 |
| - try: |
119 |
| - yield pathlib.Path(reader.resource_path(file_name)) |
120 |
| - return |
121 |
| - except FileNotFoundError: |
122 |
| - pass |
123 |
| - # Fall-through for both the lack of resource_path() *and* if |
124 |
| - # resource_path() raises FileNotFoundError. |
125 |
| - package_directory = pathlib.Path(package.__spec__.origin).parent |
126 |
| - file_path = package_directory / file_name |
127 |
| - if file_path.exists(): |
128 |
| - yield file_path |
129 |
| - else: |
130 |
| - with open(package, file_name) as file: |
131 |
| - data = file.read() |
132 |
| - # Not using tempfile.NamedTemporaryFile as it leads to deeper 'try' |
133 |
| - # blocks due to the need to close the temporary file to work on |
134 |
| - # Windows properly. |
135 |
| - fd, raw_path = tempfile.mkstemp() |
136 |
| - try: |
137 |
| - os.write(fd, data) |
138 |
| - os.close(fd) |
139 |
| - yield pathlib.Path(raw_path) |
140 |
| - finally: |
141 |
| - try: |
142 |
| - os.remove(raw_path) |
143 |
| - except FileNotFoundError: |
144 |
| - pass |
| 11 | + from importlib_resources._py2 import open, path, read |
0 commit comments