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/params.py ADDED
@@ -0,0 +1,305 @@
1
+ """Class containing Debian repository parameters."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import posixpath
7
+ import re
8
+
9
+ from txstore import is_unsafe_path, redact_url
10
+
11
+ logger = logging.getLogger(__name__)
12
+ logger.addHandler(logging.NullHandler())
13
+
14
+
15
+ class RepoParamsException(Exception):
16
+ """Exception raised for errors in the RepoParams class."""
17
+
18
+ def __init__(self, message: str) -> None:
19
+ """Initialize with error message."""
20
+ super().__init__(f"Repo parameters: {message}")
21
+
22
+
23
+ # Debian's pseudo-architecture for source packages: its indices live under
24
+ # `<component>/source/` and are named `Sources`, never `binary-source/Packages`.
25
+ SOURCE_ARCH = "source"
26
+
27
+ # Debian's architecture-independent pseudo-architecture: its packages serve every
28
+ # binary architecture, so it is always selected and never loaded as its own container.
29
+ ARCH_ANY = "all"
30
+
31
+ # The component key of a flat repository whose Release names no `Components`: a flat
32
+ # layout holds one index set, so it has exactly one component slot.
33
+ FLAT_COMPONENT = "/"
34
+
35
+ # A Debian architecture name. The token becomes the `binary-<arch>/` directory of a
36
+ # storage path, so anything else could steer that path
37
+ # -> [VALIDATION.md](VALIDATION.md#architectures).
38
+ _ARCH_TOKEN = re.compile(r"[a-z0-9][a-z0-9-]*")
39
+
40
+ # a real dist names a directory of a flat layout; the empty string names none
41
+ # -> [VALIDATION.md](VALIDATION.md#distribution-names)
42
+ _REAL_DIST = re.compile(r"[A-Za-z0-9]+")
43
+
44
+
45
+ def is_safe_name(name: str) -> bool:
46
+ """Report whether a relative storage subpath is safe to build a key from.
47
+
48
+ A dist, component, `Sources` `Directory`, or package `Filename`: it may hold `/`
49
+ (`updates/main`), but never a segment that steers the path out of its directory
50
+ -> [VALIDATION.md](VALIDATION.md#debian-source-strings),
51
+ [VALIDATION.md](VALIDATION.md#filename-safety).
52
+
53
+ Args:
54
+ name: A POSIX-normalized relative subpath.
55
+
56
+ Returns:
57
+ True when the name is non-empty, not `.`, and passes the unsafe-key rule.
58
+ """
59
+ return name not in ("", ".") and not is_unsafe_path(name)
60
+
61
+
62
+ def pool_path(comp: str | None, source: str, filename: str) -> str:
63
+ """Build the pool key an inserted `.deb` lands on.
64
+
65
+ The key follows Debian's source pool layout: the upload's file name nests under its
66
+ source package and that name's prefix, `lib` plus the next letter for a `lib*` name and
67
+ the first letter otherwise, below the component when one is given
68
+ -> [VALIDATION.md](VALIDATION.md#filename-safety).
69
+
70
+ Args:
71
+ comp: Component name, or None for a pool without one.
72
+ source: The source package name, a Debian Policy name.
73
+ filename: The upload path inside the incoming storage; only its file name is kept.
74
+
75
+ Returns:
76
+ The pool key, e.g. `pool/main/libf/libfoo/libfoo1_1.0_amd64.deb`.
77
+ """
78
+ head = f"pool/{comp}" if comp is not None else "pool"
79
+ prefix = source[:4] if source.startswith("lib") and len(source) > 3 else source[0]
80
+ return f"{head}/{prefix}/{source}/{posixpath.basename(filename)}"
81
+
82
+
83
+ def remove_prefix_from_path(path: str, prefix: str) -> str:
84
+ """Return `path` without the leading `prefix` directory, or unchanged when it lacks it.
85
+
86
+ Args:
87
+ path: Storage path.
88
+ prefix: Directory to strip, without a trailing slash.
89
+
90
+ Returns:
91
+ The path relative to `prefix`.
92
+ """
93
+ return path.removeprefix(f"{prefix}/")
94
+
95
+
96
+ def is_valid_arch(token: str) -> bool:
97
+ """Report whether a token is a well-formed Debian architecture name.
98
+
99
+ Args:
100
+ token: Architecture token from a flag, a Release, or an upload.
101
+
102
+ Returns:
103
+ True for lower-case letters, digits, and `-`, not starting with `-`.
104
+ """
105
+ return _ARCH_TOKEN.fullmatch(token) is not None
106
+
107
+
108
+ class RepoParams:
109
+ """Debian Repo input parameters.
110
+
111
+ Attributes:
112
+ dist: The distribution name.
113
+ components: The list of components.
114
+ archs: The list of architectures to limit the repo to.
115
+ indices_exclude: Globs of Release-listed index paths to skip.
116
+ verify_gpg: Whether to verify GPG signature of root Release file.
117
+ verify_digests: Whether to verify hex digests like SHA256, SHA512,...
118
+ is_flat: Whether the repository is flat. Default: False (repo with components).
119
+ """
120
+
121
+ def __init__(
122
+ self,
123
+ dist: str | None = None,
124
+ components: list[str] | None = None,
125
+ archs: list[str] | None = None,
126
+ indices_exclude: list[str] | None = None,
127
+ verify_gpg: bool = True,
128
+ verify_digests: bool = True,
129
+ ) -> None:
130
+ """Initialize RepoParams.
131
+
132
+ Args:
133
+ dist: The distribution name. Defaults to None.
134
+ components: The list of components. Defaults to None.
135
+ archs: The list of architectures. Defaults to None.
136
+ indices_exclude: Globs of Release-listed index paths to skip. Defaults to None (mirror
137
+ every listed index).
138
+ verify_gpg: Whether to verify GPG signature. Defaults to True.
139
+ verify_digests: Whether to verify hex digests. Defaults to True.
140
+ """
141
+ self.dist = dist
142
+ self.components = components
143
+ self.archs = archs
144
+ self.indices_exclude = indices_exclude
145
+ self.verify_gpg = verify_gpg
146
+ self.verify_digests = verify_digests
147
+ self.is_flat = False
148
+
149
+ def from_deb_source(self, deb_source: str | None) -> str:
150
+ """Extract debian repo attributes from a deb source string.
151
+
152
+ Args:
153
+ deb_source: The deb source string to extract attributes from; None is refused.
154
+
155
+ Returns:
156
+ The source URL, which opens the storage.
157
+
158
+ Raises:
159
+ RepoParamsException: If the deb source string is invalid.
160
+ RepoParamsException: If a componented source names an unsafe dist or component.
161
+ """
162
+ if not isinstance(deb_source, str):
163
+ raise RepoParamsException("no debian source provided")
164
+
165
+ # fields are separated by any whitespace run, leading and trailing runs dropped
166
+ parts: list[str] = deb_source.split()
167
+ if len(parts) < 2:
168
+ # the URL may carry credentials -> [CONFIG.md](CONFIG.md#secrets)
169
+ raise RepoParamsException(
170
+ f"there is no dist/components fields in source {redact_url(' '.join(parts))}"
171
+ )
172
+
173
+ url, self.dist, *components = parts
174
+ # a flat dist names a directory only when it is a real dist, which is alphanumeric
175
+ for name in (self.dist, *components) if components else ():
176
+ if not is_safe_name(name):
177
+ raise RepoParamsException(f"unsafe dist or component name: {name!r}")
178
+ if components:
179
+ self.components = components
180
+ else:
181
+ # flat repo without components
182
+ self.components = None
183
+ self.is_flat = True
184
+
185
+ logger.debug(
186
+ "Parse deb source: url=%s, dist=%s, components=%s",
187
+ redact_url(url),
188
+ self.dist,
189
+ self.components,
190
+ )
191
+ return url
192
+
193
+ @staticmethod
194
+ def arch_dir(arch: str) -> str:
195
+ """Name the per-architecture directory of a componented layout.
196
+
197
+ Binary indices nest under `binary-<arch>/`, source indices under `source/`
198
+ -> [VALIDATION.md](VALIDATION.md#repository-index-paths).
199
+
200
+ Args:
201
+ arch: Architecture name, or `SOURCE_ARCH`.
202
+
203
+ Returns:
204
+ Directory segment, without a trailing slash.
205
+ """
206
+ return SOURCE_ARCH if arch == SOURCE_ARCH else f"binary-{arch}"
207
+
208
+ @staticmethod
209
+ def index_name(arch: str) -> str:
210
+ """Name the package index of an architecture.
211
+
212
+ Args:
213
+ arch: Architecture name, or `SOURCE_ARCH`.
214
+
215
+ Returns:
216
+ `Sources` for the source architecture, `Packages` otherwise.
217
+ """
218
+ return "Sources" if arch == SOURCE_ARCH else "Packages"
219
+
220
+ def indices_path(self, inner: str, comp: str | None = None) -> str:
221
+ """Build the full storage path of an indices file.
222
+
223
+ The Debian repo layout splits into:
224
+ - non-flat: ``<indices_prefix>/<comp>/<inner>``
225
+ where ``indices_prefix == dists/<dist>``.
226
+ ``inner`` is e.g. ``binary-amd64/Packages.xz`` or ``Contents-amd64.xz``.
227
+ - flat-real-dist: ``<dist>/<inner>``
228
+ - flat-rootless: ``<inner>``
229
+
230
+ `release_key()` maps the result back to what a Release file references,
231
+ relative to the layout prefix, for ``digests`` lookups.
232
+
233
+ Args:
234
+ inner: Path under ``<comp>/`` (or bare filename for flat repos).
235
+ comp: Component name; ``None`` is treated as flat-like.
236
+
237
+ Returns:
238
+ The full storage path.
239
+ """
240
+ if self.is_flat:
241
+ return f"{self._flat_dir}/{inner}" if self._flat_dir else inner
242
+
243
+ path_short = f"{comp}/{inner}" if comp else inner
244
+ return f"{self.indices_prefix}/{path_short}" if self.indices_prefix else path_short
245
+
246
+ def release_key(self, path: str) -> str:
247
+ """Map a full index path back to the key the root Release lists it under.
248
+
249
+ The inverse of `indices_path()`: it strips exactly the layout prefix that
250
+ method prepends, so `release_key(indices_path(inner, comp))` is `inner`, under
251
+ `comp/` in a componented layout, for every layout. A path that does not carry
252
+ the prefix is returned unchanged, so an already-relative key round-trips.
253
+
254
+ Args:
255
+ path: Full storage path of an index file.
256
+
257
+ Returns:
258
+ Path relative to the layout prefix, as the Release lists it.
259
+ """
260
+ if self.is_flat:
261
+ return remove_prefix_from_path(path, self._flat_dir) if self._flat_dir else path
262
+
263
+ if self.indices_prefix:
264
+ return remove_prefix_from_path(path, self.indices_prefix)
265
+ return path
266
+
267
+ @property
268
+ def indices_prefix(self) -> str:
269
+ """The dist's index tree, derived so it never disagrees with `dist` and `is_flat`.
270
+
271
+ Returns:
272
+ `dists/<dist>` for a componented layout with a dist, else empty
273
+ -> [VALIDATION.md](VALIDATION.md#repository-index-paths).
274
+ """
275
+ return "" if self.is_flat or not self.dist else f"dists/{self.dist}"
276
+
277
+ def is_index_tree_key(self, path: str) -> bool:
278
+ """Report whether a payload key lands in the `dists/` tree of a componented layout.
279
+
280
+ Every dist sharing the root keeps its Release and indices there, so a remote
281
+ `Filename` or `Directory` naming that tree would overwrite another dist's metadata
282
+ -> [VALIDATION.md](VALIDATION.md#filename-safety). A flat layout has no such tree.
283
+
284
+ Args:
285
+ path: A POSIX-normalized payload key.
286
+
287
+ Returns:
288
+ True for `dists` or a key under `dists/` in a componented layout.
289
+ """
290
+ return not self.is_flat and (path == "dists" or path.startswith("dists/"))
291
+
292
+ @property
293
+ def _flat_dir(self) -> str | None:
294
+ """The directory a flat layout's indices sit in: the dist when it is a real one."""
295
+ return self.dist if self.is_real_dist() else None
296
+
297
+ def is_real_dist(self) -> bool:
298
+ """Check if the distribution name is a real dist, one naming a flat layout's directory.
299
+
300
+ Returns:
301
+ True when the dist is a non-empty run of ASCII letters and digits; False for None,
302
+ the empty string, or a name such as `/` or `./`
303
+ -> [VALIDATION.md](VALIDATION.md#distribution-names).
304
+ """
305
+ return self.dist is not None and _REAL_DIST.fullmatch(self.dist) is not None