datadouble 0.0.3__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.
datadouble/programs.py ADDED
@@ -0,0 +1,68 @@
1
+ # Copyright (c) 2026- Tight Line LLC
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """Running the external programs Datadouble wraps: ``docker``, ``kubectl``, ``cosign``...
5
+
6
+ Datadouble wraps mature tools rather than reimplementing them, so it runs them
7
+ often. Every run goes through here: a program found by name (or named by an
8
+ environment variable), arguments as a list and never through a shell, and
9
+ output captured for the caller to check.
10
+ """
11
+
12
+ import os
13
+ import shutil
14
+ import subprocess
15
+ from collections.abc import Mapping, Sequence
16
+ from dataclasses import dataclass
17
+
18
+
19
+ @dataclass(frozen=True, slots=True)
20
+ class Completed:
21
+ """A finished program: its status and output."""
22
+
23
+ status: int
24
+ stdout: str
25
+ stderr: str
26
+
27
+ def last_error(self) -> str:
28
+ """The last line of standard error, or the status if there is none."""
29
+ lines = [line for line in self.stderr.strip().splitlines() if line.strip()]
30
+ return lines[-1] if lines else f"status {self.status}"
31
+
32
+
33
+ def locate(name: str, variable: str | None = None) -> str | None:
34
+ """The path of program ``name``: the environment variable ``variable`` if set, else ``PATH``."""
35
+ configured = os.environ.get(variable) if variable else None
36
+ return configured or shutil.which(name)
37
+
38
+
39
+ def run_program(
40
+ program: str,
41
+ arguments: Sequence[str],
42
+ *,
43
+ stdin: str | bytes | None = None,
44
+ env: Mapping[str, str] | None = None,
45
+ ) -> Completed:
46
+ """Run ``program`` with ``arguments`` and wait; ``env`` is added to the environment.
47
+
48
+ Output is decoded as UTF-8, with anything undecodable replaced.
49
+ """
50
+ result = subprocess.run( # noqa: S603 - the one place programs run: no shell, arguments as a list
51
+ [program, *arguments],
52
+ input=stdin.encode() if isinstance(stdin, str) else stdin,
53
+ capture_output=True,
54
+ check=False,
55
+ env={**os.environ, **(env or {})},
56
+ )
57
+ return Completed(
58
+ status=result.returncode,
59
+ stdout=result.stdout.decode(errors="replace"),
60
+ stderr=result.stderr.decode(errors="replace"),
61
+ )
62
+
63
+
64
+ def start_program(program: str, arguments: Sequence[str]) -> "subprocess.Popen[str]":
65
+ """Start ``program`` without waiting; its standard output can be read as text."""
66
+ return subprocess.Popen( # noqa: S603 - as run_program, for programs that keep running
67
+ [program, *arguments], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True
68
+ )
datadouble/promote.py ADDED
@@ -0,0 +1,190 @@
1
+ # Copyright (c) 2026- Tight Line LLC
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """``promote``: the only way an image leaves production.
5
+
6
+ ``promote`` runs in production. It copies images from the build's store into
7
+ the export stores, the only storage non-production can read, and advances a
8
+ channel there, then rewrites the group's index (``index.json``), which stores
9
+ that cannot list keys are read through. It checks every image before copying
10
+ any, and refuses an image unless:
11
+
12
+ - verification passed, with every check run and none failed;
13
+ - it was built with strict-mode levels, for every kind, at least as strict as
14
+ required;
15
+ - it carries a signature the spec's ``trust`` settings accept;
16
+ - every archive's content matches the hash in its summary.
17
+ """
18
+
19
+ import tempfile
20
+ from dataclasses import dataclass
21
+ from pathlib import Path
22
+ from typing import TYPE_CHECKING
23
+
24
+ from pydantic import BaseModel, ConfigDict
25
+
26
+ from datadouble.boundary import require_inside
27
+ from datadouble.channels import point_channel
28
+ from datadouble.images import (
29
+ ImageSummary,
30
+ digest,
31
+ generations,
32
+ image_lines,
33
+ read_summary,
34
+ write_index,
35
+ )
36
+ from datadouble.names import Generation, GroupName
37
+ from datadouble.signing import SigningError, bundle_key, verify
38
+ from datadouble.spec import CosignTrust, Spec, Strict
39
+ from datadouble.storage import Store
40
+
41
+ if TYPE_CHECKING:
42
+ from datadouble.registry import Registry
43
+
44
+
45
+ class PromoteError(Exception):
46
+ """Images that may not cross into non-production, and why."""
47
+
48
+ def __init__(self, problems: tuple[str, ...]) -> None:
49
+ """Keep every reason."""
50
+ count = len(problems)
51
+ super().__init__(f"promote refused: {count} problem{'s' if count != 1 else ''}")
52
+ self.problems = problems
53
+
54
+
55
+ class Promoted(BaseModel):
56
+ """One image now in the export stores."""
57
+
58
+ model_config = ConfigDict(strict=True, frozen=True, extra="forbid")
59
+
60
+ summary: ImageSummary
61
+ channel: str
62
+ stores: tuple[str, ...]
63
+
64
+
65
+ @dataclass(frozen=True)
66
+ class _Candidate:
67
+ prefix: str
68
+ summary: ImageSummary
69
+ bundle: bytes
70
+ files: dict[str, Path]
71
+
72
+
73
+ def check_signature(store: Store, summary: ImageSummary, trust: CosignTrust) -> bytes:
74
+ """The image's signature bundle, verified; raises :class:`SigningError`."""
75
+ if summary.signature is None:
76
+ message = "the image is not signed"
77
+ raise SigningError(message)
78
+ bundle = store.get_bytes(summary.signature)
79
+ if bundle is None:
80
+ message = f"its signature {summary.signature} is missing"
81
+ raise SigningError(message)
82
+ verify(summary, bundle, trust)
83
+ return bundle
84
+
85
+
86
+ def _problems(summary: ImageSummary, required: Strict) -> list[str]:
87
+ name = f"{summary.identity.prefix()}/{summary.identity.generation}"
88
+ problems: list[str] = []
89
+ verification = summary.verification
90
+ if not verification.passed or verification.failed or not verification.checks:
91
+ problems.append(f"{name}: verification did not pass")
92
+ problems.extend(
93
+ f"{name}: built with strict mode {kind} {summary.strict.level(kind)}, "
94
+ f"but {required.level(kind)} is required"
95
+ for kind in summary.strict.weaker(required)
96
+ )
97
+ return problems
98
+
99
+
100
+ class _Promotion:
101
+ def __init__(self, spec: Spec, registry: "Registry", scratch: Path) -> None:
102
+ if spec.promote is None or spec.trust is None:
103
+ message = "the spec needs `promote` and `trust` sections to promote images"
104
+ raise PromoteError((message,))
105
+ if not spec.store:
106
+ raise PromoteError(("the spec lists no stores to promote from",))
107
+ self.spec = spec
108
+ self.settings = spec.promote
109
+ self.trust = spec.trust.cosign
110
+ self.source = registry.store(*next(iter(spec.store[0].items())))
111
+ self.targets = [
112
+ registry.store(kind, settings)
113
+ for entry in spec.promote.to
114
+ for kind, settings in entry.items()
115
+ ]
116
+ self.scratch = scratch
117
+
118
+ def candidate(self, prefix: str, generation: Generation | None) -> _Candidate | str | None:
119
+ """The image to promote from one line, the reasons it may not be, or None."""
120
+ known = generations(self.source, prefix)
121
+ chosen = generation or known[-1]
122
+ summary = read_summary(self.source, prefix, chosen) if chosen in known else None
123
+ if summary is None:
124
+ return None
125
+ problems = _problems(summary, self.settings.strict)
126
+ try:
127
+ bundle = check_signature(self.source, summary, self.trust)
128
+ except SigningError as error:
129
+ problems.append(f"{prefix}/{summary.identity.generation}: {error}")
130
+ bundle = b""
131
+ files: dict[str, Path] = {}
132
+ for archive in summary.archives:
133
+ local = self.scratch / archive.key.replace("/", "_")
134
+ if not self.source.get_file(archive.key, local):
135
+ problems.append(f"{archive.key} is missing")
136
+ elif digest(local) != archive.digest:
137
+ problems.append(f"{archive.key} does not match the hash in its summary")
138
+ files[archive.key] = local
139
+ return "; ".join(problems) if problems else _Candidate(prefix, summary, bundle, files)
140
+
141
+ def copy(self, candidate: _Candidate) -> Promoted:
142
+ summary = candidate.summary
143
+ report_key = summary.identity.summary_key().replace(".summary.json", ".verify.json")
144
+ report = self.source.get_bytes(report_key)
145
+ for target in self.targets:
146
+ for key, local in candidate.files.items():
147
+ target.put_file(key, local)
148
+ if report is not None:
149
+ target.put_bytes(report_key, report)
150
+ target.put_bytes(bundle_key(summary), candidate.bundle)
151
+ target.put_bytes(
152
+ summary.identity.summary_key(), summary.model_dump_json(indent=2).encode()
153
+ )
154
+ point_channel(
155
+ target, candidate.prefix, self.settings.channel, summary.identity.generation
156
+ )
157
+ write_index(target, summary.identity.spec, summary.identity.group)
158
+ return Promoted(
159
+ summary=summary,
160
+ channel=self.settings.channel,
161
+ stores=tuple(target.describe() for target in self.targets),
162
+ )
163
+
164
+
165
+ def promote(
166
+ spec: Spec,
167
+ registry: "Registry",
168
+ *,
169
+ groups: tuple[GroupName, ...] = (),
170
+ generation: Generation | None = None,
171
+ ) -> tuple[Promoted, ...]:
172
+ """Promote the newest (or the given) generation of each group; all or nothing."""
173
+ require_inside("promote", registry)
174
+ with tempfile.TemporaryDirectory(prefix="dd-promote-") as directory:
175
+ promotion = _Promotion(spec, registry, Path(directory))
176
+ wanted = groups or tuple(spec.images)
177
+ candidates: list[_Candidate] = []
178
+ problems: list[str] = []
179
+ for group in wanted:
180
+ prefixes = image_lines(promotion.source, spec.name, group)
181
+ if not prefixes:
182
+ problems.append(f"{spec.name}/{group}: no images in {promotion.source.describe()}")
183
+ found = [promotion.candidate(prefix, generation) for prefix in prefixes]
184
+ problems.extend(item for item in found if isinstance(item, str))
185
+ candidates.extend(item for item in found if isinstance(item, _Candidate))
186
+ if prefixes and generation is not None and all(item is None for item in found):
187
+ problems.append(f"{spec.name}/{group}: no generation {generation}")
188
+ if problems:
189
+ raise PromoteError(tuple(problems))
190
+ return tuple(promotion.copy(candidate) for candidate in candidates)
datadouble/prune.py ADDED
@@ -0,0 +1,258 @@
1
+ # Copyright (c) 2026- Tight Line LLC
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """``prune``: retention for stores and staging.
5
+
6
+ For each image line, ``prune`` keeps the newest ``prune.keep`` generations
7
+ (``fetch.keep`` in staging), anything built within ``prune.keep_days``, and
8
+ whatever any channel points at. Of a group's engine versions, only the newest
9
+ ``prune.keep_versions`` of each engine keep their generations (a spec with
10
+ ``files`` has a files line beside the database's); older versions keep only
11
+ their channels' targets, and their unclaimed pool copies are removed. A
12
+ channel's target is never removed. ``--dry-run`` reports what would go. In
13
+ the export stores, each group's index is rewritten to match what is left, or
14
+ removed when nothing is.
15
+ """
16
+
17
+ import datetime as dt
18
+ from collections.abc import Callable
19
+ from dataclasses import dataclass
20
+ from enum import StrEnum
21
+ from pathlib import Path
22
+ from typing import TYPE_CHECKING, assert_never
23
+
24
+ from pydantic import BaseModel, ConfigDict
25
+
26
+ from datadouble.channels import Channel
27
+ from datadouble.images import (
28
+ current_lines,
29
+ generations,
30
+ image_lines,
31
+ index_key,
32
+ read_summary,
33
+ write_index,
34
+ )
35
+ from datadouble.names import Generation
36
+ from datadouble.replicate import CopyState, Line, Options, Replication
37
+ from datadouble.spec import Retention, Spec
38
+ from datadouble.staging import Staging, remove_directory
39
+ from datadouble.storage import Store
40
+
41
+ if TYPE_CHECKING:
42
+ from datadouble.registry import Registry
43
+
44
+
45
+ class PruneError(Exception):
46
+ """Retention that cannot be applied as asked."""
47
+
48
+
49
+ class PruneTarget(StrEnum):
50
+ """Where to prune."""
51
+
52
+ STORE = "store"
53
+ """The build's stores (production)."""
54
+ EXPORT = "export"
55
+ """The export stores ``promote`` writes to (production)."""
56
+ STAGING = "staging"
57
+ """Staging (non-production)."""
58
+
59
+
60
+ class Pruned(BaseModel):
61
+ """One generation removed (or that would be, on a dry run)."""
62
+
63
+ model_config = ConfigDict(strict=True, frozen=True, extra="forbid")
64
+
65
+ location: str
66
+ prefix: str
67
+ generation: Generation
68
+ bytes: int
69
+
70
+
71
+ class PruneResult(BaseModel):
72
+ """What ``prune`` removed, or would remove."""
73
+
74
+ model_config = ConfigDict(strict=True, frozen=True, extra="forbid")
75
+
76
+ dry_run: bool
77
+ removed: tuple[Pruned, ...]
78
+ copies_removed: tuple[str, ...] = ()
79
+
80
+ @property
81
+ def bytes(self) -> int:
82
+ """Space recovered."""
83
+ return sum(item.bytes for item in self.removed)
84
+
85
+
86
+ def _protected(channels: list[Channel]) -> set[Generation]:
87
+ return {channel.generation for channel in channels}
88
+
89
+
90
+ def _store_channels(store: Store, prefix: str) -> list[Channel]:
91
+ return [
92
+ Channel.model_validate_json(data)
93
+ for key in store.list(f"{prefix}/channels/")
94
+ if (data := store.get_bytes(key)) is not None
95
+ ]
96
+
97
+
98
+ @dataclass(frozen=True)
99
+ class _Rules:
100
+ keep: int
101
+ cutoff: dt.datetime
102
+ current_version: bool
103
+ protected: set[Generation]
104
+
105
+
106
+ def _doomed(
107
+ known: list[Generation], built: Callable[[Generation], dt.datetime | None], rules: _Rules
108
+ ) -> list[Generation]:
109
+ """The generations retention removes, oldest first."""
110
+ newest = set(known[-rules.keep :]) if rules.current_version else set[Generation]()
111
+ removable: list[Generation] = []
112
+ for generation in known:
113
+ when = built(generation)
114
+ recent = rules.current_version and when is not None and when >= rules.cutoff
115
+ if generation not in newest and generation not in rules.protected and not recent:
116
+ removable.append(generation)
117
+ return removable
118
+
119
+
120
+ def _prune_store(
121
+ spec: Spec, store: Store, retention: Retention, cutoff: dt.datetime, *, dry_run: bool
122
+ ) -> list[Pruned]:
123
+ removed: list[Pruned] = []
124
+ for group in spec.images:
125
+ lines = image_lines(store, spec.name, group)
126
+ current = current_lines(lines, retention.keep_versions)
127
+ for prefix in lines:
128
+ summaries = {g: read_summary(store, prefix, g) for g in generations(store, prefix)}
129
+ built = {g: s.built_at for g, s in summaries.items() if s is not None}
130
+ doomed = _doomed(
131
+ list(summaries),
132
+ built.get,
133
+ _Rules(
134
+ keep=retention.keep,
135
+ cutoff=cutoff,
136
+ current_version=prefix in current,
137
+ protected=_protected(_store_channels(store, prefix)),
138
+ ),
139
+ )
140
+ for generation in doomed:
141
+ summary = summaries[generation]
142
+ size = sum(a.digest.size for a in summary.archives) if summary else 0
143
+ removed.append(
144
+ Pruned(
145
+ location=store.describe(), prefix=prefix, generation=generation, bytes=size
146
+ )
147
+ )
148
+ if not dry_run:
149
+ for key in store.list(f"{prefix}/{generation}."):
150
+ store.delete(key)
151
+ return removed
152
+
153
+
154
+ def _reindex(spec: Spec, store: Store) -> None:
155
+ """Rewrite each group's index in an export store to match what is left, or remove it."""
156
+ for group in spec.images:
157
+ if image_lines(store, spec.name, group):
158
+ write_index(store, spec.name, group)
159
+ else:
160
+ store.delete(index_key(spec.name, group))
161
+
162
+
163
+ def _size(root: Path) -> int:
164
+ return sum(item.stat().st_size for item in root.rglob("*") if item.is_file())
165
+
166
+
167
+ def _prune_staging(
168
+ spec: Spec, registry: "Registry", retention: Retention, *, dry_run: bool
169
+ ) -> tuple[list[Pruned], list[str]]:
170
+ if spec.fetch is None:
171
+ message = "the spec needs a `fetch` section to prune staging"
172
+ raise PruneError(message)
173
+ staging = Staging(spec.fetch)
174
+ removed: list[Pruned] = []
175
+ copies_removed: list[str] = []
176
+ for group in spec.images:
177
+ lines = staging.lines(spec.name, group)
178
+ current = current_lines(lines, retention.keep_versions)
179
+ for prefix in lines:
180
+ with staging.locked(prefix):
181
+ channel = staging.channel(prefix)
182
+ staged = staging.staged(prefix)
183
+ doomed = _doomed(
184
+ staged,
185
+ lambda _generation: None,
186
+ _Rules(
187
+ keep=spec.fetch.keep,
188
+ cutoff=dt.datetime.max.replace(tzinfo=dt.UTC),
189
+ current_version=prefix in current,
190
+ protected=_protected([channel] if channel else []),
191
+ ),
192
+ )
193
+ for generation in doomed:
194
+ path = staging.line(prefix) / generation
195
+ removed.append(
196
+ Pruned(
197
+ location=str(staging.root),
198
+ prefix=prefix,
199
+ generation=generation,
200
+ bytes=_size(path),
201
+ )
202
+ )
203
+ if not dry_run:
204
+ remove_directory(path)
205
+ if prefix not in current and spec.replicate is not None:
206
+ copies_removed.extend(
207
+ _retire_pool(spec, registry, staging, prefix, dry_run=dry_run)
208
+ )
209
+ return removed, copies_removed
210
+
211
+
212
+ def _retire_pool(
213
+ spec: Spec, registry: "Registry", staging: Staging, prefix: str, *, dry_run: bool
214
+ ) -> list[str]:
215
+ work = Replication(spec, registry, Options())
216
+ line = Line(staging, prefix)
217
+ copies = line.load()
218
+ unclaimed = [c for c in copies if not c.claimed or c.state is CopyState.CREATING]
219
+ if not dry_run:
220
+ for copy in unclaimed:
221
+ work.remove(line, copies, copy)
222
+ return [copy.id for copy in unclaimed]
223
+
224
+
225
+ def prune(
226
+ spec: Spec,
227
+ registry: "Registry",
228
+ target: PruneTarget,
229
+ *,
230
+ dry_run: bool = False,
231
+ clock: Callable[[], dt.datetime] = lambda: dt.datetime.now(tz=dt.UTC),
232
+ ) -> PruneResult:
233
+ """Apply retention to one kind of place."""
234
+ retention = spec.prune
235
+ cutoff = clock() - dt.timedelta(days=retention.keep_days)
236
+ match target:
237
+ case PruneTarget.STORE | PruneTarget.EXPORT:
238
+ entries = (
239
+ spec.store
240
+ if target is PruneTarget.STORE
241
+ else (spec.promote.to if spec.promote else ())
242
+ )
243
+ if not entries:
244
+ message = f"the spec configures no {target} stores"
245
+ raise PruneError(message)
246
+ removed: list[Pruned] = []
247
+ for entry in entries:
248
+ for kind, settings in entry.items():
249
+ store = registry.store(kind, settings)
250
+ removed.extend(_prune_store(spec, store, retention, cutoff, dry_run=dry_run))
251
+ if target is PruneTarget.EXPORT and not dry_run:
252
+ _reindex(spec, store)
253
+ return PruneResult(dry_run=dry_run, removed=tuple(removed))
254
+ case PruneTarget.STAGING:
255
+ staged, copies = _prune_staging(spec, registry, retention, dry_run=dry_run)
256
+ return PruneResult(dry_run=dry_run, removed=tuple(staged), copies_removed=tuple(copies))
257
+ case _:
258
+ assert_never(target)
datadouble/py.typed ADDED
File without changes
@@ -0,0 +1,131 @@
1
+ # Copyright (c) 2026- Tight Line LLC
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """Keeping data values out of engine messages (decisions 54 and 139).
5
+
6
+ Engine messages quote object names (tables, columns, constraints, roles,
7
+ files) far more often than data values, and an error that names the object
8
+ is the one worth reading. Each engine adapter builds a :class:`Redactor` from
9
+ two lists: the message shapes its engine uses to report data values, whose
10
+ values are hidden, and the words that say a quoted string names an object
11
+ (``table "orders"``, ``constraint 'pk_orders'``), which is kept. Any other
12
+ quoted string is hidden too, so a message nobody has classified stays as
13
+ safe as before. A message a user raised (a trigger's or procedure's own
14
+ error) can quote anything, so every quoted string in it is hidden.
15
+ """
16
+
17
+ import re
18
+ from collections.abc import Sequence
19
+
20
+ __all__ = ["MASK", "Redactor", "kinds"]
21
+
22
+ MASK = "…"
23
+ """What a hidden value becomes."""
24
+
25
+
26
+ def _string(mark: str) -> str:
27
+ """A pattern for one string between ``mark``s.
28
+
29
+ A mark followed by a letter or digit belongs to the string (``'O'Brien'``),
30
+ so a value holding the mark is hidden whole rather than cut short.
31
+ """
32
+ q = re.escape(mark)
33
+ return rf"{q}(?:[^{q}]|{q}(?=\w))*{q}"
34
+
35
+
36
+ def kinds(words: str) -> str:
37
+ """A pattern for any of the space-separated ``words`` and the space after it.
38
+
39
+ Before a quoted string, it says the string names an object: ``table "orders"``.
40
+ """
41
+ return rf"\b(?:{'|'.join(words.split())})\s+"
42
+
43
+
44
+ # Introducers that may open a string literal: N'…', E'…', X'…', Oracle's
45
+ # q'[…]' and nq'…', MySQL's _utf8mb4'…'.
46
+ _PREFIX = r"(?<!\w)(?P<prefix>[nebxq]|nq|_\w+)"
47
+
48
+
49
+ def _hide(match: re.Match[str]) -> str:
50
+ start, end = match.span("value")
51
+ whole = match.group(0)
52
+ offset = match.start()
53
+ return f"{whole[: start - offset]}{MASK}{whole[end - offset :]}"
54
+
55
+
56
+ def _hide_spanning(text: str, line: re.Pattern[str], spanning: re.Pattern[str]) -> str:
57
+ """``text`` with the values only ``spanning`` finds, those running over a line break, hidden.
58
+
59
+ Where ``line`` matches at the same place, the value was on one line and is
60
+ already hidden, so the greedy ``spanning`` match, which may run on into
61
+ later lines, is passed over.
62
+ """
63
+ position = 0
64
+ while (match := spanning.search(text, position)) is not None:
65
+ if line.match(text, match.start()):
66
+ position = match.start() + 1
67
+ continue
68
+ hidden = _hide(match)
69
+ text = f"{text[: match.start()]}{hidden}{text[match.end() :]}"
70
+ position = match.start() + len(hidden)
71
+ return text
72
+
73
+
74
+ class Redactor:
75
+ """Hides the data values in an engine's messages and keeps the object names.
76
+
77
+ ``values`` are the shapes that report data values, each a pattern whose
78
+ ``value`` group, written ``(?P<value>.*)`` or narrower, is hidden. Patterns
79
+ ignore case and match within a line, greedily, so a value holding its own
80
+ quote mark is hidden whole up to the text that follows it
81
+ (``'(?P<value>.*)' for key``). A value that runs over a line break is
82
+ then found by the same pattern spanning lines, greedily to its last
83
+ closing text, so no part of it is left.
84
+ ``names`` are patterns that, right before a quoted string, say it names an
85
+ object (see :func:`kinds`). ``raised`` are patterns that mark a message a
86
+ user raised, in which every quoted string is hidden. ``marks`` are the
87
+ quote characters the engine uses for strings; identifiers in other marks
88
+ (backticks, brackets, Oracle's double quotes) are never touched.
89
+ """
90
+
91
+ def __init__(
92
+ self,
93
+ *,
94
+ values: Sequence[str],
95
+ names: Sequence[str],
96
+ marks: str,
97
+ raised: Sequence[str] = (),
98
+ ) -> None:
99
+ """Compile the engine's lists."""
100
+ self.values = tuple(re.compile(value, re.IGNORECASE) for value in values)
101
+ self.spanning = tuple(re.compile(value, re.IGNORECASE | re.DOTALL) for value in values)
102
+ self.raised = re.compile("|".join(raised) or "(?!)")
103
+ strings = "|".join(_string(mark) for mark in marks)
104
+ self.strings = re.compile(
105
+ rf"(?P<name>{'|'.join(names) or '(?!)'})?(?:{_PREFIX}|(?<!\w))(?P<string>{strings})",
106
+ re.IGNORECASE,
107
+ )
108
+
109
+ def raises(self, text: str) -> bool:
110
+ """Whether ``text`` carries the mark of a message a user raised."""
111
+ return self.raised.search(text) is not None
112
+
113
+ def __call__(self, text: str, *, raised: bool = False) -> str:
114
+ """``text`` with data values, and quoted strings that name nothing, replaced by ``…``.
115
+
116
+ When ``raised`` is true, or ``text`` shows it (:meth:`raises`), every
117
+ quoted string is replaced, named or not.
118
+ """
119
+ for shape in self.values:
120
+ text = shape.sub(_hide, text)
121
+ for line, spanning in zip(self.values, self.spanning, strict=True):
122
+ text = _hide_spanning(text, line, spanning)
123
+ everything = raised or self.raises(text)
124
+
125
+ def replace(match: re.Match[str]) -> str:
126
+ if match.group("name") is not None and not everything:
127
+ return match.group(0)
128
+ mark = match.group("string")[0]
129
+ return f"{match.group('name') or ''}{match.group('prefix') or ''}{mark}{MASK}{mark}"
130
+
131
+ return self.strings.sub(replace, text)