Repository navigation
Expand file tree
/
Copy path_reader.py
More file actions
66 lines (50 loc) · 2.39 KB
/
Copy path_reader.py
File metadata and controls
66 lines (50 loc) · 2.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
"""Open a built artifact once and read its members through one checked handle."""
from __future__ import annotations
__lazy_modules__ = [
"io",
f"{__spec__.parent}._bundled", # ty: ignore[missing-union-attribute] # imported modules have a spec
f"{__spec__.parent}._zip", # ty: ignore[missing-union-attribute] # imported modules have a spec
]
from contextlib import contextmanager
from dataclasses import dataclass
from io import BytesIO
from typing import TYPE_CHECKING
from ._bundled import read_bundled_wheels
from ._zip import open_archive, read_member, sha256_hex
if TYPE_CHECKING:
import zipfile
from collections.abc import Generator
from pathlib import Path, PurePosixPath
from python_sbom._model._inputs import BundledWheel # simplint: ignore[private-import-path] # avoid root export
@contextmanager
def open_artifact(path: Path) -> Generator[ArtifactReader, None, None]:
# one open zip serves every read of a build, the provider's included, so the archive is checked and indexed once
with open_archive(path, str(path)) as archive:
yield ArtifactReader(path=path, archive=archive, members=frozenset(archive.namelist()))
@dataclass(frozen=True, slots=True, kw_only=True)
class ArtifactReader:
path: Path
archive: zipfile.ZipFile
members: frozenset[str]
def digest(self, name: str) -> str:
with self.archive.open(name) as member:
return sha256_hex(member)
def provider_read(self, path: PurePosixPath) -> bytes:
# a provider asking for a member the artifact lacks gets the KeyError a mapping raises, which it may expect
if (name := str(path)) not in self.members:
raise KeyError(name)
return self.read(name)
def read(self, name: str) -> bytes:
return read_member(self.archive, name, str(self.path))
def bundled_wheels(self, names: list[str]) -> list[BundledWheel]:
# zipfile serializes the seeks of concurrent member reads on its own lock, so the verifying threads share this
# handle and inflate side by side
# a bundled wheel is read whole, to hash it and open it as a zip, so its size is capped as metadata's is
wheel_limit: int = 512 * 1024 * 1024
return read_bundled_wheels(
names, lambda name: BytesIO(read_member(self.archive, name, str(self.path), wheel_limit))
)
__all__ = [
"ArtifactReader",
"open_artifact",
]