| 1 |
"""Provides an object-oriented model for handling :pep:`376` RECORD files.""" |
| 2 |
|
| 3 |
import base64 |
| 4 |
import csv |
| 5 |
import hashlib |
| 6 |
import os |
| 7 |
from collections.abc import Iterable, Iterator |
| 8 |
from dataclasses import dataclass |
| 9 |
from pathlib import Path |
| 10 |
from typing import BinaryIO, cast |
| 11 |
|
| 12 |
from installer.utils import copyfileobj_with_hashing, get_stream_length |
| 13 |
|
| 14 |
__all__ = [ |
| 15 |
"Hash", |
| 16 |
"InvalidRecordEntry", |
| 17 |
"RecordEntry", |
| 18 |
"parse_record_file", |
| 19 |
] |
| 20 |
|
| 21 |
|
| 22 |
@dataclass |
| 23 |
class InvalidRecordEntry(Exception): |
| 24 |
"""Raised when a RecordEntry is not valid, due to improper element values or count.""" |
| 25 |
|
| 26 |
elements: Iterable[str] |
| 27 |
issues: Iterable[str] |
| 28 |
|
| 29 |
def __post_init__(self) -> None: |
| 30 |
super().__init__(", ".join(self.issues)) |
| 31 |
|
| 32 |
|
| 33 |
@dataclass |
| 34 |
class Hash: |
| 35 |
"""Represents the "hash" element of a RecordEntry. |
| 36 |
|
| 37 |
Most consumers should use :py:meth:`Hash.parse` instead, since no |
| 38 |
validation or parsing is performed by this constructor. |
| 39 |
""" |
| 40 |
|
| 41 |
name: str |
| 42 |
"""Name of the hash function.""" |
| 43 |
|
| 44 |
value: str |
| 45 |
"""Hashed value.""" |
| 46 |
|
| 47 |
def __str__(self) -> str: |
| 48 |
return f"{self.name}={self.value}" |
| 49 |
|
| 50 |
def validate(self, data: bytes) -> bool: |
| 51 |
"""Validate that ``data`` matches this instance. |
| 52 |
|
| 53 |
:param data: Contents of the file. |
| 54 |
:return: Whether ``data`` matches the hashed value. |
| 55 |
""" |
| 56 |
digest = hashlib.new(self.name, data).digest() |
| 57 |
value = base64.urlsafe_b64encode(digest).decode("ascii").rstrip("=") |
| 58 |
return self.value == value |
| 59 |
|
| 60 |
@classmethod |
| 61 |
def parse(cls, h: str) -> "Hash": |
| 62 |
"""Build a Hash object, from a "name=value" string. |
| 63 |
|
| 64 |
This accepts a string of the format for the second element in a record, |
| 65 |
as described in :pep:`376`. |
| 66 |
|
| 67 |
Typical usage:: |
| 68 |
|
| 69 |
Hash.parse("sha256=Y0sCextp4SQtQNU-MSs7SsdxD1W-gfKJtUlEbvZ3i-4") |
| 70 |
|
| 71 |
:param h: a name=value string |
| 72 |
""" |
| 73 |
name, value = h.split("=", 1) |
| 74 |
return cls(name, value) |
| 75 |
|
| 76 |
|
| 77 |
@dataclass |
| 78 |
class RecordEntry: |
| 79 |
"""Represents a single record in a RECORD file. |
| 80 |
|
| 81 |
A list of :py:class:`RecordEntry` objects fully represents a RECORD file. |
| 82 |
|
| 83 |
Most consumers should use :py:meth:`RecordEntry.from_elements`, since no |
| 84 |
validation or parsing is performed by this constructor. |
| 85 |
""" |
| 86 |
|
| 87 |
path: str |
| 88 |
"""File's path.""" |
| 89 |
|
| 90 |
hash_: Hash | None |
| 91 |
"""Hash of the file's contents.""" |
| 92 |
|
| 93 |
size: int | None |
| 94 |
"""File's size in bytes.""" |
| 95 |
|
| 96 |
def to_row(self, path_prefix: str | None = None) -> tuple[str, str, str]: |
| 97 |
"""Convert this into a 3-element tuple that can be written in a RECORD file. |
| 98 |
|
| 99 |
:param path_prefix: A prefix to attach to the path -- must end in `/` |
| 100 |
:return: a (path, hash, size) row |
| 101 |
""" |
| 102 |
if path_prefix is not None: |
| 103 |
assert path_prefix.endswith("/") |
| 104 |
path = path_prefix + self.path |
| 105 |
else: |
| 106 |
path = self.path |
| 107 |
|
| 108 |
|
| 109 |
if os.sep == "\\": |
| 110 |
path = path.replace("\\", "/") |
| 111 |
|
| 112 |
return ( |
| 113 |
path, |
| 114 |
str(self.hash_ or ""), |
| 115 |
str(self.size) if self.size is not None else "", |
| 116 |
) |
| 117 |
|
| 118 |
def __repr__(self) -> str: |
| 119 |
return ( |
| 120 |
f"RecordEntry(path={self.path!r}, hash_={self.hash_!r}, size={self.size!r})" |
| 121 |
) |
| 122 |
|
| 123 |
def __eq__(self, other: object) -> bool: |
| 124 |
if not isinstance(other, RecordEntry): |
| 125 |
return NotImplemented |
| 126 |
return ( |
| 127 |
self.path == other.path |
| 128 |
and self.hash_ == other.hash_ |
| 129 |
and self.size == other.size |
| 130 |
) |
| 131 |
|
| 132 |
def validate(self, data: bytes) -> bool: |
| 133 |
"""Validate that ``data`` matches this instance. |
| 134 |
|
| 135 |
.. attention:: |
| 136 |
.. deprecated:: 1.0.0 |
| 137 |
Use :py:meth:`validate_stream` instead, with ``BytesIO(data)``. |
| 138 |
|
| 139 |
:param data: Contents of the file corresponding to this instance. |
| 140 |
:return: whether ``data`` matches hash and size. |
| 141 |
""" |
| 142 |
if self.size is not None and len(data) != self.size: |
| 143 |
return False |
| 144 |
|
| 145 |
if self.hash_: |
| 146 |
return self.hash_.validate(data) |
| 147 |
|
| 148 |
return True |
| 149 |
|
| 150 |
def validate_stream(self, stream: BinaryIO) -> bool: |
| 151 |
"""Validate that data read from stream matches this instance. |
| 152 |
|
| 153 |
:param stream: Representing the contents of the file. |
| 154 |
:return: Whether data read from stream matches hash and size. |
| 155 |
""" |
| 156 |
if self.hash_ is not None: |
| 157 |
with Path(os.devnull).open("wb") as new_target: |
| 158 |
hash_, size = copyfileobj_with_hashing( |
| 159 |
stream, cast("BinaryIO", new_target), self.hash_.name |
| 160 |
) |
| 161 |
|
| 162 |
if self.size is not None and size != self.size: |
| 163 |
return False |
| 164 |
return self.hash_.value == hash_ |
| 165 |
|
| 166 |
elif self.size is not None: |
| 167 |
assert self.hash_ is None |
| 168 |
size = get_stream_length(stream) |
| 169 |
return size == self.size |
| 170 |
|
| 171 |
return True |
| 172 |
|
| 173 |
@classmethod |
| 174 |
def from_elements(cls, path: str, hash_: str, size: str) -> "RecordEntry": |
| 175 |
r"""Build a RecordEntry object, from values of the elements. |
| 176 |
|
| 177 |
Typical usage:: |
| 178 |
|
| 179 |
for row in parse_record_file(f): |
| 180 |
record = RecordEntry.from_elements(row[0], row[1], row[2]) |
| 181 |
|
| 182 |
Meaning of each element is specified in :pep:`376`. |
| 183 |
|
| 184 |
:param path: first element (file's path) |
| 185 |
:param hash\_: second element (hash of the file's contents) |
| 186 |
:param size: third element (file's size in bytes) |
| 187 |
:raises InvalidRecordEntry: if any element is invalid |
| 188 |
""" |
| 189 |
|
| 190 |
issues = [] |
| 191 |
|
| 192 |
if not path: |
| 193 |
issues.append("`path` cannot be empty") |
| 194 |
|
| 195 |
hash_value: Hash | None = None |
| 196 |
if hash_: |
| 197 |
try: |
| 198 |
hash_value = Hash.parse(hash_) |
| 199 |
if hash_value.name not in hashlib.algorithms_available: |
| 200 |
issues.append(f"invalid hash algorithm '{hash_value.name}'") |
| 201 |
hash_value = None |
| 202 |
except ValueError: |
| 203 |
issues.append("`hash` does not follow the required format") |
| 204 |
|
| 205 |
if size: |
| 206 |
try: |
| 207 |
size_value: int | None = int(size) |
| 208 |
except ValueError: |
| 209 |
issues.append("`size` cannot be non-integer") |
| 210 |
else: |
| 211 |
size_value = None |
| 212 |
|
| 213 |
if issues: |
| 214 |
raise InvalidRecordEntry(elements=(path, hash_, size), issues=issues) |
| 215 |
|
| 216 |
return cls(path=path, hash_=hash_value, size=size_value) |
| 217 |
|
| 218 |
|
| 219 |
def parse_record_file(rows: Iterable[str]) -> Iterator[tuple[str, str, str]]: |
| 220 |
"""Parse a :pep:`376` RECORD. |
| 221 |
|
| 222 |
Returns an iterable of 3-value tuples, that can be passed to |
| 223 |
:any:`RecordEntry.from_elements`. |
| 224 |
|
| 225 |
:param rows: iterator providing lines of a RECORD (no trailing newlines). |
| 226 |
""" |
| 227 |
reader = csv.reader(rows, delimiter=",", quotechar='"', lineterminator="\n") |
| 228 |
for row_index, elements in enumerate(reader): |
| 229 |
if len(elements) != 3: |
| 230 |
message = f"Row Index {row_index}: expected 3 elements, got {len(elements)}" |
| 231 |
raise InvalidRecordEntry(elements=elements, issues=[message]) |
| 232 |
|
| 233 |
|
| 234 |
elements[0] = elements[0].replace("\\", "/") |
| 235 |
|
| 236 |
value = cast("tuple[str, str, str]", tuple(elements)) |
| 237 |
yield value |