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/argparser.py ADDED
@@ -0,0 +1,246 @@
1
+ """Command-line parser: flags, subcommands, and their ``DEBKIT_*`` fallbacks.
2
+
3
+ Every option is listed in [CONFIG.md](CONFIG.md); resolution order →
4
+ [CONFIG.md](CONFIG.md#resolution).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from argparse import BooleanOptionalAction, Namespace, RawDescriptionHelpFormatter
10
+
11
+ from txstore import HISTORY_KEEP_DEFAULT, HISTORY_MAX_AGE_DAYS_DEFAULT, get_supported_schemes
12
+
13
+ from debkit import __version__
14
+ from debkit._logging import LOG_LEVELS, LogFormat
15
+ from debkit._options import EnvArgumentParser
16
+ from debkit.action import add_output_cli_args
17
+ from debkit.action.action_history import ActionHistory
18
+ from debkit.action.action_pkg import ActionPkg
19
+ from debkit.action.action_sync import ActionCheck, ActionSync
20
+ from debkit.argtypes import (
21
+ bucket_acl_type,
22
+ history_max_age_type,
23
+ object_acl_type,
24
+ positive_int_type,
25
+ )
26
+
27
+ LOG_LEVEL_DEFAULT = "INFO"
28
+ # the home gpgv reads, never one relative to where debkit runs → [CRYPTO.md](CRYPTO.md#gpg)
29
+ GNUPG_HOME_DEFAULT = "~/.gnupg"
30
+ GNUPG_KEYRING_DEFAULT = "trustedkeys.gpg"
31
+ GNUPG_PASSPHRASE_DEFAULT = ""
32
+ # Repositories serve their indices to apt clients anonymously
33
+ # → [STORAGE.md](STORAGE.md#construction).
34
+ S3_DEFAULT_ACL_DEFAULT = "public-read"
35
+
36
+
37
+ def add_common_args(parser: EnvArgumentParser) -> None:
38
+ """Register the global options on the root parser.
39
+
40
+ Args:
41
+ parser: Root parser.
42
+ """
43
+ parser.add_argument("-V", "--version", action="version", version=__version__)
44
+
45
+ parser.add_env_argument(
46
+ "--target-url",
47
+ env="DEBKIT_TARGET_URL",
48
+ dest="target_url",
49
+ help="target repository 'URL DIST [COMPONENT ...]'; URL is a filesystem path or uses "
50
+ f"one of the schemes {', '.join(get_supported_schemes())} "
51
+ "(example: 's3://endpoint/bucket/debian bookworm main')",
52
+ required=True,
53
+ )
54
+ parser.add_env_argument(
55
+ "-l",
56
+ "--log-level",
57
+ env="DEBKIT_LOG_LEVEL",
58
+ dest="log_level",
59
+ help="logging level",
60
+ type=str.upper,
61
+ choices=LOG_LEVELS,
62
+ default=LOG_LEVEL_DEFAULT,
63
+ )
64
+ parser.add_env_argument(
65
+ "--log-format",
66
+ env="DEBKIT_LOG_FORMAT",
67
+ dest="log_format",
68
+ help="log line format",
69
+ type=LogFormat,
70
+ choices=list(LogFormat),
71
+ default=LogFormat.plain,
72
+ )
73
+ parser.add_env_argument(
74
+ "-n",
75
+ "--skip-verify",
76
+ env="DEBKIT_SKIP_VERIFY",
77
+ dest="skip_verify",
78
+ help="skip TLS, GPG, and digest verification - INSECURE",
79
+ action=BooleanOptionalAction,
80
+ default=False,
81
+ )
82
+ parser.add_env_argument(
83
+ "--skip-verify-ssl",
84
+ env="DEBKIT_SKIP_VERIFY_SSL",
85
+ dest="skip_verify_ssl",
86
+ help="skip TLS certificate verification - INSECURE",
87
+ action=BooleanOptionalAction,
88
+ default=False,
89
+ )
90
+ parser.add_env_argument(
91
+ "--skip-verify-gpg",
92
+ env="DEBKIT_SKIP_VERIFY_GPG",
93
+ dest="skip_verify_gpg",
94
+ help="skip GPG signature verification and signing - INSECURE",
95
+ action=BooleanOptionalAction,
96
+ default=False,
97
+ )
98
+ parser.add_env_argument(
99
+ "--gnupg-home",
100
+ env="DEBKIT_GNUPG_HOME",
101
+ dest="gnupg_home",
102
+ help="GnuPG home directory",
103
+ default=GNUPG_HOME_DEFAULT,
104
+ )
105
+ parser.add_env_argument(
106
+ "--gnupg-keyring",
107
+ env="DEBKIT_GNUPG_KEYRING",
108
+ dest="gnupg_keyring",
109
+ help="keyring whose keys are trusted for Release signatures",
110
+ default=GNUPG_KEYRING_DEFAULT,
111
+ )
112
+ parser.add_env_argument(
113
+ "--gnupg-sign-key",
114
+ env="DEBKIT_GNUPG_SIGN_KEY",
115
+ dest="gnupg_sign_key",
116
+ help="key that signs Release files: fingerprint, key ID, or user ID",
117
+ default=None,
118
+ )
119
+ parser.add_env_variable(
120
+ "DEBKIT_GNUPG_PASSPHRASE",
121
+ dest="gnupg_passphrase",
122
+ help="passphrase of the signing key",
123
+ default=GNUPG_PASSPHRASE_DEFAULT,
124
+ )
125
+ parser.add_env_argument(
126
+ "--history-keep",
127
+ env="DEBKIT_HISTORY_KEEP",
128
+ dest="history_keep",
129
+ help="newest transactions never pruned from the history",
130
+ type=positive_int_type,
131
+ default=HISTORY_KEEP_DEFAULT,
132
+ )
133
+ parser.add_env_argument(
134
+ "--history-max-age",
135
+ env="DEBKIT_HISTORY_MAX_AGE",
136
+ dest="history_max_age",
137
+ help="days after which a transaction outside --history-keep is pruned; 0 disables",
138
+ type=history_max_age_type,
139
+ default=HISTORY_MAX_AGE_DAYS_DEFAULT,
140
+ )
141
+
142
+
143
+ def add_s3_args(parser: EnvArgumentParser) -> None:
144
+ """Register the S3 options on the root parser.
145
+
146
+ Args:
147
+ parser: Root parser.
148
+ """
149
+ parser.add_env_argument(
150
+ "-u",
151
+ "--s3-access",
152
+ env="DEBKIT_S3_ACCESS",
153
+ dest="s3_access",
154
+ help="S3 access key ID; falls back to TXSTORE_S3_ACCESS",
155
+ )
156
+ parser.add_env_variable(
157
+ "DEBKIT_S3_SECRET",
158
+ dest="s3_secret",
159
+ help="S3 secret key; falls back to TXSTORE_S3_SECRET",
160
+ )
161
+ parser.add_env_argument(
162
+ "--s3-default-acl",
163
+ env="DEBKIT_S3_DEFAULT_ACL",
164
+ dest="s3_default_acl",
165
+ help="canned ACL for written objects, or 'none' to send no ACL",
166
+ type=object_acl_type,
167
+ default=S3_DEFAULT_ACL_DEFAULT,
168
+ )
169
+ parser.add_env_argument(
170
+ "--s3-bucket-acl",
171
+ env="DEBKIT_S3_BUCKET_ACL",
172
+ dest="s3_bucket_acl",
173
+ help="canned ACL for a bucket created by the run; unset sends none",
174
+ type=bucket_acl_type,
175
+ )
176
+
177
+
178
+ def build_parser() -> EnvArgumentParser:
179
+ """Build the root parser with every subcommand.
180
+
181
+ Returns:
182
+ Root parser.
183
+ """
184
+ root_parser = EnvArgumentParser(
185
+ prog="debkit",
186
+ description=f"debkit {__version__}: build, mirror, and verify Debian repositories",
187
+ formatter_class=RawDescriptionHelpFormatter,
188
+ )
189
+ add_common_args(root_parser)
190
+ add_s3_args(root_parser)
191
+
192
+ subparsers = root_parser.add_subparsers(
193
+ help="command help", dest="command", required=True, parser_class=EnvArgumentParser
194
+ )
195
+
196
+ dump_parser = subparsers.add_parser("dump", help="dump repository indices structure and data")
197
+ add_output_cli_args(dump_parser)
198
+
199
+ list_parser = subparsers.add_parser("list", help="list all packages from repository")
200
+ add_output_cli_args(list_parser)
201
+
202
+ stats_parser = subparsers.add_parser("stats", help="show repository data statistics")
203
+ add_output_cli_args(stats_parser)
204
+
205
+ insert_parser = subparsers.add_parser("insert", help="insert packages to repository")
206
+ ActionPkg.add_insert_cli_args(insert_parser)
207
+ add_output_cli_args(insert_parser)
208
+
209
+ remove_parser = subparsers.add_parser("remove", help="remove packages from repository")
210
+ ActionPkg.add_remove_cli_args(remove_parser)
211
+ add_output_cli_args(remove_parser)
212
+
213
+ sync_parser = subparsers.add_parser("sync", help="sync data from other repository")
214
+ ActionSync.add_sync_cli_args(sync_parser)
215
+ ActionSync.add_selection_cli_args(sync_parser)
216
+ add_output_cli_args(sync_parser)
217
+
218
+ check_parser = subparsers.add_parser("check", help="check data consistency in repository")
219
+ ActionCheck.add_check_cli_args(check_parser)
220
+ ActionSync.add_selection_cli_args(check_parser)
221
+ add_output_cli_args(check_parser)
222
+
223
+ log_parser = subparsers.add_parser("log", help="show transaction history")
224
+ add_output_cli_args(log_parser)
225
+
226
+ revert_parser = subparsers.add_parser("revert", help="revert latest committed transaction")
227
+ ActionHistory.add_dry_run_cli_arg(revert_parser)
228
+
229
+ prune_parser = subparsers.add_parser("prune", help="prune old transactions from the history")
230
+ ActionHistory.add_dry_run_cli_arg(prune_parser)
231
+ ActionHistory.add_prune_cli_args(prune_parser)
232
+ add_output_cli_args(prune_parser)
233
+
234
+ return root_parser
235
+
236
+
237
+ def parse_cli(argv: list[str] | None = None) -> Namespace:
238
+ """Parse `argv` (or ``sys.argv``) and resolve the ``DEBKIT_*`` fallbacks.
239
+
240
+ Args:
241
+ argv: Arguments without the program name; None reads ``sys.argv``.
242
+
243
+ Returns:
244
+ Parsed and resolved options.
245
+ """
246
+ return build_parser().parse_args(argv)
debkit/argtypes.py ADDED
@@ -0,0 +1,140 @@
1
+ """CLI type converters for argparse flags and their ``DEBKIT_*`` fallbacks.
2
+
3
+ Each converter raises `ArgumentTypeError` (or `ValueError`), which argparse reports as a usage
4
+ error and the environment fallback reports naming the variable →
5
+ [VALIDATION.md](VALIDATION.md#principles). Imports only the standard library and the `txstore`
6
+ façade → [STRUCTURE.md](STRUCTURE.md#dependencies).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import re
13
+ from argparse import ArgumentTypeError
14
+ from typing import Literal
15
+
16
+ from txstore import (
17
+ NO_ACL,
18
+ BucketCannedACL,
19
+ ObjectCannedACL,
20
+ is_unsafe_path,
21
+ parse_bucket_acl,
22
+ parse_object_acl,
23
+ )
24
+
25
+ # Upper bound of `--history-max-age`; `txstore.HistoryRetention` rejects larger values
26
+ # → [VALIDATION.md](VALIDATION.md#history-retention).
27
+ HISTORY_MAX_AGE_LIMIT = 36500
28
+
29
+ # one optional sign, then ASCII digits → [VALIDATION.md](VALIDATION.md#history-retention)
30
+ _DECIMAL = re.compile(r"[+-]?[0-9]+")
31
+
32
+ # Longest accepted `--pkg-pattern` regex → [VALIDATION.md](VALIDATION.md#package-pattern-matching).
33
+ PKG_PATTERN_MAX_LENGTH = 500
34
+
35
+
36
+ def _int_type(value: str, minimum: int, maximum: int | None = None) -> int:
37
+ """Parse `value` as a decimal integer within ``minimum..maximum``.
38
+
39
+ Args:
40
+ value: Raw flag or environment value.
41
+ minimum: Smallest accepted integer.
42
+ maximum: Largest accepted integer; None for no bound.
43
+
44
+ Raises:
45
+ ArgumentTypeError: If `value` is not an integer in range.
46
+
47
+ Returns:
48
+ The parsed value.
49
+ """
50
+ stripped = str(value).strip()
51
+ if not _DECIMAL.fullmatch(stripped):
52
+ raise ArgumentTypeError(f"invalid value: not an integer: {value!r}")
53
+ parsed = int(stripped, 10)
54
+ if parsed < minimum:
55
+ raise ArgumentTypeError(f"invalid value: must be {minimum} or greater, got {parsed}")
56
+ if maximum is not None and parsed > maximum:
57
+ raise ArgumentTypeError(f"invalid value: must be {maximum} or less, got {parsed}")
58
+ return parsed
59
+
60
+
61
+ def positive_int_type(value: str) -> int:
62
+ """Parse a flag value that must be 1 or greater."""
63
+ return _int_type(value, 1)
64
+
65
+
66
+ def history_max_age_type(value: str) -> int:
67
+ """Parse a history age in days: ``0..HISTORY_MAX_AGE_LIMIT``, ``0`` disables pruning."""
68
+ return _int_type(value, 0, HISTORY_MAX_AGE_LIMIT)
69
+
70
+
71
+ def component_type(value: str) -> str:
72
+ """Parse a component name: non-empty, not ``.``, and no path-steering segment.
73
+
74
+ The same rule as `is_safe_name()` in `repo/params.py`, which `argtypes` may not import
75
+ → [VALIDATION.md](VALIDATION.md#debian-source-strings).
76
+ """
77
+ if value in ("", ".") or is_unsafe_path(value):
78
+ raise ArgumentTypeError(f"unsafe component name: {value!r}")
79
+ return value
80
+
81
+
82
+ def object_acl_type(value: str) -> ObjectCannedACL | Literal["none"]:
83
+ """Parse an S3 object canned ACL, or ``none`` to send no ACL.
84
+
85
+ Raises:
86
+ ArgumentTypeError: If `value` is neither ``none`` nor an object canned ACL.
87
+ """
88
+ if value == NO_ACL:
89
+ return NO_ACL
90
+ try:
91
+ return parse_object_acl(value)
92
+ except ValueError as exc:
93
+ raise ArgumentTypeError(str(exc)) from None
94
+
95
+
96
+ def bucket_acl_type(value: str) -> BucketCannedACL:
97
+ """Parse an S3 bucket canned ACL.
98
+
99
+ Raises:
100
+ ArgumentTypeError: If `value` is not a bucket canned ACL.
101
+ """
102
+ try:
103
+ return parse_bucket_acl(value)
104
+ except ValueError as exc:
105
+ raise ArgumentTypeError(str(exc)) from None
106
+
107
+
108
+ def pkg_pattern_type(value: str) -> dict[str, re.Pattern[str]]:
109
+ """Parse a JSON object mapping package fields to regex patterns, and compile each pattern.
110
+
111
+ Rules → [VALIDATION.md](VALIDATION.md#package-pattern-matching).
112
+
113
+ Raises:
114
+ ArgumentTypeError: If `value` is not a non-empty JSON object of strings, or a pattern is
115
+ too long or does not compile.
116
+
117
+ Returns:
118
+ Compiled pattern per field.
119
+ """
120
+ try:
121
+ fields = json.loads(value)
122
+ except json.JSONDecodeError as exc:
123
+ raise ArgumentTypeError(f"invalid JSON: {exc}") from None
124
+ if not isinstance(fields, dict) or not fields:
125
+ raise ArgumentTypeError("must be a non-empty JSON object of field names to regex patterns")
126
+ compiled: dict[str, re.Pattern[str]] = {}
127
+ for name, pattern in fields.items():
128
+ if not isinstance(pattern, str):
129
+ raise ArgumentTypeError(
130
+ f"{name}: pattern must be a string, not {type(pattern).__name__}"
131
+ )
132
+ if len(pattern) > PKG_PATTERN_MAX_LENGTH:
133
+ raise ArgumentTypeError(
134
+ f"{name}: pattern too long ({len(pattern)} chars, max {PKG_PATTERN_MAX_LENGTH})"
135
+ )
136
+ try:
137
+ compiled[name] = re.compile(pattern)
138
+ except re.error as exc:
139
+ raise ArgumentTypeError(f"{name}: invalid regex pattern: {exc}") from None
140
+ return compiled
debkit/cli.py ADDED
@@ -0,0 +1,130 @@
1
+ r"""Command-line entry point: parse options, configure logging, dispatch, map errors to exit 1.
2
+
3
+ _ _ _ _ _
4
+ __| | ___| |__ | | _(_) |_
5
+ / _` |/ _ \ '_ \| |/ / | __|
6
+ | (_| | __/ |_) | <| | |_
7
+ \__,_|\___|_.__/|_|\_\_|\__|
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import logging
13
+ import sys
14
+ from typing import NoReturn
15
+
16
+ import urllib3
17
+ from txstore import StorageException
18
+
19
+ from debkit import __version__
20
+ from debkit._logging import configure_logging
21
+ from debkit.action import ActionException, verify_policy
22
+ from debkit.action.action_history import ActionHistory
23
+ from debkit.action.action_pkg import ActionPkg
24
+ from debkit.action.action_sync import ActionCheck, ActionSync
25
+ from debkit.argparser import parse_cli
26
+ from debkit.repo import RepoReadException
27
+ from debkit.repo.changes import ChangesException
28
+ from debkit.repo.component import ComponentException
29
+ from debkit.repo.debfile import DebFileException
30
+ from debkit.repo.gnupg import GPGVerifyException
31
+ from debkit.repo.hashes import ChecksumException
32
+ from debkit.repo.package import PackageException
33
+ from debkit.repo.packages import PackagesException
34
+ from debkit.repo.params import RepoParamsException
35
+ from debkit.repo.release import (
36
+ ReleaseFreshnessException,
37
+ ReleaseReadException,
38
+ ReleaseWriteException,
39
+ )
40
+ from debkit.repo.repo_sync import RepoSyncException
41
+
42
+ logger = logging.getLogger(__name__)
43
+ logger.addHandler(logging.NullHandler())
44
+
45
+
46
+ def err_exit(message: object) -> NoReturn:
47
+ """Log a critical message and exit with status 1.
48
+
49
+ Args:
50
+ message: Error message; coerced to ``str`` for logging.
51
+ """
52
+ logger.critical(message)
53
+ sys.exit(1)
54
+
55
+
56
+ def main(argv: list[str] | None = None) -> None:
57
+ """Run one debkit command.
58
+
59
+ Args:
60
+ argv: Arguments without the program name; None reads ``sys.argv``.
61
+
62
+ Raises:
63
+ SystemExit: Status 2 on a usage error, 1 on a mapped failure
64
+ → [EXCEPTIONS.md](EXCEPTIONS.md#cli-exit-groups).
65
+ """
66
+ pars = parse_cli(argv)
67
+ configure_logging(pars.log_level, pars.log_format)
68
+ if not verify_policy(pars).verify_ssl:
69
+ # txstore logs one warning per storage; urllib3 would add one per request.
70
+ urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
71
+
72
+ logger.debug("debkit version: %s", __version__)
73
+
74
+ try:
75
+ match pars.command:
76
+ case "list":
77
+ ActionPkg(pars).list_packages()
78
+ case "dump":
79
+ ActionPkg(pars).dump()
80
+ case "stats":
81
+ ActionPkg(pars).stats()
82
+ case "insert":
83
+ ActionPkg(pars, create_path=True).insert()
84
+ case "remove":
85
+ ActionPkg(pars, create_path=True).remove()
86
+ case "sync":
87
+ ActionSync(pars, create_path=True).sync()
88
+ case "check":
89
+ if not ActionCheck(pars).check():
90
+ err_exit("Repository is not consistent.")
91
+ case "log":
92
+ ActionHistory(pars).log()
93
+ case "revert":
94
+ ActionHistory(pars).revert()
95
+ case "prune":
96
+ ActionHistory(pars).prune()
97
+
98
+ except (
99
+ RepoReadException,
100
+ GPGVerifyException,
101
+ ComponentException,
102
+ ChangesException,
103
+ DebFileException,
104
+ PackageException,
105
+ PackagesException,
106
+ ReleaseReadException,
107
+ ) as exc:
108
+ logger.critical(exc)
109
+ err_exit("Can't read repository.")
110
+
111
+ except (ChecksumException, ReleaseFreshnessException) as exc:
112
+ logger.critical(exc)
113
+ err_exit("Distrustful object.")
114
+
115
+ except ReleaseWriteException as exc:
116
+ logger.critical(exc)
117
+ logger.warning("Some data may have been left unfinished.")
118
+ err_exit("Can't write repository.")
119
+
120
+ except RepoSyncException as exc:
121
+ logger.critical(exc)
122
+ logger.warning("Some data may have remained incomplete.")
123
+ err_exit("Sync failed.")
124
+
125
+ except (
126
+ ActionException,
127
+ RepoParamsException,
128
+ StorageException,
129
+ ) as exc:
130
+ err_exit(exc)