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,325 @@
1
+ """Base class for Debian repo actions."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import logging
7
+ import os
8
+ from enum import Enum
9
+ from typing import TYPE_CHECKING, NamedTuple
10
+
11
+ from txstore import HistoryRetention, StorageException, make_storage, redact_url
12
+
13
+ from debkit.repo import RepoReadException
14
+ from debkit.repo.gnupg import GnuPG
15
+ from debkit.repo.params import RepoParams, RepoParamsException
16
+ from debkit.repo.repo_rw import RepoRW
17
+
18
+ if TYPE_CHECKING:
19
+ from argparse import Namespace
20
+
21
+ from txstore import Storage, StorageMetrics
22
+
23
+ from debkit._options import EnvArgumentParser
24
+
25
+ logger = logging.getLogger(__name__)
26
+ logger.addHandler(logging.NullHandler())
27
+
28
+
29
+ class OutputType(Enum):
30
+ """Output type enum for action output."""
31
+
32
+ brief = "brief"
33
+ json = "json"
34
+
35
+ def __str__(self) -> str:
36
+ """Return the string value of the enum member."""
37
+ return self.value
38
+
39
+
40
+ OUTPUT_DEFAULT = OutputType.brief
41
+
42
+
43
+ def storage_url(url: str) -> str:
44
+ """Return `url`, or ``fs://`` plus the absolute path when `url` has no scheme.
45
+
46
+ → [VALIDATION.md](VALIDATION.md#storage-urls).
47
+
48
+ Args:
49
+ url: Storage URL or filesystem path.
50
+
51
+ Returns:
52
+ A URL `make_storage` accepts.
53
+ """
54
+ if "://" in url:
55
+ return url
56
+ return f"fs://{os.path.abspath(url)}"
57
+
58
+
59
+ def open_storage(pars: Namespace, url: str, create_path: bool = False) -> Storage:
60
+ """Build the `Storage` for `url` from the resolved CLI options.
61
+
62
+ The only `make_storage` call → [STORAGE.md](STORAGE.md#construction).
63
+
64
+ Args:
65
+ pars: Parsed CLI namespace.
66
+ url: Storage URL or filesystem path.
67
+ create_path: Create the destination bucket or directory if missing.
68
+
69
+ Raises:
70
+ RepoParamsException: txstore rejects the URL → [VALIDATION.md](VALIDATION.md#storage-urls).
71
+
72
+ Returns:
73
+ A backend instance routed by the URL scheme.
74
+ """
75
+ try:
76
+ return make_storage(
77
+ storage_url(url),
78
+ create_path=create_path,
79
+ verify_ssl=verify_policy(pars).verify_ssl,
80
+ s3_access=pars.s3_access,
81
+ s3_secret=pars.s3_secret,
82
+ s3_default_acl=pars.s3_default_acl,
83
+ s3_bucket_acl=pars.s3_bucket_acl,
84
+ )
85
+ except ValueError as exc:
86
+ # the URL may carry credentials -> [CONFIG.md](CONFIG.md#secrets)
87
+ raise RepoParamsException(str(exc)) from exc
88
+
89
+
90
+ def history_retention(pars: Namespace) -> HistoryRetention:
91
+ """Build the retention policy from the resolved ``--history-*`` options.
92
+
93
+ Args:
94
+ pars: Parsed CLI namespace.
95
+
96
+ Returns:
97
+ Policy for `maybe_transaction` and `prune`.
98
+ """
99
+ return HistoryRetention.from_env(keep=pars.history_keep, max_age_days=pars.history_max_age)
100
+
101
+
102
+ class VerifyPolicy(NamedTuple):
103
+ """The checks the resolved ``--skip-verify*`` switches leave on.
104
+
105
+ → [CRYPTO.md](CRYPTO.md#verification-switches).
106
+ """
107
+
108
+ verify_ssl: bool
109
+ verify_gpg: bool
110
+ verify_digests: bool
111
+
112
+
113
+ def verify_policy(pars: Namespace) -> VerifyPolicy:
114
+ """Resolve ``--skip-verify``, ``--skip-verify-ssl``, and ``--skip-verify-gpg``.
115
+
116
+ Args:
117
+ pars: Parsed CLI namespace.
118
+
119
+ Returns:
120
+ Which of TLS, GPG, and digest verification stay on.
121
+ """
122
+ return VerifyPolicy(
123
+ verify_ssl=not (pars.skip_verify or pars.skip_verify_ssl),
124
+ verify_gpg=not (pars.skip_verify or pars.skip_verify_gpg),
125
+ verify_digests=not pars.skip_verify,
126
+ )
127
+
128
+
129
+ def attach_storage_repo(
130
+ pars: Namespace,
131
+ url: str,
132
+ create_path: bool = False,
133
+ *,
134
+ archs: list[str] | None = None,
135
+ indices_exclude: list[str] | None = None,
136
+ ) -> tuple[Storage, RepoParams]:
137
+ """Build a `Storage` and `RepoParams` pair from a deb-source URL.
138
+
139
+ Args:
140
+ pars: Parsed CLI namespace.
141
+ url: Deb-source string.
142
+ create_path: Create the destination bucket/directory if missing.
143
+ archs: The `--architectures` selection; None keeps the Release's.
144
+ indices_exclude: The `--indices-exclude` globs; None mirrors every listed index.
145
+
146
+ Raises:
147
+ RepoParamsException: If the deb source or its URL is invalid.
148
+ RepoReadException: If the storage cannot be constructed.
149
+
150
+ Returns:
151
+ Tuple of (storage, repo_params).
152
+ """
153
+ policy = verify_policy(pars)
154
+ repo_params = RepoParams(
155
+ archs=archs,
156
+ indices_exclude=indices_exclude,
157
+ verify_gpg=policy.verify_gpg,
158
+ verify_digests=policy.verify_digests,
159
+ )
160
+ source_url = repo_params.from_deb_source(url)
161
+
162
+ try:
163
+ storage = open_storage(pars, source_url, create_path=create_path)
164
+ except StorageException as exc:
165
+ raise RepoReadException(str(exc)) from exc
166
+ return storage, repo_params
167
+
168
+
169
+ def attach_storage_root(pars: Namespace, url: str, create_path: bool = False) -> Storage:
170
+ """Build a `Storage` from the URL field of a deb source, ignoring dist/components.
171
+
172
+ Root-scoped commands (`log`, `revert`) address the storage root only, so
173
+ they accept both ``<url>`` and ``<url> <dist> [<component> ...]``.
174
+
175
+ Args:
176
+ pars: Parsed CLI namespace.
177
+ url: Deb-source or plain storage URL.
178
+ create_path: Create the destination bucket/directory if missing.
179
+
180
+ Raises:
181
+ StorageException: If the URL is blank.
182
+
183
+ Returns:
184
+ A backend instance routed by the URL scheme.
185
+ """
186
+ if not url.strip():
187
+ raise StorageException("Empty storage URL.")
188
+ return open_storage(pars, url.split()[0], create_path=create_path)
189
+
190
+
191
+ def open_target_repo(
192
+ pars: Namespace,
193
+ *,
194
+ gpg: GnuPG | None,
195
+ create_path: bool = False,
196
+ archs: list[str] | None = None,
197
+ indices_exclude: list[str] | None = None,
198
+ ) -> RepoRW:
199
+ """Open the `--target-url` repository with its selection.
200
+
201
+ Args:
202
+ pars: Parsed CLI namespace.
203
+ gpg: Verifies and signs its Release; None reads it unverified and never signs it.
204
+ create_path: Create the target path or bucket if missing.
205
+ archs: The `--architectures` selection; None keeps the Release's.
206
+ indices_exclude: The `--indices-exclude` globs; None excludes nothing.
207
+
208
+ Raises:
209
+ RepoParamsException: If the deb source or its URL is invalid.
210
+ RepoReadException: If the storage cannot be constructed.
211
+
212
+ Returns:
213
+ The target repository, not yet loaded.
214
+ """
215
+ # `--target-url` is required, so every action has a target
216
+ logger.debug("Prepare target URL: %s", redact_url(pars.target_url))
217
+ storage, params = attach_storage_repo(
218
+ pars,
219
+ pars.target_url,
220
+ create_path=create_path,
221
+ archs=archs,
222
+ indices_exclude=indices_exclude,
223
+ )
224
+ return RepoRW(storage, params, gpg=gpg)
225
+
226
+
227
+ class ActionException(Exception):
228
+ """Exception raised for errors in the Action class."""
229
+
230
+ def __init__(self, message: str) -> None:
231
+ """Initialize ActionException.
232
+
233
+ Args:
234
+ message: Human-readable description of the failure.
235
+ """
236
+ super().__init__(f"Action: {message}")
237
+
238
+
239
+ class RepoJSONEncoder(json.JSONEncoder):
240
+ """JSON encoder that serialises objects exposing a ``dump()`` method."""
241
+
242
+ def default(self, obj: object) -> object:
243
+ """Return a serialisable representation of *obj*."""
244
+ if hasattr(obj, "dump"):
245
+ return obj.dump()
246
+ return super().default(obj)
247
+
248
+
249
+ def dump_json(obj: object) -> str:
250
+ """Serialize *obj* via RepoJSONEncoder, two-space indented, so dump()-bearing objects work."""
251
+ return json.dumps(obj, cls=RepoJSONEncoder, indent=2)
252
+
253
+
254
+ def add_output_cli_args(parser: EnvArgumentParser) -> None:
255
+ """Register ``--output`` on a subcommand parser.
256
+
257
+ Args:
258
+ parser: The subcommand parser.
259
+ """
260
+ parser.add_env_argument(
261
+ "-o",
262
+ "--output",
263
+ env="DEBKIT_OUTPUT",
264
+ dest="output",
265
+ help="output format",
266
+ choices=list(OutputType),
267
+ default=OUTPUT_DEFAULT,
268
+ type=OutputType,
269
+ )
270
+
271
+
272
+ class Action:
273
+ """Base class for repo actions.
274
+
275
+ Attributes:
276
+ output: Output format.
277
+ gpg: Verifies and signs Release files; None when GPG verification is off.
278
+ target_repo: Target repository.
279
+ history_retention: Policy the write paths hand to `maybe_transaction`; a `max_age_days` of
280
+ `0` records without pruning.
281
+ """
282
+
283
+ target_repo: RepoRW
284
+
285
+ def __init__(self, pars: Namespace):
286
+ """Read the output, verification, and history settings every action shares.
287
+
288
+ No storage is opened here: each subcommand opens its repositories after this
289
+ returns, through `open_target_repo` or `attach_storage_repo`, so it can refuse its
290
+ own flags first and set every attribute before a repository exists.
291
+
292
+ Args:
293
+ pars: Parsed command line arguments.
294
+ """
295
+ # every action subcommand registers `--output` -> [CONFIG.md](CONFIG.md#global-flags)
296
+ self.output: OutputType = pars.output
297
+ self.gpg: GnuPG | None = None
298
+ self.history_retention: HistoryRetention = history_retention(pars)
299
+
300
+ policy = verify_policy(pars)
301
+ # one warning per run, as for `--allow-release-rollback`
302
+ # -> [CRYPTO.md](CRYPTO.md#verification-switches)
303
+ if not policy.verify_digests:
304
+ logger.warning(
305
+ "GPG and digest verification skipped: --skip-verify is set; "
306
+ "Release files are neither verified nor signed"
307
+ )
308
+ elif not policy.verify_gpg:
309
+ logger.warning(
310
+ "GPG verification skipped: --skip-verify-gpg is set; "
311
+ "Release files are neither verified nor signed"
312
+ )
313
+ else:
314
+ self.gpg = GnuPG(
315
+ pars.gnupg_home, pars.gnupg_keyring, pars.gnupg_passphrase, pars.gnupg_sign_key
316
+ )
317
+
318
+ @property
319
+ def _target_metrics(self) -> StorageMetrics:
320
+ """The read and write counters of the target storage, which the reports print.
321
+
322
+ Returns:
323
+ The target storage's metrics.
324
+ """
325
+ return self.target_repo.storage.metrics
@@ -0,0 +1,191 @@
1
+ """Transaction history actions (log, revert, prune)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterator
6
+ from contextlib import contextmanager
7
+ from datetime import datetime
8
+ from typing import TYPE_CHECKING
9
+
10
+ from txstore import (
11
+ HistoryRetention,
12
+ StorageException,
13
+ TransactionHistory,
14
+ TransactionModel,
15
+ is_transactional,
16
+ )
17
+
18
+ from debkit._escape import escape_control
19
+ from debkit.action import (
20
+ OUTPUT_DEFAULT,
21
+ ActionException,
22
+ OutputType,
23
+ attach_storage_root,
24
+ dump_json,
25
+ history_retention,
26
+ )
27
+
28
+ if TYPE_CHECKING:
29
+ from argparse import ArgumentParser, Namespace
30
+
31
+
32
+ def _record(model: TransactionModel) -> dict[str, object]:
33
+ """Return the history-file form of `model`: ``{"id", "timestamp"}``."""
34
+ return {"id": model.id, "timestamp": model.timestamp.to_json()}
35
+
36
+
37
+ class ActionHistory:
38
+ """Actions for transaction history: log, revert, and prune.
39
+
40
+ Attributes:
41
+ output: Output format.
42
+ dry_run: If True, revert and prune print what would happen without applying.
43
+ orphans: If True, prune also sweeps footmark objects that belong to no recorded transaction.
44
+ history_retention: Policy prune applies.
45
+ """
46
+
47
+ def __init__(self, pars: Namespace) -> None:
48
+ """Initialize ActionHistory.
49
+
50
+ Args:
51
+ pars: Parsed CLI namespace.
52
+ """
53
+ self.output: OutputType = getattr(pars, "output", OUTPUT_DEFAULT)
54
+ self.dry_run: bool = getattr(pars, "dry_run", False)
55
+ self.orphans: bool = getattr(pars, "orphans", False)
56
+ self.history_retention: HistoryRetention = history_retention(pars)
57
+ self._storage = attach_storage_root(pars, pars.target_url)
58
+
59
+ @contextmanager
60
+ def _translate_storage_errors(self) -> Iterator[None]:
61
+ """Map ``StorageException`` to ``ActionException`` for this command."""
62
+ try:
63
+ yield
64
+ except StorageException as exc:
65
+ raise ActionException(str(exc)) from exc
66
+
67
+ def log(self) -> None:
68
+ """Print transaction history.
69
+
70
+ Raises:
71
+ ActionException: If the storage backend does not support transactions,
72
+ or the history file contains a malformed record.
73
+ """
74
+ self._assert_transactional()
75
+ history = TransactionHistory(self._storage)
76
+ with self._translate_storage_errors():
77
+ records = history.load()
78
+
79
+ if self.output == OutputType.json:
80
+ print(dump_json([_record(rec) for rec in records]))
81
+ else:
82
+ if not records:
83
+ print("No transactions recorded.")
84
+ return
85
+ for rec in records:
86
+ print(f" {rec.id:>4} {rec.timestamp.to_json()}")
87
+
88
+ def revert(self) -> None:
89
+ """Revert the latest committed transaction.
90
+
91
+ Raises:
92
+ ActionException: If history is empty or backend is non-transactional.
93
+ """
94
+ self._assert_transactional()
95
+ history = TransactionHistory(self._storage)
96
+
97
+ if self.dry_run:
98
+ with self._translate_storage_errors():
99
+ records = history.load()
100
+ if not records:
101
+ raise ActionException("No transactions to revert.")
102
+ last = records[-1]
103
+ print(f"Would revert transaction {last.id} ({last.timestamp.to_json()})")
104
+ return
105
+
106
+ with self._translate_storage_errors():
107
+ removed = history.revert_last()
108
+ if removed is None:
109
+ raise ActionException("No transactions to revert.")
110
+ print(f"Reverted transaction {removed.id}")
111
+
112
+ def prune(self, now: datetime | None = None) -> None:
113
+ """Prune expired transactions, and orphaned footmarks when asked.
114
+
115
+ Retention comes from the global flags → [CONFIG.md](CONFIG.md#prune);
116
+ the rule it applies → [STORAGE.md](STORAGE.md#history-commands).
117
+
118
+ Args:
119
+ now: Reference time for record age; None means the current time.
120
+
121
+ Raises:
122
+ ActionException: If the storage backend does not support
123
+ transactions, or the history cannot be read or rewritten.
124
+ """
125
+ self._assert_transactional()
126
+ history = TransactionHistory(self._storage)
127
+
128
+ with self._translate_storage_errors():
129
+ result = history.prune(
130
+ self.history_retention,
131
+ now=now,
132
+ orphans=self.orphans,
133
+ dry_run=self.dry_run,
134
+ )
135
+
136
+ if self.output == OutputType.json:
137
+ print(
138
+ dump_json(
139
+ {
140
+ "transactions": [_record(rec) for rec in result.records],
141
+ "footmarks": result.footmark_paths,
142
+ "orphans": result.orphans,
143
+ }
144
+ )
145
+ )
146
+ return
147
+
148
+ verb = "Would remove" if self.dry_run else "Removed"
149
+ for rec in result.records:
150
+ print(f" {verb} transaction {rec.id} {rec.timestamp.to_json()}")
151
+ for path in result.footmark_paths:
152
+ print(f" {verb} footmark {escape_control(path)}")
153
+ for path in result.orphans:
154
+ print(f" {verb} orphaned footmark {escape_control(path)}")
155
+ if not result.records and not result.orphans:
156
+ print("Nothing to prune.")
157
+
158
+ def _assert_transactional(self) -> None:
159
+ """Guard: raise if backend lacks transaction support."""
160
+ if not is_transactional(self._storage):
161
+ raise ActionException("Storage backend does not support transactions.")
162
+
163
+ @staticmethod
164
+ def add_dry_run_cli_arg(parser: ArgumentParser) -> None:
165
+ """Register `--dry-run`, shared by the revert and prune subcommands.
166
+
167
+ Args:
168
+ parser: The argument parser for a history subcommand.
169
+ """
170
+ parser.add_argument(
171
+ "--dry-run",
172
+ action="store_true",
173
+ dest="dry_run",
174
+ default=False,
175
+ help="show what would be changed without applying",
176
+ )
177
+
178
+ @staticmethod
179
+ def add_prune_cli_args(parser: ArgumentParser) -> None:
180
+ """Add prune-specific CLI arguments.
181
+
182
+ Args:
183
+ parser: The argument parser for the prune subcommand.
184
+ """
185
+ parser.add_argument(
186
+ "--orphans",
187
+ action="store_true",
188
+ dest="orphans",
189
+ default=False,
190
+ help="also remove footmark objects belonging to no recorded transaction",
191
+ )