Debian Codegraph @

src/installer/sources.py

raw symbols SCIP
1 """Source of information about a wheel file."""
2
3 import posixpath
4 import stat
5 import zipfile
6 from collections.abc import Iterator
7 from contextlib import contextmanager
8 from functools import cached_property
9 from pathlib import Path
10 from typing import (
11 TYPE_CHECKING,
12 BinaryIO,
13 ClassVar,
14 cast,
15 )
16
17 from installer.exceptions import InstallerError
18 from installer.records import InvalidRecordEntry, RecordEntry, parse_record_file
19 from installer.utils import canonicalize_name, parse_wheel_filename
20
21 if TYPE_CHECKING:
22 import os
23
24 WheelContentElement = tuple[tuple[str, str, str], BinaryIO, bool]
25
26
27 __all__ = ["WheelFile", "WheelSource"]
28
29
30 class WheelSource:
31 """Represents an installable wheel.
32
33 This is an abstract class, whose methods have to be implemented by subclasses.
34 """
35
36 validation_error: ClassVar[type[Exception]] = ValueError #: :meta hide-value:
37 """
38 .. versionadded:: 0.7.0
39
40 Exception to be raised by :py:meth:`validate_record` when validation fails.
41 This is expected to be a subclass of :py:class:`ValueError`.
42 """
43
44 def __init__(self, distribution: str, version: str) -> None:
45 """Initialize a WheelSource object.
46
47 :param distribution: distribution name (like ``urllib3``)
48 :param version: version associated with the wheel
49 """
50 super().__init__()
51 self.distribution = distribution
52 self.version = version
53
54 @property
55 def dist_info_dir(self) -> str:
56 """Name of the dist-info directory."""
57 return f"{self.distribution}-{self.version}.dist-info"
58
59 @property
60 def data_dir(self) -> str:
61 """Name of the data directory."""
62 return f"{self.distribution}-{self.version}.data"
63
64 @property
65 def dist_info_filenames(self) -> list[str]:
66 """Get names of all files in the dist-info directory.
67
68 Sample usage/behaviour::
69
70 >>> wheel_source.dist_info_filenames
71 ['METADATA', 'WHEEL']
72 """
73 raise NotImplementedError
74
75 def read_dist_info(self, filename: str) -> str:
76 """Get contents, from ``filename`` in the dist-info directory.
77
78 Sample usage/behaviour::
79
80 >>> wheel_source.read_dist_info("METADATA")
81 ...
82
83 :param filename: name of the file
84 """
85 raise NotImplementedError
86
87 def validate_record(self) -> None:
88 """Validate ``RECORD`` of the wheel.
89
90 .. versionadded:: 0.7.0
91
92 This method should be called before :py:func:`install <installer.install>`
93 if validation is required.
94 """
95 raise NotImplementedError
96
97 def get_contents(self) -> Iterator[WheelContentElement]:
98 """Sequential access to all contents of the wheel (including dist-info files).
99
100 This method should return an iterable. Each value from the iterable must be a
101 tuple containing 3 elements:
102
103 - record: 3-value tuple, to pass to
104 :py:meth:`RecordEntry.from_elements <installer.records.RecordEntry.from_elements>`.
105 - stream: An :py:class:`io.BufferedReader` object, providing the contents of the
106 file at the location provided by the first element (path).
107 - is_executable: A boolean, representing whether the item has an executable bit.
108
109 All paths must be relative to the root of the wheel.
110
111 Sample usage/behaviour::
112
113 >>> iterable = wheel_source.get_contents()
114 >>> next(iterable)
115 (('pkg/__init__.py', '', '0'), <...>, False)
116
117 This method may be called multiple times. Each iterable returned must
118 provide the same content upon reading from a specific file's stream.
119 """
120 raise NotImplementedError
121
122
123 class _WheelFileValidationError(ValueError, InstallerError):
124 """Raised when a wheel file fails validation."""
125
126 def __init__(self, issues: list[str]) -> None:
127 super().__init__(repr(issues))
128 self.issues = issues
129
130 def __repr__(self) -> str:
131 return f"WheelFileValidationError(issues={self.issues!r})"
132
133
134 class _WheelFileBadDistInfo(ValueError, InstallerError):
135 """Raised when a wheel file has issues around `.dist-info`."""
136
137 def __init__(self, *, reason: str, filename: str | None, dist_info: str) -> None:
138 super().__init__(reason)
139 self.reason = reason
140 self.filename = filename
141 self.dist_info = dist_info
142
143 def __str__(self) -> str:
144 return (
145 f"{self.reason} (filename={self.filename!r}, dist_info={self.dist_info!r})"
146 )
147
148
149 class WheelFile(WheelSource):
150 """Implements `WheelSource`, for an existing file from the filesystem.
151
152 Example usage::
153
154 >>> with WheelFile.open("sampleproject-2.0.0-py3-none-any.whl") as source:
155 ... installer.install(source, destination)
156 """
157
158 validation_error = _WheelFileValidationError
159
160 def __init__(self, f: zipfile.ZipFile) -> None:
161 """Initialize a WheelFile object.
162
163 :param f: An open zipfile, which will stay open as long as this object is used.
164 """
165 self._zipfile = f
166 assert f.filename
167
168 basename = Path(f.filename).name
169 parsed_name = parse_wheel_filename(basename)
170 super().__init__(
171 version=parsed_name.version,
172 distribution=parsed_name.distribution,
173 )
174
175 @classmethod
176 @contextmanager
177 def open(cls, path: "os.PathLike[str]") -> Iterator["WheelFile"]:
178 """Create a wheelfile from a given path."""
179 with zipfile.ZipFile(path) as f:
180 yield cls(f)
181
182 @cached_property
183 def dist_info_dir(self) -> str:
184 """Name of the dist-info directory."""
185 top_level_directories = {
186 path.split("/", 1)[0] for path in self._zipfile.namelist()
187 }
188 dist_infos = [
189 name for name in top_level_directories if name.endswith(".dist-info")
190 ]
191
192 try:
193 (dist_info_dir,) = dist_infos
194 except ValueError:
195 raise _WheelFileBadDistInfo(
196 reason="Wheel doesn't contain exactly one .dist-info directory",
197 filename=self._zipfile.filename,
198 dist_info=str(sorted(dist_infos)),
199 ) from None
200
201 # NAME-VER.dist-info
202 di_dname = dist_info_dir.rsplit("-", 2)[0]
203 norm_di_dname = canonicalize_name(di_dname)
204 norm_file_dname = canonicalize_name(self.distribution)
205
206 if norm_di_dname != norm_file_dname:
207 raise _WheelFileBadDistInfo(
208 reason="Wheel .dist-info directory doesn't match wheel filename",
209 filename=self._zipfile.filename,
210 dist_info=dist_info_dir,
211 )
212
213 return dist_info_dir
214
215 @property
216 def dist_info_filenames(self) -> list[str]:
217 """Get names of all files in the dist-info directory."""
218 base = self.dist_info_dir
219 return [
220 name[len(base) + 1 :]
221 for name in self._zipfile.namelist()
222 if name[-1:] != "/"
223 if base == posixpath.commonprefix([name, base])
224 ]
225
226 def read_dist_info(self, filename: str) -> str:
227 """Get contents, from ``filename`` in the dist-info directory."""
228 path = posixpath.join(self.dist_info_dir, filename)
229 return self._zipfile.read(path).decode("utf-8")
230
231 def validate_record(self, *, validate_contents: bool = True) -> None:
232 """Validate ``RECORD`` of the wheel.
233
234 This method should be called before :py:func:`install <installer.install>`
235 if validation is required.
236
237 File names will always be validated against ``RECORD``.
238
239 If ``validate_contents`` is true, sizes and hashes of files
240 will also be validated against ``RECORD``.
241
242 :param validate_contents: Whether to validate content integrity.
243 """
244 try:
245 record_lines = self.read_dist_info("RECORD").splitlines()
246 record_mapping = {
247 record[0]: record for record in parse_record_file(record_lines)
248 }
249 except Exception as exc:
250 raise _WheelFileValidationError(
251 [f"Unable to retrieve `RECORD` from {self._zipfile.filename}: {exc!r}"]
252 ) from exc
253
254 issues: list[str] = []
255
256 for item in self._zipfile.infolist():
257 if item.filename[-1:] == "/": # looks like a directory
258 continue
259
260 record_args = record_mapping.pop(item.filename, None)
261
262 if self.dist_info_dir == posixpath.commonprefix(
263 [self.dist_info_dir, item.filename]
264 ) and item.filename.split("/")[-1] in ("RECORD.p7s", "RECORD.jws"):
265 # both are for digital signatures, and not mentioned in RECORD
266 if record_args is not None:
267 # Incorrectly contained
268 issues.append(
269 f"In {self._zipfile.filename}, digital signature file {item.filename} is incorrectly contained in RECORD."
270 )
271 continue
272
273 if record_args is None:
274 issues.append(
275 f"In {self._zipfile.filename}, {item.filename} is not mentioned in RECORD"
276 )
277 continue
278
279 try:
280 record = RecordEntry.from_elements(*record_args)
281 except InvalidRecordEntry as e:
282 for issue in e.issues:
283 issues.append(
284 f"In {self._zipfile.filename}, entry in RECORD file for "
285 f"{item.filename} is invalid: {issue}"
286 )
287 continue
288
289 if item.filename == f"{self.dist_info_dir}/RECORD":
290 # Assert that RECORD doesn't have size and hash.
291 if record.hash_ is not None or record.size is not None:
292 # Incorrectly contained hash / size
293 issues.append(
294 f"In {self._zipfile.filename}, RECORD file incorrectly contains hash / size."
295 )
296 continue
297 if record.hash_ is None or record.size is None:
298 # Report empty hash / size
299 issues.append(
300 f"In {self._zipfile.filename}, hash / size of {item.filename} is not included in RECORD"
301 )
302 if validate_contents:
303 with self._zipfile.open(item, "r") as stream:
304 if not record.validate_stream(cast("BinaryIO", stream)):
305 issues.append(
306 f"In {self._zipfile.filename}, hash / size of {item.filename} didn't match RECORD"
307 )
308
309 if issues:
310 raise _WheelFileValidationError(issues)
311
312 def get_contents(self) -> Iterator[WheelContentElement]:
313 """Sequential access to all contents of the wheel (including dist-info files).
314
315 This implementation requires that every file that is a part of the wheel
316 archive has a corresponding entry in RECORD. If they are not, an
317 :any:`AssertionError` will be raised.
318 """
319 # Convert the record file into a useful mapping
320 record_lines = self.read_dist_info("RECORD").splitlines()
321 records = parse_record_file(record_lines)
322 record_mapping = {record[0]: record for record in records}
323
324 for item in self._zipfile.infolist():
325 if item.filename[-1:] == "/": # looks like a directory
326 continue
327
328 # Pop record with empty default, because validation is handled by `validate_record`
329 record = record_mapping.pop(item.filename, (item.filename, "", ""))
330
331 # Borrowed from:
332 # https://github.com/pypa/pip/blob/0f21fb92/src/pip/_internal/utils/unpacking.py#L96-L100
333 mode = item.external_attr >> 16
334 is_executable = bool(mode and stat.S_ISREG(mode) and mode & 0o111)
335
336 with self._zipfile.open(item) as stream:
337 stream_casted = cast("BinaryIO", stream)
338 yield record, stream_casted, is_executable