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/__init__.py +7 -0
- debkit/__main__.py +8 -0
- debkit/_env.py +67 -0
- debkit/_escape.py +25 -0
- debkit/_logging.py +98 -0
- debkit/_options.py +177 -0
- debkit/action/__init__.py +325 -0
- debkit/action/action_history.py +191 -0
- debkit/action/action_pkg.py +468 -0
- debkit/action/action_sync.py +495 -0
- debkit/argparser.py +246 -0
- debkit/argtypes.py +140 -0
- debkit/cli.py +130 -0
- debkit/repo/__init__.py +610 -0
- debkit/repo/changes.py +172 -0
- debkit/repo/component.py +335 -0
- debkit/repo/compress.py +266 -0
- debkit/repo/debfile.py +207 -0
- debkit/repo/gnupg.py +215 -0
- debkit/repo/hashes.py +139 -0
- debkit/repo/index_selection.py +224 -0
- debkit/repo/package.py +177 -0
- debkit/repo/packages.py +525 -0
- debkit/repo/params.py +305 -0
- debkit/repo/release.py +881 -0
- debkit/repo/repo_diff.py +114 -0
- debkit/repo/repo_rw.py +444 -0
- debkit/repo/repo_sync.py +433 -0
- debkit/repo/shared_root.py +348 -0
- debkit/repo/sources.py +165 -0
- debkit/repo/stanza.py +47 -0
- debkit-0.1.0.dist-info/METADATA +138 -0
- debkit-0.1.0.dist-info/RECORD +36 -0
- debkit-0.1.0.dist-info/WHEEL +4 -0
- debkit-0.1.0.dist-info/entry_points.txt +2 -0
- debkit-0.1.0.dist-info/licenses/LICENSE +21 -0
debkit/__init__.py
ADDED
debkit/__main__.py
ADDED
debkit/_env.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""Read ``DEBKIT_*`` environment variables.
|
|
2
|
+
|
|
3
|
+
The only module that reads `os.environ`. Each helper returns one variable's raw or parsed value,
|
|
4
|
+
or None when it is unset or empty; the CLI resolves a flag first, then the variable, then the
|
|
5
|
+
default → [CONFIG.md](CONFIG.md#resolution). Grammar →
|
|
6
|
+
[VALIDATION.md](VALIDATION.md#environment-values). `child_env` builds the environment a child
|
|
7
|
+
process runs with → [CONFIG.md](CONFIG.md#secrets).
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import os
|
|
13
|
+
|
|
14
|
+
ENV_PREFIX = "DEBKIT_"
|
|
15
|
+
# prefixes of the variables that carry debkit's and txstore's secrets and credentialed URLs
|
|
16
|
+
_CHILD_DROPPED_PREFIXES = (ENV_PREFIX, "TXSTORE_")
|
|
17
|
+
|
|
18
|
+
_TRUE = frozenset({"1", "true", "yes", "on"})
|
|
19
|
+
_FALSE = frozenset({"0", "false", "no", "off"})
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def env_str(name: str) -> str | None:
|
|
23
|
+
"""Return the value of variable `name`, or None when unset or empty.
|
|
24
|
+
|
|
25
|
+
Raises:
|
|
26
|
+
ValueError: If `name` lacks the ``DEBKIT_`` prefix (a programming error).
|
|
27
|
+
"""
|
|
28
|
+
if not name.startswith(ENV_PREFIX):
|
|
29
|
+
raise ValueError(f"environment variable {name!r} lacks the {ENV_PREFIX} prefix")
|
|
30
|
+
value = os.environ.get(name)
|
|
31
|
+
return value if value else None
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def env_bool(name: str) -> bool | None:
|
|
35
|
+
"""Return the boolean value of `name`, or None when unset or empty.
|
|
36
|
+
|
|
37
|
+
Accepts ``1/0``, ``true/false``, ``yes/no``, and ``on/off`` in any case.
|
|
38
|
+
|
|
39
|
+
Raises:
|
|
40
|
+
ValueError: If the value is outside that vocabulary.
|
|
41
|
+
"""
|
|
42
|
+
value = env_str(name)
|
|
43
|
+
if value is None:
|
|
44
|
+
return None
|
|
45
|
+
folded = value.strip().lower()
|
|
46
|
+
if folded in _TRUE:
|
|
47
|
+
return True
|
|
48
|
+
if folded in _FALSE:
|
|
49
|
+
return False
|
|
50
|
+
raise ValueError(f"expected a boolean (1/0, true/false, yes/no, on/off), got {value!r}")
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def child_env() -> dict[str, str]:
|
|
54
|
+
"""Return the environment a child process runs with: this one without debkit's variables.
|
|
55
|
+
|
|
56
|
+
A child such as `zstd` or `gpg` reads untrusted data and needs none of them, so it never
|
|
57
|
+
holds a secret or a credentialed URL → [CONFIG.md](CONFIG.md#secrets). `PATH` and the
|
|
58
|
+
rest stay, so the child is found and runs as before.
|
|
59
|
+
|
|
60
|
+
Returns:
|
|
61
|
+
A copy of the environment without the ``DEBKIT_*`` and ``TXSTORE_*`` variables.
|
|
62
|
+
"""
|
|
63
|
+
return {
|
|
64
|
+
key: value
|
|
65
|
+
for key, value in os.environ.items()
|
|
66
|
+
if not key.startswith(_CHILD_DROPPED_PREFIXES)
|
|
67
|
+
}
|
debkit/_escape.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""Control-character escaping for untrusted text bound for a terminal.
|
|
2
|
+
|
|
3
|
+
Repository content (Release fields, storage keys) could carry an ANSI escape that rewrites the
|
|
4
|
+
terminal, or a newline that forges a line (CWE-117); log lines and brief output escape it the
|
|
5
|
+
same way → [CONFIG.md](CONFIG.md#output-flag). A leaf: it imports no `debkit` module.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
# C0 and C1 control characters and DEL, except tab, each become a visible ``\xNN``.
|
|
11
|
+
CONTROL_ESCAPES = {
|
|
12
|
+
code: f"\\x{code:02x}" for code in (*range(0x20), *range(0x7F, 0xA0)) if code != ord("\t")
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def escape_control(text: str) -> str:
|
|
17
|
+
r"""Replace each C0/C1 control character but tab in `text` with ``\xNN``.
|
|
18
|
+
|
|
19
|
+
Args:
|
|
20
|
+
text: Untrusted text.
|
|
21
|
+
|
|
22
|
+
Returns:
|
|
23
|
+
The text, safe to write to a terminal on one line.
|
|
24
|
+
"""
|
|
25
|
+
return text.translate(CONTROL_ESCAPES)
|
debkit/_logging.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"""Root logger configuration for the CLI.
|
|
2
|
+
|
|
3
|
+
Only `cli.main` calls `configure_logging`; every other module logs through its own logger and
|
|
4
|
+
never configures handlers → [STYLE.md](STYLE.md#logging). It imports only the `_escape` leaf.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import logging
|
|
11
|
+
from enum import StrEnum
|
|
12
|
+
|
|
13
|
+
from debkit._escape import escape_control
|
|
14
|
+
|
|
15
|
+
LOG_LEVELS = ("CRITICAL", "ERROR", "WARNING", "INFO", "DEBUG")
|
|
16
|
+
|
|
17
|
+
# Chatty third-party loggers held at INFO when the root runs at DEBUG; python-gnupg logs every
|
|
18
|
+
# gpg command line and status line there, and `GnuPG.verify` logs the status of a failure itself
|
|
19
|
+
QUIET_LOGGERS = ("urllib3", "botocore", "boto3", "s3transfer", "gnupg")
|
|
20
|
+
|
|
21
|
+
_PLAIN_FORMAT = "%(levelname)s %(message)s"
|
|
22
|
+
_DEBUG_FORMAT = "%(levelname)s %(module)s %(funcName)s %(message)s"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class LogFormat(StrEnum):
|
|
26
|
+
"""Log line format."""
|
|
27
|
+
|
|
28
|
+
plain = "plain"
|
|
29
|
+
json = "json"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class _PlainFormatter(logging.Formatter):
|
|
33
|
+
"""Emit one plain line per record with control characters escaped.
|
|
34
|
+
|
|
35
|
+
Repository content in a message (package names, Release fields, URLs) could otherwise carry a
|
|
36
|
+
newline or carriage return that forges an extra entry, or an ANSI escape that rewrites the
|
|
37
|
+
terminal (CWE-117). A traceback still spans several lines; `LogFormat.json` keeps it on one.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
def formatMessage(self, record: logging.LogRecord) -> str:
|
|
41
|
+
r"""Format `record` through the template, then escape its control characters.
|
|
42
|
+
|
|
43
|
+
Returns:
|
|
44
|
+
The formatted line with each C0/C1 control except tab replaced by ``\xNN``.
|
|
45
|
+
"""
|
|
46
|
+
return escape_control(super().formatMessage(record))
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class _JsonFormatter(logging.Formatter):
|
|
50
|
+
"""Emit one JSON object per log record with escaped fields.
|
|
51
|
+
|
|
52
|
+
A ``%(message)s`` template does not escape quotes, backslashes, or control characters, so
|
|
53
|
+
repository content in a message (package names, Release fields, URLs) could forge extra
|
|
54
|
+
entries in a line-based log shipper (CWE-117); `json.dumps` keeps each record one line.
|
|
55
|
+
"""
|
|
56
|
+
|
|
57
|
+
def format(self, record: logging.LogRecord) -> str:
|
|
58
|
+
"""Format `record` as a single-line JSON object.
|
|
59
|
+
|
|
60
|
+
Returns:
|
|
61
|
+
JSON with ``time``, ``name``, ``level``, and ``message``, plus ``exception`` and
|
|
62
|
+
``stack`` when the record carries them.
|
|
63
|
+
"""
|
|
64
|
+
payload: dict[str, object] = {
|
|
65
|
+
"time": self.formatTime(record),
|
|
66
|
+
"name": record.name,
|
|
67
|
+
"level": record.levelname,
|
|
68
|
+
"message": record.getMessage(),
|
|
69
|
+
}
|
|
70
|
+
if record.exc_info:
|
|
71
|
+
payload["exception"] = self.formatException(record.exc_info)
|
|
72
|
+
if record.stack_info:
|
|
73
|
+
payload["stack"] = self.formatStack(record.stack_info)
|
|
74
|
+
return json.dumps(payload, ensure_ascii=False)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def configure_logging(level: str, log_format: LogFormat = LogFormat.plain) -> None:
|
|
78
|
+
"""Configure the root logger on stderr, replacing any handler already installed.
|
|
79
|
+
|
|
80
|
+
Python warnings are captured into the ``py.warnings`` logger, so they reach the same handler.
|
|
81
|
+
|
|
82
|
+
Args:
|
|
83
|
+
level: One of `LOG_LEVELS`.
|
|
84
|
+
log_format: Plain lines (module and function added at DEBUG) or one JSON object per line.
|
|
85
|
+
"""
|
|
86
|
+
logging.captureWarnings(True)
|
|
87
|
+
numeric = logging.getLevelNamesMapping()[level]
|
|
88
|
+
handler = logging.StreamHandler()
|
|
89
|
+
if log_format is LogFormat.json:
|
|
90
|
+
handler.setFormatter(_JsonFormatter())
|
|
91
|
+
else:
|
|
92
|
+
handler.setFormatter(
|
|
93
|
+
_PlainFormatter(_DEBUG_FORMAT if numeric <= logging.DEBUG else _PLAIN_FORMAT)
|
|
94
|
+
)
|
|
95
|
+
logging.basicConfig(level=numeric, handlers=[handler], force=True)
|
|
96
|
+
if numeric <= logging.DEBUG:
|
|
97
|
+
for name in QUIET_LOGGERS:
|
|
98
|
+
logging.getLogger(name).setLevel(logging.INFO)
|
debkit/_options.py
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
"""Argparse options backed by ``DEBKIT_*`` environment variables.
|
|
2
|
+
|
|
3
|
+
`EnvArgumentParser.add_env_argument` registers an option with ``default=None`` and records its
|
|
4
|
+
variable, default, and converter; `EnvArgumentParser.add_env_variable` records a variable with no
|
|
5
|
+
flag. After argparse has parsed the command line, each value still None resolves from its
|
|
6
|
+
variable, then from its default → [CONFIG.md](CONFIG.md#resolution). Subparsers inherit the
|
|
7
|
+
class, so each parser resolves its own options.
|
|
8
|
+
|
|
9
|
+
A leaf over `_env`: it imports no other `debkit` module → [STRUCTURE.md](STRUCTURE.md#dependencies).
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from argparse import Action, ArgumentParser, ArgumentTypeError, BooleanOptionalAction, Namespace
|
|
15
|
+
from collections.abc import Callable, Sequence
|
|
16
|
+
from dataclasses import dataclass
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
from debkit._env import env_bool, env_str
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True)
|
|
23
|
+
class EnvOption:
|
|
24
|
+
"""One option resolved from the command line, then a variable, then a default.
|
|
25
|
+
|
|
26
|
+
Attributes:
|
|
27
|
+
dest: Namespace attribute.
|
|
28
|
+
flag: Longest option string, named in error messages; None for a variable without a flag.
|
|
29
|
+
env: ``DEBKIT_*`` variable read when the flag is absent.
|
|
30
|
+
default: Value when neither flag nor variable is given.
|
|
31
|
+
convert: Converter applied to a variable's string value; None keeps the string.
|
|
32
|
+
choices: Allowed converted values; None allows any.
|
|
33
|
+
switch: Boolean switch: the variable is read with `env_bool`.
|
|
34
|
+
required: Fail when no value resolves.
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
dest: str
|
|
38
|
+
flag: str | None
|
|
39
|
+
env: str
|
|
40
|
+
default: Any
|
|
41
|
+
convert: Callable[[str], Any] | None
|
|
42
|
+
choices: Sequence[Any] | None
|
|
43
|
+
switch: bool
|
|
44
|
+
required: bool
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class EnvArgumentParser(ArgumentParser):
|
|
48
|
+
"""`ArgumentParser` whose options can fall back to ``DEBKIT_*`` variables."""
|
|
49
|
+
|
|
50
|
+
def __init__(self, *args: Any, **kwargs: Any) -> None:
|
|
51
|
+
super().__init__(*args, **kwargs)
|
|
52
|
+
self._env_options: list[EnvOption] = []
|
|
53
|
+
self._env_only_help: dict[str, str] = {}
|
|
54
|
+
|
|
55
|
+
def add_env_argument(
|
|
56
|
+
self,
|
|
57
|
+
*flags: str,
|
|
58
|
+
env: str,
|
|
59
|
+
help: str,
|
|
60
|
+
default: Any = None,
|
|
61
|
+
required: bool = False,
|
|
62
|
+
**kwargs: Any,
|
|
63
|
+
) -> Action:
|
|
64
|
+
"""Register an option that falls back to `env`, then to `default`.
|
|
65
|
+
|
|
66
|
+
``action=BooleanOptionalAction`` makes a switch with a ``--no-`` form; any other option
|
|
67
|
+
takes a value converted by ``type``. Help names the variable and the default.
|
|
68
|
+
|
|
69
|
+
Args:
|
|
70
|
+
*flags: Option strings, as for `add_argument`.
|
|
71
|
+
env: ``DEBKIT_*`` variable read when the flag is absent.
|
|
72
|
+
help: Help text without the variable or default.
|
|
73
|
+
default: Value when neither flag nor variable is given.
|
|
74
|
+
required: Fail after resolution when no value resolves.
|
|
75
|
+
**kwargs: Passed to `add_argument` (``type``, ``choices``, ``action``, ``dest``).
|
|
76
|
+
|
|
77
|
+
Returns:
|
|
78
|
+
The registered argparse action.
|
|
79
|
+
"""
|
|
80
|
+
details = [f"env: {env}"]
|
|
81
|
+
if default not in (None, ""):
|
|
82
|
+
details.append(f"default: {default}")
|
|
83
|
+
text = f"{help} [{'; '.join(details)}]".replace("%", "%%")
|
|
84
|
+
action = self.add_argument(*flags, default=None, help=text, **kwargs)
|
|
85
|
+
self._env_options.append(
|
|
86
|
+
EnvOption(
|
|
87
|
+
dest=action.dest,
|
|
88
|
+
flag=max(action.option_strings, key=len),
|
|
89
|
+
env=env,
|
|
90
|
+
default=default,
|
|
91
|
+
convert=kwargs.get("type"),
|
|
92
|
+
choices=kwargs.get("choices"),
|
|
93
|
+
switch=kwargs.get("action") is BooleanOptionalAction,
|
|
94
|
+
required=required,
|
|
95
|
+
)
|
|
96
|
+
)
|
|
97
|
+
return action
|
|
98
|
+
|
|
99
|
+
def add_env_variable(self, env: str, *, dest: str, help: str, default: Any = None) -> None:
|
|
100
|
+
"""Register a value read only from `env`, then `default`; no flag sets it.
|
|
101
|
+
|
|
102
|
+
For secrets: a command-line value is visible to other local users →
|
|
103
|
+
[CONFIG.md](CONFIG.md#secrets). Help names the variable, never its value or default.
|
|
104
|
+
|
|
105
|
+
Args:
|
|
106
|
+
env: ``DEBKIT_*`` variable holding the value.
|
|
107
|
+
dest: Namespace attribute.
|
|
108
|
+
help: Help text without the variable.
|
|
109
|
+
default: Value when the variable is unset or empty.
|
|
110
|
+
"""
|
|
111
|
+
self._env_options.append(
|
|
112
|
+
EnvOption(
|
|
113
|
+
dest=dest,
|
|
114
|
+
flag=None,
|
|
115
|
+
env=env,
|
|
116
|
+
default=default,
|
|
117
|
+
convert=None,
|
|
118
|
+
choices=None,
|
|
119
|
+
switch=False,
|
|
120
|
+
required=False,
|
|
121
|
+
)
|
|
122
|
+
)
|
|
123
|
+
self._env_only_help[env] = help
|
|
124
|
+
|
|
125
|
+
def format_help(self) -> str:
|
|
126
|
+
"""Return argparse help followed by the variables registered without a flag."""
|
|
127
|
+
text = super().format_help()
|
|
128
|
+
if not self._env_only_help:
|
|
129
|
+
return text
|
|
130
|
+
width = max(map(len, self._env_only_help))
|
|
131
|
+
rows = [f" {env:<{width}} {line}" for env, line in self._env_only_help.items()]
|
|
132
|
+
return "\n".join([text, "environment-only variables:", *rows, ""])
|
|
133
|
+
|
|
134
|
+
def parse_known_args( # type: ignore[override]
|
|
135
|
+
self, args: Sequence[str] | None = None, namespace: Namespace | None = None
|
|
136
|
+
) -> tuple[Namespace, list[str]]:
|
|
137
|
+
"""Parse `args`, then resolve every option of this parser still None.
|
|
138
|
+
|
|
139
|
+
Raises:
|
|
140
|
+
SystemExit: Status 2 when a variable holds an invalid value or a required option
|
|
141
|
+
resolves no value.
|
|
142
|
+
"""
|
|
143
|
+
parsed, extras = super().parse_known_args(args, namespace)
|
|
144
|
+
for option in self._env_options:
|
|
145
|
+
if getattr(parsed, option.dest, None) is None:
|
|
146
|
+
setattr(parsed, option.dest, self._resolve(option))
|
|
147
|
+
return parsed, extras
|
|
148
|
+
|
|
149
|
+
def _resolve(self, option: EnvOption) -> Any:
|
|
150
|
+
"""Return the variable's converted value, else the default."""
|
|
151
|
+
try:
|
|
152
|
+
value = self._read_env(option)
|
|
153
|
+
except (ArgumentTypeError, ValueError, TypeError) as exc:
|
|
154
|
+
self.error(f"{option.env}: {exc}")
|
|
155
|
+
if value is not None:
|
|
156
|
+
return value
|
|
157
|
+
if option.required:
|
|
158
|
+
self.error(f"{option.flag} or {option.env} is required")
|
|
159
|
+
return option.default
|
|
160
|
+
|
|
161
|
+
@staticmethod
|
|
162
|
+
def _read_env(option: EnvOption) -> Any:
|
|
163
|
+
"""Read and convert `option`'s variable; None when unset or empty.
|
|
164
|
+
|
|
165
|
+
Raises:
|
|
166
|
+
ValueError: If the value is not in the option's choices, or the converter rejects it.
|
|
167
|
+
"""
|
|
168
|
+
if option.switch:
|
|
169
|
+
return env_bool(option.env)
|
|
170
|
+
raw = env_str(option.env)
|
|
171
|
+
if raw is None:
|
|
172
|
+
return None
|
|
173
|
+
value = option.convert(raw) if option.convert else raw
|
|
174
|
+
if option.choices is not None and value not in option.choices:
|
|
175
|
+
allowed = ", ".join(str(choice) for choice in option.choices)
|
|
176
|
+
raise ValueError(f"invalid choice: {raw!r} (choose from {allowed})")
|
|
177
|
+
return value
|