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.
@@ -0,0 +1,348 @@
1
+ """What the other dists of a shared target root claim, and the target's reconciliation lists.
2
+
3
+ A componented root holds many dists under `dists/<dist>/` sharing one `pool/`; what each other
4
+ dist's indices list keeps a path from deletion or replacement
5
+ -> [VALIDATION.md](VALIDATION.md#index-selection).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import logging
11
+ import re
12
+ from collections.abc import Collection, Mapping
13
+ from typing import TYPE_CHECKING, NamedTuple
14
+
15
+ from txstore import StorageException, compare_digests
16
+
17
+ from debkit.repo import Repo, RepoReadException
18
+ from debkit.repo.component import ComponentException, IndexLoad
19
+ from debkit.repo.gnupg import GPGVerifyException
20
+ from debkit.repo.hashes import ChecksumException, has_sha
21
+ from debkit.repo.index_selection import INDEX_TAIL, match_index_tail
22
+ from debkit.repo.package import PackageException
23
+ from debkit.repo.packages import PackagesException
24
+ from debkit.repo.params import SOURCE_ARCH, RepoParams, is_safe_name
25
+ from debkit.repo.release import Release, ReleaseReadException, RootRelease
26
+
27
+ if TYPE_CHECKING:
28
+ from txstore import Storage
29
+
30
+ logger = logging.getLogger(__name__)
31
+ logger.addHandler(logging.NullHandler())
32
+
33
+
34
+ class SharedRoot(NamedTuple):
35
+ """What the other dists of a shared target root claim.
36
+
37
+ The rules are in [VALIDATION.md](VALIDATION.md#index-selection).
38
+
39
+ Attributes:
40
+ prefix: The synced dist's own index tree, `dists/<dist>/`, or empty for a flat layout.
41
+ claimed: Paths another dist holds: its `dists/<dist>/` tree and the payloads its indices
42
+ list.
43
+ complete: Whether every other dist loaded, so `claimed` holds all of its payloads.
44
+ recorded: Payload path -> the digests every index of every other dist records for it;
45
+ None only when the caller did not ask for them.
46
+ """
47
+
48
+ prefix: str
49
+ claimed: frozenset[str]
50
+ complete: bool
51
+ recorded: Mapping[str, tuple[dict[str, str], ...]] | None = None
52
+
53
+ def deletable(self, path: str) -> bool:
54
+ """Report whether deleting `path` from the root leaves every other dist's claims intact.
55
+
56
+ Args:
57
+ path: Storage path in the target root.
58
+
59
+ Returns:
60
+ False for a path another dist claims, and for any path outside the own index tree
61
+ while another dist's payloads are unknown.
62
+ """
63
+ if path in self.claimed:
64
+ return False
65
+ return self.complete or path.startswith(self.prefix)
66
+
67
+ def corrupt_deletable(self, path: str, digests: dict[str, str]) -> bool:
68
+ """Report whether a payload whose bytes fail the own indices may be deleted.
69
+
70
+ Another dist's index may record exactly these bytes, so they are kept for it; one that
71
+ records other bytes loses nothing, since the bytes are wrong for it too. A record with
72
+ no SHA digest cannot tell, so it keeps them
73
+ -> [VALIDATION.md](VALIDATION.md#index-selection).
74
+
75
+ Args:
76
+ path: Storage path of the payload in the target root.
77
+ digests: The digests of the bytes the root holds at `path`.
78
+
79
+ Returns:
80
+ False while another dist's payloads are unknown, when a record of `path` carries no
81
+ SHA digest, and when one records `digests`; without collected digests, what
82
+ `deletable` says, which never deletes a claimed path.
83
+ """
84
+ if self.recorded is None:
85
+ return self.deletable(path)
86
+ if not self.complete:
87
+ return False
88
+ records = self.recorded.get(path, ())
89
+ if not all(has_sha(record) for record in records):
90
+ return False
91
+ return not any(compare_digests(record, digests) for record in records)
92
+
93
+ def replaceable(self, path: str, digests: dict[str, str]) -> bool:
94
+ """Report whether a held payload may be overwritten with the bytes the own source records.
95
+
96
+ Another dist's index pinning other bytes at the same key would serve its clients a hash
97
+ mismatch once they change; a record with no SHA digest cannot tell, so it refuses too
98
+ -> [VALIDATION.md](VALIDATION.md#index-selection).
99
+
100
+ Args:
101
+ path: Storage path of the payload in the target root.
102
+ digests: The digests the own source records for `path`.
103
+
104
+ Returns:
105
+ True when no other dist records `path`, or every record of it carries a SHA digest
106
+ matching `digests`; False while another dist's payloads are unknown.
107
+ """
108
+ if not self.complete:
109
+ return False
110
+ if self.recorded is None:
111
+ return path not in self.claimed
112
+ records = self.recorded.get(path, ())
113
+ return all(has_sha(record) and compare_digests(record, digests) for record in records)
114
+
115
+
116
+ class ConsistencyLists(NamedTuple):
117
+ """What `RepoRW.consistency_lists` found in the repository's own storage listing.
118
+
119
+ Attributes:
120
+ missing: Payloads and parsed component indices the listing lacks, sorted.
121
+ orphans: Listed paths that no index and no other dist claims, sorted.
122
+ shared: What the other dists sharing the root claim, from the same listing.
123
+ """
124
+
125
+ missing: list[str]
126
+ orphans: list[str]
127
+ shared: SharedRoot
128
+
129
+
130
+ # a flat layout has no `dists/` tree, so no other dist shares its root
131
+ _FLAT_ROOT = SharedRoot("", frozenset(), complete=True, recorded={})
132
+
133
+
134
+ def _has_dists_tree(params: RepoParams) -> bool:
135
+ """Report whether the repository's indices sit under a `dists/<dist>/` tree.
136
+
137
+ Args:
138
+ params: The repository's parameters.
139
+
140
+ Returns:
141
+ False for a flat layout, and for one with no dist to name the tree.
142
+ """
143
+ return not params.is_flat and bool(params.indices_prefix)
144
+
145
+
146
+ def unlisted_shared_root(params: RepoParams) -> SharedRoot:
147
+ """The claims of a root whose storage cannot list.
148
+
149
+ Args:
150
+ params: The repository's parameters.
151
+
152
+ Returns:
153
+ No claims; for a componented layout incomplete, so nothing outside the own index tree
154
+ is deletable.
155
+ """
156
+ if not _has_dists_tree(params):
157
+ return _FLAT_ROOT
158
+ return SharedRoot(f"{params.indices_prefix}/", frozenset(), complete=False, recorded={})
159
+
160
+
161
+ # what a neighbour dist's load may raise: `RootRelease.load`, the unsafe-component refusal in
162
+ # `_claims_of`, and `Repo.load` and its Raises; every one leaves that dist's payloads unknown
163
+ _NOT_LOADED = (
164
+ RepoReadException,
165
+ ReleaseReadException,
166
+ GPGVerifyException,
167
+ ComponentException,
168
+ PackagesException,
169
+ PackageException,
170
+ ChecksumException,
171
+ StorageException,
172
+ )
173
+
174
+
175
+ # a listed index key whose Release names no components: the component is everything before
176
+ # the index tail, so `updates/main/binary-amd64/Packages` reads as component `updates/main`
177
+ _LISTED_INDEX = re.compile(rf"(?P<comp>.+)/(?:{INDEX_TAIL.pattern})")
178
+
179
+
180
+ def _listed_slots(release: Release) -> dict[str, set[str]]:
181
+ """Map each component of a root Release to the archs whose indices it lists.
182
+
183
+ A component may hold `/`, so a key is matched below a component the `Components` field
184
+ declares, the longest first; a key no declared component explains still claims, with the
185
+ key's head as its component, since a missed index would leave its payloads deletable
186
+ -> [VALIDATION.md](VALIDATION.md#index-selection).
187
+
188
+ Args:
189
+ release: A loaded root Release.
190
+
191
+ Returns:
192
+ Component -> its binary archs, plus `SOURCE_ARCH` for a listed `Sources`.
193
+ """
194
+ declared = sorted(release.fields.get("Components", "").split(), key=len, reverse=True)
195
+ slots: dict[str, set[str]] = {}
196
+ for key in release.digests:
197
+ for comp in declared:
198
+ if tail := match_index_tail(key, comp):
199
+ slots.setdefault(comp, set()).add(tail["arch"] or SOURCE_ARCH)
200
+ break
201
+ else:
202
+ if listed := _LISTED_INDEX.fullmatch(key):
203
+ slots.setdefault(listed["comp"], set()).add(listed["arch"] or SOURCE_ARCH)
204
+ return slots
205
+
206
+
207
+ def _claims_of(storage: Storage, dist: str) -> dict[str, list[dict[str, str]]]:
208
+ """Load another dist of the root and return the payloads its indices list.
209
+
210
+ Exactly the indices its root Release lists are loaded, and each must load: one skipped
211
+ would leave its payloads unclaimed, so they would read as orphans
212
+ -> [VALIDATION.md](VALIDATION.md#index-selection).
213
+
214
+ Args:
215
+ storage: The target storage.
216
+ dist: The other dist.
217
+
218
+ Raises:
219
+ RepoReadException: A listed component is not a safe name.
220
+ ReleaseReadException: The dist has no root Release, or it does not parse.
221
+ ComponentException: A listed index is missing or does not load.
222
+
223
+ Returns:
224
+ Each payload path the dist's binary and source indices list -> the digests each index
225
+ records, so a path two indices record differently keeps both.
226
+ """
227
+ release = RootRelease(storage, RepoParams(dist=dist, verify_gpg=False, verify_digests=False))
228
+ release.load()
229
+
230
+ claims: dict[str, list[dict[str, str]]] = {}
231
+ for comp, archs in sorted(_listed_slots(release).items()):
232
+ if not is_safe_name(comp):
233
+ raise RepoReadException(f"dist {dist} lists an unsafe component {comp!r}")
234
+ params = RepoParams(
235
+ dist=dist,
236
+ components=[comp],
237
+ archs=sorted(archs),
238
+ verify_gpg=False,
239
+ verify_digests=False,
240
+ )
241
+ repo = Repo(storage, params)
242
+ repo.load(IndexLoad.STRICT)
243
+ # every slot, not `get_packages`, which yields a path shared by two arch indices once
244
+ for component in repo.components.values():
245
+ for packages in component.packages.values():
246
+ for package in packages.packages.values():
247
+ claims.setdefault(str(package), []).append(package.get_digests())
248
+ return claims
249
+
250
+
251
+ def shared_root_claims(
252
+ storage: Storage,
253
+ params: RepoParams,
254
+ existing: set[str] | None = None,
255
+ *,
256
+ with_digests: bool = False,
257
+ ) -> SharedRoot:
258
+ """Collect what the other dists of a componented target root claim.
259
+
260
+ A Debian root holds many dists under `dists/<dist>/` sharing one `pool/`. Each other dist
261
+ is loaded unverified, since its claims only ever keep a path, never copy one
262
+ -> [VALIDATION.md](VALIDATION.md#index-selection).
263
+
264
+ Args:
265
+ storage: The target storage.
266
+ params: The synced dist's parameters.
267
+ existing: Paths the target listing returned; None lists the storage, so a caller
268
+ that already listed it judges claims against the same listing. A flat layout is
269
+ never listed.
270
+ with_digests: Also keep the digests each index of each other dist records, which
271
+ `SharedRoot.corrupt_deletable` and `SharedRoot.replaceable` read. Defaults to
272
+ False: a caller that only deletes keeps them out of memory.
273
+
274
+ Returns:
275
+ The claims; none for a flat layout, which has no `dists/` tree, and unknown when the
276
+ storage cannot list.
277
+ """
278
+ if not _has_dists_tree(params):
279
+ return _FLAT_ROOT
280
+ if existing is None:
281
+ try:
282
+ existing = set(storage.list())
283
+ except NotImplementedError:
284
+ return unlisted_shared_root(params)
285
+
286
+ prefix = f"{params.indices_prefix}/"
287
+ foreign = {
288
+ path for path in existing if path.startswith("dists/") and not path.startswith(prefix)
289
+ }
290
+ dists = sorted({path.split("/")[1] for path in foreign if path.count("/") >= 2})
291
+ claimed = set(foreign)
292
+ recorded: dict[str, list[dict[str, str]]] = {}
293
+ complete = True
294
+
295
+ for dist in dists:
296
+ if not is_safe_name(dist):
297
+ logger.warning("Shared root dist %r is not a safe name; its payloads are kept.", dist)
298
+ complete = False
299
+ continue
300
+ try:
301
+ claims = _claims_of(storage, dist)
302
+ except _NOT_LOADED as exc:
303
+ logger.warning(
304
+ "Dist %s shares the target root but did not load (%s); "
305
+ "nothing outside %s is deleted or overwritten.",
306
+ dist,
307
+ exc,
308
+ prefix,
309
+ )
310
+ complete = False
311
+ continue
312
+ claimed.update(claims)
313
+ if with_digests:
314
+ for path, records in claims.items():
315
+ recorded.setdefault(path, []).extend(records)
316
+
317
+ if dists:
318
+ logger.info("Shared root: keeping what dists %s claim", ", ".join(dists))
319
+ return SharedRoot(
320
+ prefix,
321
+ frozenset(claimed),
322
+ complete,
323
+ {path: tuple(records) for path, records in recorded.items()} if with_digests else None,
324
+ )
325
+
326
+
327
+ def missing_and_unclaimed(
328
+ payloads: set[str],
329
+ indices: Collection[str],
330
+ existing_files: set[str],
331
+ planned: set[str] | None = None,
332
+ ) -> tuple[set[str], set[str]]:
333
+ """Compare a target listing with the package and index sets.
334
+
335
+ Args:
336
+ payloads: Every payload path the package set holds.
337
+ indices: Every index path the index set holds.
338
+ existing_files: Paths the target listing returned.
339
+ planned: Paths a package diff already copies or removes, left out of both results.
340
+ Defaults to None (nothing planned).
341
+
342
+ Returns:
343
+ The payloads the listing lacks, and the listed paths neither set holds.
344
+ """
345
+ planned = planned or set()
346
+ repair = payloads - planned - existing_files
347
+ purge = {file for file in existing_files - payloads - planned if file not in indices}
348
+ return repair, purge
debkit/repo/sources.py ADDED
@@ -0,0 +1,165 @@
1
+ """Class expanding a Debian `Sources` index into one record per source payload file."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import posixpath
7
+ import re
8
+ from typing import Any, ClassVar
9
+
10
+ from txstore import is_unsafe_path
11
+
12
+ from debkit.repo.hashes import CHECKSUM_FIELDS, has_sha, parse_hash_block
13
+ from debkit.repo.package import FILENAME_FIELD_KEY, Package
14
+ from debkit.repo.packages import Packages, PackagesException
15
+ from debkit.repo.params import is_safe_name
16
+ from debkit.repo.stanza import parse_stanza
17
+
18
+ logger = logging.getLogger(__name__)
19
+ logger.addHandler(logging.NullHandler())
20
+
21
+ # Stanza fields copied onto every payload record of that stanza.
22
+ STANZA_FIELDS = ("Package", "Version")
23
+
24
+
25
+ class Sources(Packages):
26
+ """Read-only package container fed by a `Sources` index.
27
+
28
+ A `Sources` stanza names several payload files under one `Directory`; each
29
+ becomes a `Package` keyed by its `Filename`, so the sync diff, the purge and
30
+ repair passes, and checksum verification consume source payloads exactly as they
31
+ consume binary ones. `len()` counts payload files, not stanzas.
32
+
33
+ The index itself is mirrored as an opaque object and is never regenerated, so
34
+ this container refuses every mutation -> [VALIDATION.md](VALIDATION.md#sources-stanzas).
35
+ """
36
+
37
+ WRITABLE: ClassVar[bool] = False
38
+
39
+ def _parse_indices(self, data: str) -> int:
40
+ """Expand every stanza into one `Package` per payload file.
41
+
42
+ Args:
43
+ data: Decoded `Sources` index.
44
+
45
+ Raises:
46
+ PackagesException: If a stanza holds an unreadable line, names no usable
47
+ `Directory`, an unsafe file name, disagreeing sizes, or a payload without a SHA
48
+ digest.
49
+
50
+ Returns:
51
+ The number of payload files known after parsing.
52
+ """
53
+ for block in self._stanzas(data):
54
+ for package in self._expand_stanza(block):
55
+ name = str(package)
56
+ previous = self.packages.get(name)
57
+ if previous is not None and previous.get_digests() != package.get_digests():
58
+ logger.debug("%s is listed with differing digests across stanzas.", name)
59
+ self.packages[name] = package
60
+
61
+ return len(self)
62
+
63
+ def _expand_stanza(self, block: str) -> list[Package]:
64
+ """Build one `Package` per file named by a single `Sources` stanza.
65
+
66
+ `Package.parse` is not reused: it folds multi-line values onto one line, which
67
+ destroys the hash blocks, and it demands a `Filename` no stanza carries.
68
+
69
+ Args:
70
+ block: One stanza, without its trailing blank line.
71
+
72
+ Raises:
73
+ PackagesException: On an unreadable line, a missing or unsafe `Directory`, one in
74
+ the `dists/` tree of a componented layout, a file name with a path segment, a
75
+ size that differs between hash blocks, or a payload carrying no SHA digest.
76
+
77
+ Returns:
78
+ One record per payload file, in first-seen order.
79
+ """
80
+ parsed, _, unreadable = parse_stanza(block)
81
+ # the fields after an unreadable line would be missing, and with them payload files
82
+ # the sync would neither copy nor keep -> [VALIDATION.md](VALIDATION.md#blank-lines)
83
+ if unreadable:
84
+ raise PackagesException("unreadable line in Sources stanza: a field line needs a colon")
85
+ fields = dict(parsed.items())
86
+
87
+ directory = posixpath.normpath(fields.get("Directory", "").strip())
88
+ if not is_safe_name(directory):
89
+ raise PackagesException(
90
+ f"no usable Directory in Sources stanza: {fields.get('Package')}"
91
+ )
92
+ # a payload under `dists/` would overwrite the metadata of any dist sharing the root
93
+ # -> [VALIDATION.md](VALIDATION.md#filename-safety)
94
+ if self.params.is_index_tree_key(directory):
95
+ raise PackagesException(
96
+ f"Sources stanza Directory lies in the dists/ tree: {directory}"
97
+ )
98
+
99
+ stanza = {key: fields[key].strip() for key in STANZA_FIELDS if key in fields}
100
+ records: dict[str, dict[str, Any]] = {}
101
+
102
+ for field, algorithm in CHECKSUM_FIELDS.items():
103
+ if field not in fields:
104
+ continue
105
+
106
+ for hashstr, size, name in parse_hash_block(fields[field]):
107
+ filename = f"{directory}/{name}"
108
+ if "/" in name or is_unsafe_path(filename):
109
+ raise PackagesException(f"unsafe file name in Sources stanza: {filename}")
110
+
111
+ record = records.setdefault(
112
+ name, {**stanza, FILENAME_FIELD_KEY: filename, "Size": size}
113
+ )
114
+ if record["Size"] != size:
115
+ raise PackagesException(f"{filename} has a different size in each hash block")
116
+ record[algorithm] = hashstr
117
+
118
+ for record in records.values():
119
+ # a payload needs an algorithm comparison keeps: an MD5-only record would
120
+ # compare unequal forever and be recopied on every sync
121
+ # -> [CRYPTO.md](CRYPTO.md#checksums)
122
+ if not has_sha(record):
123
+ raise PackagesException(f"{record[FILENAME_FIELD_KEY]} carries no SHA digest")
124
+
125
+ return [Package(fields=record) for record in records.values()]
126
+
127
+ def save(self) -> dict[str, dict[str, str]] | None:
128
+ """Write nothing: the mirrored `Sources` object is the only source of truth.
129
+
130
+ Returns:
131
+ Always `None`, the value `Component.save` reads as "nothing was written".
132
+ """
133
+ return None
134
+
135
+ def insert(self, package: Package) -> None:
136
+ """Refuse: a `Sources` index is mirrored, never composed.
137
+
138
+ Args:
139
+ package: Ignored.
140
+
141
+ Raises:
142
+ PackagesException: Always.
143
+ """
144
+ raise PackagesException("Sources index is read-only")
145
+
146
+ def remove(self, fields: dict[str, re.Pattern[str]]) -> set[str]:
147
+ """Remove nothing: a `Sources` index is mirrored, never composed.
148
+
149
+ Returning the base contract's "nothing removed" lets a caller iterate every
150
+ container without knowing which one is read-only; a match is logged as kept, so
151
+ the caller's "nothing matched" is not the only word on it
152
+ -> [VALIDATION.md](VALIDATION.md#sources-stanzas).
153
+
154
+ Args:
155
+ fields: Compiled pattern per package field.
156
+
157
+ Returns:
158
+ Always empty.
159
+ """
160
+ if kept := self.matching(fields):
161
+ logger.warning(
162
+ "%d source payloads match but the mirrored Sources index is read-only; kept.",
163
+ len(kept),
164
+ )
165
+ return set()
debkit/repo/stanza.py ADDED
@@ -0,0 +1,47 @@
1
+ """Single-paragraph control files read through the email parser."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from email.message import Message
6
+ from email.parser import Parser
7
+ from typing import NamedTuple
8
+
9
+
10
+ class Stanza(NamedTuple):
11
+ """The first paragraph of a control file, parsed.
12
+
13
+ Attributes:
14
+ message: The fields of the first paragraph, in file order, repeats kept.
15
+ more_paragraphs: A field follows an empty line: the file held more than one
16
+ paragraph, which a single-paragraph file must not.
17
+ unreadable: A line of the first paragraph is neither a field, a continuation, nor
18
+ empty, so the email parser stopped there and every field after it is missing.
19
+ """
20
+
21
+ message: Message
22
+ more_paragraphs: bool
23
+ unreadable: bool
24
+
25
+
26
+ def parse_stanza(text: str) -> Stanza:
27
+ """Parse the first paragraph of a `.changes`, a `Release`, or one `Sources` stanza.
28
+
29
+ Debian Policy 5.1 ends a paragraph at an empty line. CRLF line ends are read as LF and
30
+ leading empty lines are skipped; what a later paragraph or an unreadable line means is
31
+ the caller's rule -> [VALIDATION.md](VALIDATION.md#blank-lines). A line of only spaces
32
+ or tabs is not empty: it continues the field before it, as apt reads it.
33
+
34
+ Args:
35
+ text: The decoded file.
36
+
37
+ Returns:
38
+ The first paragraph's fields, whether more paragraphs follow, and whether a line
39
+ hid the fields after it.
40
+ """
41
+ lines = text.replace("\r\n", "\n").lstrip("\n").split("\n")
42
+ end = lines.index("") if "" in lines else len(lines)
43
+ message = Parser().parsestr("".join(f"{line}\n" for line in lines[:end]))
44
+ # every line went to the parser as a header; one it cannot read as a field or a
45
+ # continuation ends the headers there and leaves the rest as a payload
46
+ unreadable = bool(message.get_payload()) or bool(message.defects)
47
+ return Stanza(message, any(lines[end:]), unreadable)