debkit 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
debkit/repo/changes.py ADDED
@@ -0,0 +1,172 @@
1
+ """Class containing Debian Changes file data."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import logging
7
+ from typing import TYPE_CHECKING
8
+
9
+ from txstore import StorageException, is_unsafe_path
10
+
11
+ from debkit.repo.compress import SizeLimitError, read_capped
12
+ from debkit.repo.gnupg import CLEARSIGN_BEGIN, GPGVerifyException, cleartext_body
13
+ from debkit.repo.hashes import CHECKSUMS_SHA256, ChecksumException, HexDigests, parse_hash_block
14
+ from debkit.repo.params import SOURCE_ARCH
15
+ from debkit.repo.stanza import parse_stanza
16
+
17
+ if TYPE_CHECKING:
18
+ from txstore import Storage
19
+
20
+ logger = logging.getLogger(__name__)
21
+ logger.addHandler(logging.NullHandler())
22
+
23
+ DEFAULT_ARCH = "amd64"
24
+
25
+ # Largest `.changes` file read; a real one lists a few files and is a few KiB, so this bounds
26
+ # what a mistyped name or a misbehaving backend can make a load buffer
27
+ # -> [VALIDATION.md](VALIDATION.md#object-sizes)
28
+ MAX_CHANGES_BYTES = 4 * 1024 * 1024
29
+
30
+
31
+ class ChangesException(Exception):
32
+ """Exception raised for errors in the Changes class."""
33
+
34
+ def __init__(self, message: str) -> None:
35
+ """Initialize with error message."""
36
+ super().__init__(f"Changes: {message}")
37
+
38
+
39
+ class Changes(HexDigests):
40
+ """Object holding parsed Debian ``.changes`` file data.
41
+
42
+ Attributes:
43
+ storage: Storage backend used to read the file.
44
+ fields: Parsed header fields from the changes file.
45
+ """
46
+
47
+ def __init__(self, storage: Storage) -> None:
48
+ """Initialize Changes object.
49
+
50
+ Args:
51
+ storage: Storage object
52
+ """
53
+ self.storage = storage
54
+ self.fields: dict[str, str] = {}
55
+ super().__init__()
56
+
57
+ def parse(self, enc_data: bytes) -> None:
58
+ """Parse Changes file fields from headers format.
59
+
60
+ Args:
61
+ enc_data: The encoded data to parse.
62
+
63
+ A clearsigned file, as `debsign` writes it, is read through its signed body; the
64
+ signature itself is not verified -> [CRYPTO.md](CRYPTO.md#verification-failures).
65
+
66
+ Raises:
67
+ ChangesException: If the file is not UTF-8.
68
+ ChangesException: If a field appears twice, its name compared without case.
69
+ ChangesException: If a blank line stands between two fields.
70
+ ChangesException: If a line is neither a field, a continuation, nor empty.
71
+ ChangesException: If no SHA256 checksums found in changes file.
72
+ ChangesException: If a listed file is not a bare, safe file name.
73
+ ChangesException: If a clearsigned file is malformed.
74
+ """
75
+ if enc_data.startswith(CLEARSIGN_BEGIN.encode()):
76
+ try:
77
+ enc_data = cleartext_body(enc_data)
78
+ except GPGVerifyException as exc:
79
+ raise ChangesException(f"malformed signed file: {exc}") from exc
80
+ # Debian Policy 5.1: control data is UTF-8
81
+ # -> [VALIDATION.md](VALIDATION.md#control-file-encoding)
82
+ try:
83
+ data = enc_data.decode("utf-8")
84
+ except UnicodeDecodeError as exc:
85
+ raise ChangesException(f"not UTF-8: {exc}") from exc
86
+
87
+ # one paragraph, as dpkg reads it: a blank line would end the fields there and hide
88
+ # the digests and architectures after it -> [VALIDATION.md](VALIDATION.md#blank-lines)
89
+ parsed, more_paragraphs, unreadable = parse_stanza(data)
90
+ if more_paragraphs:
91
+ raise ChangesException("blank line between fields: a .changes is one paragraph")
92
+ if unreadable:
93
+ raise ChangesException("unreadable line: a .changes field line needs a colon")
94
+ # Debian Policy 5.1 field names ignore case, and dpkg refuses a repeated one: a reader
95
+ # keeping another copy would see other digests and architectures than debkit checks
96
+ # -> [VALIDATION.md](VALIDATION.md#repeated-fields)
97
+ names = [name.lower() for name in parsed]
98
+ if repeated := sorted({name for name in names if names.count(name) > 1}):
99
+ raise ChangesException(f"repeated field: {', '.join(repeated)}")
100
+ self.fields = dict(parsed.items())
101
+
102
+ if CHECKSUMS_SHA256 not in self.fields:
103
+ raise ChangesException("No SHA256 checksums found")
104
+
105
+ for hashstr, size, filename in parse_hash_block(self.fields[CHECKSUMS_SHA256]):
106
+ # a listed name is read from the incoming storage and names the pool key, so
107
+ # it is a bare file name -> [VALIDATION.md](VALIDATION.md#filename-safety)
108
+ if "/" in filename or is_unsafe_path(filename):
109
+ raise ChangesException(f"unsafe file name: {filename!r}")
110
+ digests = {"Size": str(size), "SHA256": hashstr}
111
+ self.update_digests(filename, digests)
112
+
113
+ def load(self, filename: str, digest_expected: str | None = None) -> None:
114
+ """Load Changes file fields from data.
115
+
116
+ Args:
117
+ filename: The filename of the data.
118
+ digest_expected: The expected digest of the data.
119
+
120
+ Raises:
121
+ ChangesException: If the file cannot be read, is empty, or is larger than
122
+ `MAX_CHANGES_BYTES`.
123
+ ChecksumException: If the checksum of the file does not match the expected checksum.
124
+ """
125
+ try:
126
+ data = read_capped(self.storage, filename, MAX_CHANGES_BYTES)
127
+ except StorageException as exc:
128
+ raise ChangesException(f"Cannot read .changes file {filename}: {exc}") from exc
129
+ except SizeLimitError as exc:
130
+ raise ChangesException(str(exc)) from exc
131
+
132
+ if not data:
133
+ raise ChangesException(f"Empty changes file: {filename}")
134
+
135
+ digest = hashlib.sha256(data).hexdigest()
136
+ if (digest_expected is not None) and (digest_expected != digest):
137
+ raise ChecksumException(
138
+ f"{filename} checksum mismatch. Expected: {digest_expected}, got: {digest}"
139
+ )
140
+ logger.debug("Parse changes file %s (%d bytes)", filename, len(data))
141
+ self.parse(data)
142
+
143
+ def get_archs(self) -> list[str]:
144
+ """Get every architecture token the Changes file names.
145
+
146
+ `dpkg-genchanges` writes one Architecture field per upload, so a source plus
147
+ binary build names `source` beside the binary arch. Reading a single token
148
+ makes the field order decide the upload, so every token is returned.
149
+
150
+ Returns:
151
+ The architecture tokens of the Changes file.
152
+ """
153
+ return self.fields.get("Architecture", DEFAULT_ARCH).split()
154
+
155
+ def names_source_arch(self) -> bool:
156
+ """Report whether the Changes file names the source architecture.
157
+
158
+ The token may sit anywhere in the field, so the answer does not depend on the
159
+ order `dpkg-genchanges` wrote -> [VALIDATION.md](VALIDATION.md#sources-stanzas).
160
+
161
+ Returns:
162
+ True when any architecture token is the source one.
163
+ """
164
+ return SOURCE_ARCH in self.get_archs()
165
+
166
+ def get_deb_files(self) -> list[str]:
167
+ """Get the .deb files in the Changes file.
168
+
169
+ Returns:
170
+ The deb files in the Changes file.
171
+ """
172
+ return [f for f in self.digests if f.endswith(".deb")]
@@ -0,0 +1,335 @@
1
+ """Class containg Debian packages (Packages objects) for each architecture."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import re
7
+ from enum import Enum
8
+ from typing import TYPE_CHECKING, Any
9
+
10
+ from txstore import StorageException
11
+
12
+ from debkit.repo.packages import Packages, PackagesException, PackagesNotFoundException
13
+ from debkit.repo.params import ARCH_ANY, SOURCE_ARCH, is_valid_arch
14
+ from debkit.repo.release import RootRelease
15
+ from debkit.repo.sources import Sources
16
+
17
+ if TYPE_CHECKING:
18
+ from txstore import Storage
19
+
20
+ from debkit.repo.package import Package
21
+ from debkit.repo.params import RepoParams
22
+
23
+ logger = logging.getLogger(__name__)
24
+ logger.addHandler(logging.NullHandler())
25
+
26
+
27
+ def container_for(arch: str) -> type[Packages]:
28
+ """Return the index container class that owns an architecture.
29
+
30
+ The source architecture is mirrored through a read-only `Sources` index, every
31
+ other one through `Packages`. Both the read and the write path resolve the class
32
+ here: `Packages.setup` names its file through `index_name`/`arch_dir`, so a
33
+ `Packages` built for the source arch would write a binary index into the canonical
34
+ `Sources` path, which the next load cannot parse
35
+ -> [VALIDATION.md](VALIDATION.md#sources-stanzas).
36
+
37
+ Args:
38
+ arch: The architecture name.
39
+
40
+ Returns:
41
+ `Sources` for the source architecture, `Packages` otherwise.
42
+ """
43
+ return Sources if arch == SOURCE_ARCH else Packages
44
+
45
+
46
+ class IndexLoad(Enum):
47
+ """What a component load skips when an arch's index does not load.
48
+
49
+ The modes and the commands using each -> [VALIDATION.md](VALIDATION.md#index-loading).
50
+
51
+ Attributes:
52
+ STRICT: Every arch must load; a missing or unreadable index raises.
53
+ WRITABLE: A missing index is skipped, so an insert starts it; an unreadable one
54
+ raises, since a save would replace it, except the never-written `Sources`.
55
+ READ_ONLY: A missing or unreadable index is skipped with a warning.
56
+ """
57
+
58
+ STRICT = "strict"
59
+ WRITABLE = "writable"
60
+ READ_ONLY = "read-only"
61
+
62
+
63
+ class ComponentException(Exception):
64
+ """Exception raised for errors in the Component class."""
65
+
66
+ def __init__(self, message: str) -> None:
67
+ """Initialize with error message."""
68
+ super().__init__(f"Component: {message}")
69
+
70
+
71
+ class Component:
72
+ """Container to store sets of Debian packages for each architecture.
73
+
74
+ Attributes:
75
+ name: The name of the component.
76
+ storage: The storage object.
77
+ params: The parameters for the Component object.
78
+ packages: 'Packages' objects by architecture.
79
+ root_release: The release object.
80
+ is_flat: Read-only; delegates to ``params.is_flat``.
81
+ """
82
+
83
+ def __init__(
84
+ self, storage: Storage, params: RepoParams, release: RootRelease, name: str
85
+ ) -> None:
86
+ """Initialize a Component object.
87
+
88
+ Args:
89
+ storage: The storage object.
90
+ params: The parameters for the Component object.
91
+ release: The release object.
92
+ name: The name of the component.
93
+ """
94
+ self.storage = storage
95
+ self.params = params
96
+ self.packages: dict[str, Packages] = {}
97
+ self.root_release = release
98
+ self.name = name
99
+
100
+ @property
101
+ def is_flat(self) -> bool:
102
+ """Whether the underlying repo layout is flat (delegates to ``params``)."""
103
+ return self.params.is_flat
104
+
105
+ def _flat_container(self, arch: str) -> Packages | None:
106
+ """Get the container a flat layout already holds for the index file of `arch`.
107
+
108
+ A flat layout names one `Packages` (and one `Sources`) file whatever the arch, so
109
+ every arch slot shares one container; separate ones would each save the whole file
110
+ and the last save would win -> [VALIDATION.md](VALIDATION.md#repository-index-paths).
111
+
112
+ Args:
113
+ arch: The architecture of the slot.
114
+
115
+ Returns:
116
+ The shared container, or None when the layout is componented or no slot holds that index
117
+ file yet.
118
+ """
119
+ if not self.is_flat:
120
+ return None
121
+ kind = container_for(arch)
122
+ return next((pkgs for pkgs in self.packages.values() if type(pkgs) is kind), None)
123
+
124
+ def containers(self) -> list[Packages]:
125
+ """Get every index container of the component, each once.
126
+
127
+ Flat arch slots share one container
128
+ -> [VALIDATION.md](VALIDATION.md#repository-index-paths).
129
+
130
+ Returns:
131
+ The distinct containers, in slot order.
132
+ """
133
+ return list({id(pkgs): pkgs for pkgs in self.packages.values()}.values())
134
+
135
+ def slot_packages(self, arch: str) -> dict[str, Package]:
136
+ """Get the packages one arch slot reports, keyed by `Filename`.
137
+
138
+ A componented slot reports its whole index. The one index of a flat layout holds
139
+ every arch, whichever are selected, so a flat arch slot reports the packages of its
140
+ arch and of `all`, as a componented `binary-<arch>/` index lists them; a package with
141
+ no `Architecture`, or the empty arch of a flat repo naming none, is reported whole.
142
+ Reports read it; payload planning reads the whole index, since a flat sync copies the
143
+ index whole -> [VALIDATION.md](VALIDATION.md#repository-index-paths).
144
+
145
+ Args:
146
+ arch: The architecture of the slot.
147
+
148
+ Returns:
149
+ The slot's packages.
150
+ """
151
+ packages = self.packages[arch]
152
+ if not (self.is_flat and arch):
153
+ return packages.packages
154
+ return {
155
+ filename: package
156
+ for filename, package in packages.packages.items()
157
+ if package.fields.get("Architecture", arch) in (arch, ARCH_ANY)
158
+ }
159
+
160
+ def load(self, archs: list[str], mode: IndexLoad = IndexLoad.WRITABLE) -> int:
161
+ """Load package sets (Packages objects) for all architectures.
162
+
163
+ An arch with no index file is skipped unless `STRICT`, so an insert can start its
164
+ index. One whose index exists but does not decode, or whose per-arch Release storage
165
+ fails, is skipped only in `READ_ONLY`, or for the never-written `Sources` index in
166
+ `WRITABLE`: a caller that saves would replace it with a fresh index holding its own
167
+ changes alone. A storage failure reading an existing index is a backend failure and
168
+ propagates in every mode -> [VALIDATION.md](VALIDATION.md#index-loading).
169
+
170
+ Args:
171
+ archs: The list of architectures.
172
+ mode: What an arch that does not load may skip. Defaults to `WRITABLE`.
173
+
174
+ Raises:
175
+ ComponentException: If an arch cannot be loaded and may not be skipped, or the
176
+ architecture check fails.
177
+ StorageException: An index exists but its storage fails to read.
178
+
179
+ Returns:
180
+ The total number of packages loaded.
181
+ """
182
+ npkgs = 0
183
+ for arch in archs:
184
+ shared = self._flat_container(arch)
185
+ if shared is not None:
186
+ self.packages[arch] = shared
187
+ continue
188
+ kind = container_for(arch)
189
+ packages = kind(self.storage, self.params)
190
+ may_skip_unreadable = mode is IndexLoad.READ_ONLY or (
191
+ mode is IndexLoad.WRITABLE and not kind.WRITABLE
192
+ )
193
+
194
+ if not self.is_flat:
195
+ try:
196
+ packages.release.load_component(self.name, arch, root_release=self.root_release)
197
+ except StorageException as exc:
198
+ if not may_skip_unreadable:
199
+ raise ComponentException(f"Cannot load {self.name}: {arch}: {exc}") from exc
200
+
201
+ logger.warning("Architecture %s not available.", arch)
202
+ continue
203
+
204
+ try:
205
+ packages.load(self.root_release, self.name, arch)
206
+ except PackagesException as exc:
207
+ missing = isinstance(exc, PackagesNotFoundException)
208
+ if mode is IndexLoad.STRICT or not (missing or may_skip_unreadable):
209
+ raise ComponentException(f"Cannot load {self.name}: {arch}: {exc}") from exc
210
+
211
+ logger.warning("Packages for %s failed: %s", arch, exc)
212
+ continue
213
+
214
+ # a per-arch Release names its own arch in `Architecture`, read first so a copied
215
+ # root `Architectures` cannot vouch for a misplaced file; the root Release reads
216
+ # the other way round -> [VALIDATION.md](VALIDATION.md#architectures)
217
+ if not self.is_flat and not packages.release.is_empty():
218
+ if "Architecture" in packages.release.fields:
219
+ comp_arch_raw = packages.release.fields["Architecture"]
220
+ elif "Architectures" in packages.release.fields:
221
+ comp_arch_raw = packages.release.fields["Architectures"]
222
+ else:
223
+ raise ComponentException("no 'Architecture' field in Release")
224
+
225
+ # `Architectures` can list multiple tokens (e.g. "amd64 arm64 all");
226
+ # `all` is universally compatible.
227
+ comp_archs = set(comp_arch_raw.split())
228
+ if arch not in comp_archs and ARCH_ANY not in comp_archs:
229
+ raise ComponentException("architecture check mismatch.")
230
+
231
+ self.packages[arch] = packages
232
+ npkgs += len(packages)
233
+ return npkgs
234
+
235
+ def save(self) -> bool:
236
+ """Save all package sets (Packages objects) for all architectures.
237
+
238
+ Returns:
239
+ True if any package was saved, False otherwise.
240
+ """
241
+ ret: bool = False
242
+ # a container shared by several flat slots is saved once
243
+ for packages in self.containers():
244
+ digests = packages.save()
245
+
246
+ if digests is None:
247
+ continue
248
+
249
+ ret = True
250
+ for filename, digest in digests.items():
251
+ self.root_release.update_digests(self.params.release_key(filename), digest)
252
+
253
+ return ret
254
+
255
+ def dump(self) -> dict[str, dict[str, Any]]:
256
+ """Dump architectures containing Packages objects to a dict.
257
+
258
+ Returns:
259
+ A dictionary where the keys are architectures and the values are the dumped packages.
260
+ """
261
+ return {
262
+ arch: packages.dump(self.slot_packages(arch).values())
263
+ for arch, packages in self.packages.items()
264
+ }
265
+
266
+ def get_indices_paths(self) -> list[str]:
267
+ """Get list of indices files paths.
268
+
269
+ Returns:
270
+ A list of indices paths for each package in the component.
271
+ """
272
+ return [path for packages in self.containers() for path in packages.get_indices_paths()]
273
+
274
+ def setup(self, archs: list[str]) -> None:
275
+ """Setup the component.
276
+
277
+ Args:
278
+ archs: The list of architectures.
279
+ """
280
+ for arch in archs:
281
+ self.packages[arch] = self._new_slot(arch)
282
+
283
+ def _new_slot(self, arch: str) -> Packages:
284
+ """Get a fresh container for `arch`, or the one a flat layout already holds.
285
+
286
+ Args:
287
+ arch: The architecture of the slot.
288
+
289
+ Returns:
290
+ The container the slot holds.
291
+ """
292
+ shared = self._flat_container(arch)
293
+ if shared is not None:
294
+ return shared
295
+ packages = container_for(arch)(self.storage, self.params)
296
+ packages.setup(self.name, arch)
297
+ return packages
298
+
299
+ def insert_pkg(self, arch: str, package: Package) -> None:
300
+ """Add deb package object to the component.
301
+
302
+ Args:
303
+ arch: The architecture.
304
+ package: The Package object to insert.
305
+
306
+ Raises:
307
+ ComponentException: If ``arch`` is neither empty nor an architecture name.
308
+ """
309
+ # the arch names the `binary-<arch>/` index path, so a caller that skipped the
310
+ # action-layer check cannot steer it -> [VALIDATION.md](VALIDATION.md#architectures)
311
+ if arch and not is_valid_arch(arch):
312
+ raise ComponentException(f"invalid architecture: {arch!r}")
313
+ if arch not in self.packages:
314
+ self.packages[arch] = self._new_slot(arch)
315
+
316
+ logger.info("Insert package: %s %s", package, arch)
317
+
318
+ self.packages[arch].insert(package)
319
+
320
+ def remove_pkg(self, fields_patterns: dict[str, re.Pattern[str]]) -> set[str]:
321
+ """Drop matching packages from every arch index of the component; storage is untouched.
322
+
323
+ A mirrored `Sources` index removes nothing →
324
+ [VALIDATION.md](VALIDATION.md#sources-stanzas).
325
+
326
+ Args:
327
+ fields_patterns: Compiled pattern per package field.
328
+
329
+ Returns:
330
+ Filenames dropped from any arch, each once.
331
+ """
332
+ removed: set[str] = set()
333
+ for packages in self.containers():
334
+ removed |= packages.remove(fields_patterns)
335
+ return removed