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/hashes.py ADDED
@@ -0,0 +1,139 @@
1
+ """Debian hash blocks and the per-file digest table of a `Release` or index.
2
+
3
+ The digest helpers and the algorithm-name lists come from `txstore`; this module owns what
4
+ is Debian-specific on top of them -> [CRYPTO.md](CRYPTO.md#checksums).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ from collections.abc import Mapping
11
+
12
+ from txstore import COMPARE_HASH_LIST, compare_digests
13
+
14
+ __all__ = [
15
+ "CHECKSUMS_SHA256",
16
+ "CHECKSUM_FIELDS",
17
+ "ChecksumException",
18
+ "HexDigests",
19
+ "has_sha",
20
+ "parse_hash_block",
21
+ "parse_size",
22
+ ]
23
+
24
+ # A `Sources` or `.changes` hash-block field -> the algorithm its digests are in; a `Release`
25
+ # names its hash fields after the algorithm itself -> [CRYPTO.md](CRYPTO.md#checksums)
26
+ CHECKSUMS_SHA256 = "Checksums-Sha256"
27
+ CHECKSUM_FIELDS = {
28
+ "Files": "MD5Sum",
29
+ "Checksums-Sha1": "SHA1",
30
+ CHECKSUMS_SHA256: "SHA256",
31
+ "Checksums-Sha512": "SHA512",
32
+ }
33
+
34
+
35
+ def has_sha(record: Mapping[str, object]) -> bool:
36
+ """Report whether a digest record holds an algorithm `compare_digests` matches on.
37
+
38
+ Args:
39
+ record: Digest record keyed by algorithm name; other keys are ignored.
40
+
41
+ Returns:
42
+ True when the record carries a SHA digest; an MD5-only or empty one cannot tell bytes
43
+ apart -> [CRYPTO.md](CRYPTO.md#checksums).
44
+ """
45
+ return any(algorithm in record for algorithm in COMPARE_HASH_LIST)
46
+
47
+
48
+ def parse_size(value: object) -> int | None:
49
+ """Read a `Size` field as a byte count.
50
+
51
+ Args:
52
+ value: The field value.
53
+
54
+ Returns:
55
+ The byte count, or None when the value is not a run of ASCII digits.
56
+ """
57
+ size = str(value)
58
+ return int(size) if size.isascii() and size.isdigit() else None
59
+
60
+
61
+ def parse_hash_block(text: str) -> list[tuple[str, str, str]]:
62
+ """Split a Debian hash block into `(hexdigest, size, filename)` triples.
63
+
64
+ A hash block is the multi-line value of a `Release` hash field, a
65
+ `Checksums-<algorithm>` field, or the `Files` field of a `Sources` stanza:
66
+ whitespace-separated runs of three tokens. A trailing partial run is dropped.
67
+ The five-column `Files` field of a `.changes` file has a different shape and does
68
+ not belong here -> [CRYPTO.md](CRYPTO.md#checksums).
69
+
70
+ Args:
71
+ text: Field value, continuation indentation included.
72
+
73
+ Returns:
74
+ One triple per complete run, in file order.
75
+ """
76
+ parts = re.split(r"\s+", text.strip())
77
+ return list(zip(*[iter(parts)] * 3, strict=False))
78
+
79
+
80
+ class ChecksumException(Exception):
81
+ """Exception raised for digest mismatch or distrustful object failures."""
82
+
83
+ def __init__(self, message: str) -> None:
84
+ """Initialize the exception with a checksum error message.
85
+
86
+ Args:
87
+ message: Explanation of the error.
88
+ """
89
+ super().__init__(f"Checksum: {message}")
90
+
91
+
92
+ class HexDigests:
93
+ """Class for managing checksums of files.
94
+
95
+ Attributes:
96
+ digests: The checksums of files.
97
+ """
98
+
99
+ def __init__(self) -> None:
100
+ """Initialize the HexDigests object."""
101
+ self.digests: dict[str, dict[str, str]] = {}
102
+
103
+ def verify_digests(self, filename: str, incoming_digests: dict[str, str]) -> bool:
104
+ """Verify checksum of a file.
105
+
106
+ Args:
107
+ filename: The filename to verify.
108
+ incoming_digests: The checksums to verify.
109
+
110
+ Returns:
111
+ True if the checksum is valid, False otherwise.
112
+ """
113
+ if filename not in self.digests:
114
+ return False
115
+
116
+ return compare_digests(self.digests[filename], incoming_digests)
117
+
118
+ def declared_size(self, filename: str) -> int | None:
119
+ """Get the `Size` the digest table records for a file.
120
+
121
+ Args:
122
+ filename: The filename to look up.
123
+
124
+ Returns:
125
+ The recorded size, or None when the file or a well-formed size is not recorded.
126
+ """
127
+ return parse_size(self.digests.get(filename, {}).get("Size", ""))
128
+
129
+ def update_digests(self, filename: str, incoming_digests: dict[str, str]) -> None:
130
+ """Update checksums of a file.
131
+
132
+ Args:
133
+ filename: The filename to update.
134
+ incoming_digests: The checksums to update.
135
+ """
136
+ if filename not in self.digests:
137
+ self.digests[filename] = {}
138
+
139
+ self.digests[filename].update(incoming_digests)
@@ -0,0 +1,224 @@
1
+ """Index selection rules: which Release-listed indices a mirror carries.
2
+
3
+ Pure functions over Release keys -> [VALIDATION.md](VALIDATION.md#index-selection).
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import fnmatch
9
+ import logging
10
+ import re
11
+
12
+ from debkit.repo.params import ARCH_ANY, SOURCE_ARCH, RepoParams
13
+
14
+ logger = logging.getLogger(__name__)
15
+ logger.addHandler(logging.NullHandler())
16
+
17
+ # Index directories no container parses. `Packages` opens only
18
+ # `<component>/binary-<arch>/Packages*` and `<component>/source/Sources*`, so an index
19
+ # under one of these is mirrored while the payloads it names never join the package
20
+ # set -> [VALIDATION.md](VALIDATION.md#index-selection).
21
+ UNPARSED_INDEX_DIRS = ("debian-installer",)
22
+
23
+ # Prefix of an installer image tree segment, `installer-<arch>/`, where `<arch>` is one
24
+ # the repository knows. The Release lists the checksum manifests it holds, not the
25
+ # images themselves, so mirroring them copies manifests for a tree the mirror does not
26
+ # carry.
27
+ UNPARSED_INDEX_DIR_PREFIX = "installer-"
28
+
29
+ # File names listing the same udeb payloads from outside `debian-installer/`:
30
+ # `Contents-udeb-<arch>` maps paths to packages the package set never gains.
31
+ UNPARSED_INDEX_NAME_PREFIXES = ("Contents-udeb",)
32
+
33
+ # Directory and file stem of the source indices, `source/Sources*`.
34
+ SOURCE_INDEX_NAMES = (RepoParams.arch_dir(SOURCE_ARCH), RepoParams.index_name(SOURCE_ARCH))
35
+
36
+ # a binary or source index key below its component, `binary-<arch>/Packages[.<ext>]` or
37
+ # `source/Sources[.<ext>]`; a component may hold `/`, so the key is matched below a known one
38
+ INDEX_TAIL = re.compile(r"(?:binary-(?P<arch>[^/]+)/Packages|source/Sources)(?:\.[^/]+)?")
39
+
40
+
41
+ def match_index_tail(key: str, component: str) -> re.Match[str] | None:
42
+ """Match a Release key as a binary or source index of `component`.
43
+
44
+ Args:
45
+ key: A Release key, relative to the dist.
46
+ component: A component name, which may hold `/`.
47
+
48
+ Returns:
49
+ The index tail match, whose `arch` group is None for `Sources`; None when the key is
50
+ no index of `component`.
51
+ """
52
+ if not key.startswith(f"{component}/"):
53
+ return None
54
+ return INDEX_TAIL.fullmatch(key[len(component) + 1 :])
55
+
56
+
57
+ def _split_component(key: str, components: set[str] | None) -> tuple[str | None, str]:
58
+ """Split a Release key into its component segment and the path below it.
59
+
60
+ The component is a name the repository chose, so the structural rules read only
61
+ the path below it: a component called `extra-armhf` or `installer-extras` says
62
+ nothing about the architecture or the shape of the indices under it. Within this
63
+ selection, one split feeds both the component membership test and those rules, so the
64
+ two never disagree on where a component ends; the shared-root claims split against
65
+ another dist's declared components instead
66
+ -> [VALIDATION.md](VALIDATION.md#index-selection).
67
+
68
+ A component may hold `/`, as `updates/main` does, so the key is matched against the
69
+ selected components, the longest first; a key under none of them splits at its first
70
+ `/`, which names a component outside the selection.
71
+
72
+ Args:
73
+ key: Path as the Release lists it, relative to the layout prefix.
74
+ components: Selected components, or `None` for a flat repo whose paths carry no component
75
+ segment.
76
+
77
+ Returns:
78
+ The component and the key below it, or `None` and the whole key for a flat repo and for a
79
+ key with no `/`, which belongs to no component.
80
+ """
81
+ if components is None or "/" not in key:
82
+ return None, key
83
+ for component in sorted(components, key=len, reverse=True):
84
+ if key.startswith(f"{component}/"):
85
+ return component, key[len(component) + 1 :]
86
+ component, _, rest = key.partition("/")
87
+ return component, rest
88
+
89
+
90
+ def _unselected_arch_token(key: str, archs: set[str], arch_universe: set[str]) -> str | None:
91
+ """Find an architecture token in `key` the repository knows but has not selected.
92
+
93
+ A token is a `-<arch>` run ending at a `.`, a `/`, or the end of the key. Several
94
+ known architectures can end at the same position, as `amd64` does inside
95
+ `kfreebsd-amd64`; the longest one owns the token, because that is the name the
96
+ repository publishes the file under. Matching the shorter one would drop
97
+ `binary-kfreebsd-amd64/Packages.xz` whenever `amd64` itself was unselected.
98
+ Alternatives are ordered longest first, so the leftmost-first match `re` returns
99
+ is also the longest at each token.
100
+
101
+ Args:
102
+ key: Release key below its component segment -> `_split_component`.
103
+ archs: Selected architectures.
104
+ arch_universe: Every architecture this repository knows about.
105
+
106
+ Returns:
107
+ The unselected architecture owning a token, or `None` when every token in the key belongs to
108
+ a selected architecture.
109
+ """
110
+ if not arch_universe:
111
+ return None
112
+
113
+ alternatives = "|".join(
114
+ re.escape(arch) for arch in sorted(arch_universe, key=len, reverse=True)
115
+ )
116
+ wanted = archs | {ARCH_ANY}
117
+
118
+ for match in re.finditer(rf"-({alternatives})(?=[./]|$)", key):
119
+ if match.group(1) not in wanted:
120
+ return match.group(1)
121
+
122
+ return None
123
+
124
+
125
+ def _is_unparsed_index(key: str, arch_universe: set[str]) -> bool:
126
+ """Report whether a Release key names an index nothing parses.
127
+
128
+ A `debian-installer` index names `.udeb` payloads that never reach the package
129
+ set, so mirroring it would copy the index, leave the payloads behind, and purge
130
+ any the target already held as orphans: apt would read an index whose objects
131
+ 404. This is the rule `Sources` already follows, for the same reason.
132
+
133
+ Two shapes carry the same content from outside that directory, and each needs its
134
+ own test: `installer-<arch>/` image trees are a directory segment naming an
135
+ architecture the repository knows, and the `Contents-udeb-<arch>` listing is a
136
+ file name -> [VALIDATION.md](VALIDATION.md#index-selection).
137
+
138
+ Args:
139
+ key: Release key below its component segment -> `_split_component`.
140
+ arch_universe: Every architecture this repository knows about.
141
+
142
+ Returns:
143
+ True when the key names an index nothing parses.
144
+ """
145
+ parts = key.split("/")
146
+ installer_dirs = {f"{UNPARSED_INDEX_DIR_PREFIX}{arch}" for arch in arch_universe}
147
+ if any(part in UNPARSED_INDEX_DIRS or part in installer_dirs for part in parts[:-1]):
148
+ return True
149
+ return any(part.partition(".")[0].startswith(UNPARSED_INDEX_NAME_PREFIXES) for part in parts)
150
+
151
+
152
+ def _is_source_index(key: str) -> bool:
153
+ """Report whether a Release key names a source index.
154
+
155
+ In a componented repository they live under `<component>/source/`, in a flat one
156
+ they are the `Sources*` files at the root, and `Contents-source` carries a
157
+ `-source` token. This is the whole rule, so the architecture token rule never has
158
+ to know the source architecture -> [VALIDATION.md](VALIDATION.md#index-selection).
159
+
160
+ Args:
161
+ key: Release key below its component segment -> `_split_component`.
162
+
163
+ Returns:
164
+ True when the key belongs to the source architecture.
165
+ """
166
+ stems = [part.partition(".")[0] for part in key.split("/")]
167
+ return any(stem in SOURCE_INDEX_NAMES or stem.endswith(f"-{SOURCE_ARCH}") for stem in stems)
168
+
169
+
170
+ def select_index_entry(
171
+ key: str,
172
+ *,
173
+ components: set[str] | None,
174
+ archs: set[str],
175
+ arch_universe: set[str],
176
+ excludes: list[str],
177
+ ) -> bool:
178
+ """Decide whether a Release-listed index belongs in the sync set.
179
+
180
+ An entry is dropped when an exclude glob matches it, when it lives under an
181
+ unselected component, when it is a source index and `source` is not selected,
182
+ when nothing parses the index it names, or when its name carries an architecture
183
+ token the repository knows but has not selected. The component segment is never
184
+ read as an architecture or installer token; only the path below it is. An
185
+ architecture token is matched only against `arch_universe`, so name parts that
186
+ merely look like one (`icons-64x64`) are left alone; where several known
187
+ architectures end at one token the longest one owns it. A key with no `/`
188
+ belongs to no component, as a `Contents-<arch>` file at the dists root does, and
189
+ passes the component rule.
190
+
191
+ Args:
192
+ key: Path as the Release lists it, relative to the layout prefix.
193
+ components: Selected components, or `None` for a flat repo where paths carry no component
194
+ segment.
195
+ archs: Selected architectures.
196
+ arch_universe: Every architecture this repository knows about.
197
+ excludes: fnmatch globs matched against `key`.
198
+
199
+ Returns:
200
+ True when the entry belongs in the sync set.
201
+ """
202
+ for pattern in excludes:
203
+ if fnmatch.fnmatchcase(key, pattern):
204
+ return False
205
+
206
+ component, below = _split_component(key, components)
207
+ # a component implies `components` is set; the second test narrows it for mypy
208
+ if component is not None and components is not None and component not in components:
209
+ return False
210
+
211
+ if _is_source_index(below) and SOURCE_ARCH not in archs:
212
+ logger.debug("%s is a source index and source is not selected. Skipped.", key)
213
+ return False
214
+
215
+ if _is_unparsed_index(below, arch_universe):
216
+ logger.debug("%s is an index nothing parses. Skipped.", key)
217
+ return False
218
+
219
+ unselected = _unselected_arch_token(below, archs, arch_universe)
220
+ if unselected is not None:
221
+ logger.debug("%s carries unselected architecture %s. Skipped.", key, unselected)
222
+ return False
223
+
224
+ return True
debkit/repo/package.py ADDED
@@ -0,0 +1,177 @@
1
+ """Class containing fields data from Debian package."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import posixpath
6
+ from typing import Any
7
+
8
+ from debian.deb822 import Deb822
9
+ from txstore import SUPPORT_HASH_LIST
10
+
11
+ MANDATORY_FIELDS = ["Package", "Filename", "Size"]
12
+
13
+ # fields used as storage keys or digests; a line break in one is never a folded value
14
+ SINGLE_LINE_FIELDS = [*MANDATORY_FIELDS, *SUPPORT_HASH_LIST]
15
+
16
+ FILENAME_FIELD_KEY = "Filename"
17
+
18
+
19
+ class PackageException(Exception):
20
+ """Exception raised for errors in the Package class."""
21
+
22
+ def __init__(self, message: str) -> None:
23
+ """Initialize with error message."""
24
+ super().__init__(f"Package: {message}")
25
+
26
+
27
+ class Package:
28
+ """Object containing fields data from Debian package.
29
+
30
+ Attributes:
31
+ fields: The package fields.
32
+ """
33
+
34
+ def __init__(self, fields: dict[str, Any] | None = None) -> None:
35
+ """Initialize Package with optional pre-populated fields.
36
+
37
+ Args:
38
+ fields: Initial field values. Defaults to None.
39
+ """
40
+ self.fields: dict[str, Any] = fields if fields else {}
41
+
42
+ def __repr__(self) -> str:
43
+ """Return a string representation of the Package.
44
+
45
+ Returns:
46
+ A string representation of the Package.
47
+ """
48
+ return f"{self.fields.get(FILENAME_FIELD_KEY, '<empty package>')}"
49
+
50
+ def parse(self, headers: str, controls_only: bool = False) -> str | None:
51
+ """Parse fields of one package from headers format string.
52
+
53
+ Args:
54
+ headers: Lines in string to parse.
55
+ controls_only: If True, only parse controls fields. Defaults to False.
56
+
57
+ Multi-line values (`Description`, `Conffiles`) keep their continuation lines, so a
58
+ rewritten index carries them unchanged -> [VALIDATION.md](VALIDATION.md#package-stanzas).
59
+
60
+ Raises:
61
+ PackageException: If mandatory field is missing or a single-line field holds a
62
+ line break.
63
+
64
+ Returns:
65
+ The package name. None if data not parsed.
66
+ """
67
+ parsed = Deb822(headers)
68
+
69
+ if not parsed:
70
+ return None
71
+
72
+ self.fields.update(parsed)
73
+
74
+ if controls_only:
75
+ return None
76
+
77
+ # test mandatory fields
78
+ for test_field in MANDATORY_FIELDS:
79
+ if test_field not in self.fields:
80
+ raise PackageException(f"mandatory field '{test_field}' is missing: {self.fields}")
81
+
82
+ # a storage key is a POSIX path whatever the host OS; a relative segment does not
83
+ # work in some storages like S3
84
+ self.fields[FILENAME_FIELD_KEY] = posixpath.normpath(self.fields[FILENAME_FIELD_KEY])
85
+
86
+ for key in SINGLE_LINE_FIELDS:
87
+ value = str(self.fields.get(key, ""))
88
+ if "\n" in value:
89
+ raise PackageException(f"newline in field: {key}:{value!r}")
90
+
91
+ # return package name
92
+ filename: str | None = self.fields[FILENAME_FIELD_KEY]
93
+ return filename
94
+
95
+ def get_filename(self) -> str:
96
+ """Get the Filename field.
97
+
98
+ Raises:
99
+ PackageException: If the filename is missing or empty.
100
+
101
+ Returns:
102
+ The pool-relative filename.
103
+ """
104
+ filename = self.fields.get(FILENAME_FIELD_KEY)
105
+ if not filename:
106
+ raise PackageException("filename is empty")
107
+ return str(filename)
108
+
109
+ def set_filename(self, filename: str) -> None:
110
+ """Set the Filename field.
111
+
112
+ Args:
113
+ filename: The new filename.
114
+
115
+ Raises:
116
+ PackageException: If the filename is empty.
117
+ """
118
+ if not filename:
119
+ raise PackageException("filename is empty")
120
+ self.fields[FILENAME_FIELD_KEY] = filename
121
+
122
+ def get_arch(self) -> str | None:
123
+ """Get the architecture of the package.
124
+
125
+ Returns:
126
+ The architecture. None if the field is not present.
127
+ """
128
+ return self.fields.get("Architecture", None)
129
+
130
+ def serialize(self) -> str:
131
+ """Serialize fields of one package to headers format.
132
+
133
+ Values are written verbatim: multi-line values keep their continuation lines and
134
+ non-ASCII text stays UTF-8.
135
+
136
+ Returns:
137
+ The serialized stanza, ending with the blank line that separates stanzas.
138
+ """
139
+ return Deb822({field: str(data) for field, data in self.fields.items()}).dump() + "\n"
140
+
141
+ def dump(self) -> dict[str, Any]:
142
+ """Return dump of package fields in dict.
143
+
144
+ Returns:
145
+ The package fields.
146
+ """
147
+ return self.fields
148
+
149
+ def get_digests(self) -> dict[str, str]:
150
+ """Return all hexdigests from fields.
151
+
152
+ Returns:
153
+ The hexdigests.
154
+ """
155
+ return {alg: self.fields[alg] for alg in SUPPORT_HASH_LIST if alg in self.fields}
156
+
157
+ def set_digests(self, digests: dict[str, str]) -> None:
158
+ """Set all hexdigests to fields.
159
+
160
+ Args:
161
+ digests: The hexdigests.
162
+ """
163
+ self.fields.update(digests)
164
+
165
+ def __eq__(self, other: object) -> bool:
166
+ """Check if this Package is equal to another Package.
167
+
168
+ Args:
169
+ other: The object to compare with.
170
+
171
+ Returns:
172
+ True if the fields of the two Packages are equal, False otherwise; NotImplemented for an
173
+ object that is not a Package.
174
+ """
175
+ if not isinstance(other, Package):
176
+ return NotImplemented
177
+ return self.fields == other.fields