datadouble 0.0.4__tar.gz → 0.0.6__tar.gz

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.
Files changed (94) hide show
  1. {datadouble-0.0.4 → datadouble-0.0.6}/PKG-INFO +1 -1
  2. {datadouble-0.0.4 → datadouble-0.0.6}/pyproject.toml +16 -4
  3. datadouble-0.0.6/src/datadouble/anonymize.py +445 -0
  4. {datadouble-0.0.4 → datadouble-0.0.6}/src/datadouble/api.py +179 -20
  5. {datadouble-0.0.4 → datadouble-0.0.6}/src/datadouble/catalog.py +38 -10
  6. {datadouble-0.0.4 → datadouble-0.0.6}/src/datadouble/ci.py +44 -0
  7. {datadouble-0.0.4 → datadouble-0.0.6}/src/datadouble/cli.py +127 -4
  8. datadouble-0.0.6/src/datadouble/discover.py +1402 -0
  9. {datadouble-0.0.4 → datadouble-0.0.6}/src/datadouble/engine.py +219 -12
  10. datadouble-0.0.6/src/datadouble/files.py +247 -0
  11. {datadouble-0.0.4 → datadouble-0.0.6}/src/datadouble/images.py +4 -1
  12. {datadouble-0.0.4 → datadouble-0.0.6}/src/datadouble/jailer.py +14 -8
  13. datadouble-0.0.6/src/datadouble/jsonpath.py +183 -0
  14. datadouble-0.0.6/src/datadouble/locales/__init__.py +56 -0
  15. datadouble-0.0.6/src/datadouble/locales/base.py +310 -0
  16. datadouble-0.0.6/src/datadouble/locales/data/first_names.txt +4000 -0
  17. datadouble-0.0.6/src/datadouble/locales/data/sources.txt +5 -0
  18. datadouble-0.0.6/src/datadouble/locales/data/streets.txt +2000 -0
  19. datadouble-0.0.6/src/datadouble/locales/data/surnames.txt +6000 -0
  20. datadouble-0.0.6/src/datadouble/locales/gb.py +218 -0
  21. datadouble-0.0.6/src/datadouble/locales/us.py +111 -0
  22. datadouble-0.0.6/src/datadouble/locales/vocabulary.py +59 -0
  23. datadouble-0.0.6/src/datadouble/pii.py +518 -0
  24. {datadouble-0.0.4 → datadouble-0.0.6}/src/datadouble/planner.py +139 -10
  25. datadouble-0.0.6/src/datadouble/progress.py +277 -0
  26. {datadouble-0.0.4 → datadouble-0.0.6}/src/datadouble/prune.py +51 -14
  27. {datadouble-0.0.4 → datadouble-0.0.6}/src/datadouble/redaction.py +42 -2
  28. {datadouble-0.0.4 → datadouble-0.0.6}/src/datadouble/replicate.py +4 -0
  29. {datadouble-0.0.4 → datadouble-0.0.6}/src/datadouble/run.py +112 -14
  30. {datadouble-0.0.4 → datadouble-0.0.6}/src/datadouble/spec.py +246 -20
  31. {datadouble-0.0.4 → datadouble-0.0.6}/src/datadouble/strict.py +11 -5
  32. {datadouble-0.0.4 → datadouble-0.0.6}/src/datadouble/verify.py +86 -30
  33. {datadouble-0.0.4 → datadouble-0.0.6}/tests/fake_engine.py +44 -5
  34. datadouble-0.0.6/tests/test_anonymize_pii.py +546 -0
  35. {datadouble-0.0.4 → datadouble-0.0.6}/tests/test_catalog.py +32 -0
  36. {datadouble-0.0.4 → datadouble-0.0.6}/tests/test_ci.py +69 -8
  37. {datadouble-0.0.4 → datadouble-0.0.6}/tests/test_commands.py +69 -4
  38. datadouble-0.0.6/tests/test_commands_operations.py +406 -0
  39. datadouble-0.0.6/tests/test_discover.py +1072 -0
  40. {datadouble-0.0.4 → datadouble-0.0.6}/tests/test_extends.py +43 -9
  41. datadouble-0.0.6/tests/test_files.py +281 -0
  42. {datadouble-0.0.4 → datadouble-0.0.6}/tests/test_jailer.py +7 -1
  43. datadouble-0.0.6/tests/test_jsonpath.py +209 -0
  44. datadouble-0.0.6/tests/test_locales.py +423 -0
  45. {datadouble-0.0.4 → datadouble-0.0.6}/tests/test_operations.py +10 -2
  46. {datadouble-0.0.4 → datadouble-0.0.6}/tests/test_planner.py +181 -0
  47. datadouble-0.0.6/tests/test_progress.py +187 -0
  48. {datadouble-0.0.4 → datadouble-0.0.6}/tests/test_redaction.py +19 -1
  49. {datadouble-0.0.4 → datadouble-0.0.6}/tests/test_run.py +205 -2
  50. {datadouble-0.0.4 → datadouble-0.0.6}/tests/test_spec.py +36 -2
  51. datadouble-0.0.6/tests/test_transform.py +97 -0
  52. datadouble-0.0.4/src/datadouble/anonymize.py +0 -165
  53. datadouble-0.0.4/src/datadouble/files.py +0 -78
  54. datadouble-0.0.4/src/datadouble/pii.py +0 -109
  55. datadouble-0.0.4/tests/test_anonymize_pii.py +0 -170
  56. datadouble-0.0.4/tests/test_commands_operations.py +0 -151
  57. datadouble-0.0.4/tests/test_files.py +0 -60
  58. {datadouble-0.0.4 → datadouble-0.0.6}/.gitignore +0 -0
  59. {datadouble-0.0.4 → datadouble-0.0.6}/LICENSE +0 -0
  60. {datadouble-0.0.4 → datadouble-0.0.6}/README.md +0 -0
  61. {datadouble-0.0.4 → datadouble-0.0.6}/src/datadouble/__init__.py +0 -0
  62. {datadouble-0.0.4 → datadouble-0.0.6}/src/datadouble/announce.py +0 -0
  63. {datadouble-0.0.4 → datadouble-0.0.6}/src/datadouble/boundary.py +0 -0
  64. {datadouble-0.0.4 → datadouble-0.0.6}/src/datadouble/channels.py +0 -0
  65. {datadouble-0.0.4 → datadouble-0.0.6}/src/datadouble/closure.py +0 -0
  66. {datadouble-0.0.4 → datadouble-0.0.6}/src/datadouble/names.py +0 -0
  67. {datadouble-0.0.4 → datadouble-0.0.6}/src/datadouble/notify.py +0 -0
  68. {datadouble-0.0.4 → datadouble-0.0.6}/src/datadouble/objects.py +0 -0
  69. {datadouble-0.0.4 → datadouble-0.0.6}/src/datadouble/outcome.py +0 -0
  70. {datadouble-0.0.4 → datadouble-0.0.6}/src/datadouble/programs.py +0 -0
  71. {datadouble-0.0.4 → datadouble-0.0.6}/src/datadouble/promote.py +0 -0
  72. {datadouble-0.0.4 → datadouble-0.0.6}/src/datadouble/py.typed +0 -0
  73. {datadouble-0.0.4 → datadouble-0.0.6}/src/datadouble/registry.py +0 -0
  74. {datadouble-0.0.4 → datadouble-0.0.6}/src/datadouble/resolve.py +0 -0
  75. {datadouble-0.0.4 → datadouble-0.0.6}/src/datadouble/runtime.py +0 -0
  76. {datadouble-0.0.4 → datadouble-0.0.6}/src/datadouble/secrets.py +0 -0
  77. {datadouble-0.0.4 → datadouble-0.0.6}/src/datadouble/settings.py +0 -0
  78. {datadouble-0.0.4 → datadouble-0.0.6}/src/datadouble/signing.py +0 -0
  79. {datadouble-0.0.4 → datadouble-0.0.6}/src/datadouble/staging.py +0 -0
  80. {datadouble-0.0.4 → datadouble-0.0.6}/src/datadouble/storage.py +0 -0
  81. {datadouble-0.0.4 → datadouble-0.0.6}/src/datadouble/subset.py +0 -0
  82. {datadouble-0.0.4 → datadouble-0.0.6}/src/datadouble/versions.py +0 -0
  83. {datadouble-0.0.4 → datadouble-0.0.6}/tests/conftest.py +0 -0
  84. {datadouble-0.0.4 → datadouble-0.0.6}/tests/fakes.py +0 -0
  85. {datadouble-0.0.4 → datadouble-0.0.6}/tests/test_api.py +0 -0
  86. {datadouble-0.0.4 → datadouble-0.0.6}/tests/test_cli.py +0 -0
  87. {datadouble-0.0.4 → datadouble-0.0.6}/tests/test_closure.py +0 -0
  88. {datadouble-0.0.4 → datadouble-0.0.6}/tests/test_notify.py +0 -0
  89. {datadouble-0.0.4 → datadouble-0.0.6}/tests/test_objects.py +0 -0
  90. {datadouble-0.0.4 → datadouble-0.0.6}/tests/test_programs.py +0 -0
  91. {datadouble-0.0.4 → datadouble-0.0.6}/tests/test_resolve_strict.py +0 -0
  92. {datadouble-0.0.4 → datadouble-0.0.6}/tests/test_runtime.py +0 -0
  93. {datadouble-0.0.4 → datadouble-0.0.6}/tests/test_storage_images.py +0 -0
  94. {datadouble-0.0.4 → datadouble-0.0.6}/tests/test_subset.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: datadouble
3
- Version: 0.0.4
3
+ Version: 0.0.6
4
4
  Summary: Realistic, safe copies of production data for development and testing
5
5
  Project-URL: Homepage, https://datadouble.tightlinesoftware.com/
6
6
  Project-URL: Source, https://github.com/datadouble/datadouble
@@ -3,9 +3,8 @@
3
3
 
4
4
  [project]
5
5
  name = "datadouble"
6
- # All packages share one version until 1.0 (decision 38); scripts/make_tag.py
7
- # sets it at release time.
8
- version = "0.0.4"
6
+ # Every package takes its version from the release tag (decision 165).
7
+ dynamic = ["version"]
9
8
  description = "Realistic, safe copies of production data for development and testing"
10
9
  readme = "README.md"
11
10
  license = "MIT"
@@ -46,8 +45,21 @@ dotenv = "datadouble.announce:dotenv_announcer"
46
45
  ci-outputs = "datadouble.announce:ci_outputs_announcer"
47
46
 
48
47
  [build-system]
49
- requires = ["hatchling>=1.33.0"]
48
+ requires = ["hatchling>=1.33.0", "hatch-vcs>=0.5.0"]
50
49
  build-backend = "hatchling.build"
51
50
 
51
+ # The version comes from `git describe`: the tag's on a tagged commit, and a
52
+ # development version such as 0.0.5.dev3+gabc1234 anywhere else. A build with
53
+ # no Git history (a Docker build) gets 0.0.0.dev0 unless the build sets
54
+ # SETUPTOOLS_SCM_PRETEND_VERSION.
55
+ [tool.hatch.version]
56
+ source = "vcs"
57
+ fallback-version = "0.0.0.dev0"
58
+ raw-options = { search_parent_directories = true }
59
+
60
+ # Reinstall when the commit or tags change, so the installed version follows.
61
+ [tool.uv]
62
+ cache-keys = [{ file = "pyproject.toml" }, { git = { commit = true, tags = true } }]
63
+
52
64
  [tool.hatch.build.targets.wheel]
53
65
  packages = ["src/datadouble"]
@@ -0,0 +1,445 @@
1
+ # Copyright (c) 2026- Tight Line LLC
2
+ # SPDX-License-Identifier: MIT
3
+
4
+ """Replacement values for the strategies that work value by value.
5
+
6
+ Faker, hash, format-preserving, scrub and paths rules map each distinct
7
+ original value to a replacement here, in the Datadouble process; the engine adapter then applies
8
+ the mapping in one native update per table. Every replacement is keyed by the
9
+ run's anonymization key, so the same input gets the same output in every
10
+ table and every image group of a build, and nothing about the original can be
11
+ recovered without the key.
12
+
13
+ A faker value is seeded from the input after normalizing it for its kind, so
14
+ ``Alice@Example.com`` and ``alice@example.com`` get the same fake email, and
15
+ ``(217) 555-1234`` and ``2175551234`` the same fake phone number. The fake is
16
+ then shaped like the input: upper case for upper case, lower case for lower
17
+ case, and a ten-digit phone number keeps its layout.
18
+
19
+ Generated emails, URLs, phone numbers, national identifiers and IP
20
+ addresses use reserved example domains, fictional ranges and documentation
21
+ ranges, so the PII scan does not mistake them for real data. Names and
22
+ street addresses come from a fictional vocabulary, for the same reason.
23
+ Phone numbers, national identifiers, IBANs and street suffixes come from a
24
+ locale pack: the first one the spec names, unless a rule names another.
25
+ """
26
+
27
+ import hashlib
28
+ import hmac
29
+ import re
30
+ import secrets
31
+ from collections.abc import Callable, Iterable
32
+ from functools import partial
33
+ from typing import TYPE_CHECKING, assert_never
34
+
35
+ from faker import Faker
36
+
37
+ from datadouble.catalog import ColumnKind
38
+ from datadouble.jsonpath import (
39
+ DuplicateMemberError,
40
+ Json,
41
+ dumps,
42
+ loads,
43
+ number,
44
+ parse_path,
45
+ rewrite,
46
+ )
47
+ from datadouble.locales import PACKS, Pack, Phones, packs
48
+ from datadouble.locales.vocabulary import Words
49
+ from datadouble.pii import Detectors
50
+ from datadouble.spec import (
51
+ FakerKind,
52
+ FakerRule,
53
+ FormatPreservingRule,
54
+ HashRule,
55
+ Locale,
56
+ NullRule,
57
+ PathRule,
58
+ PathsRule,
59
+ ScrubKind,
60
+ ScrubRule,
61
+ )
62
+
63
+ if TYPE_CHECKING:
64
+ import random
65
+
66
+ _MAX_ATTEMPTS = 100
67
+ _INT32_MAX = 2**31 - 1
68
+ _LUHN_CARRY = 9
69
+ _PHONE_PUNCTUATION = frozenset("+()-. ")
70
+ _WHITESPACE = re.compile(r"\s+")
71
+ _CASEFOLDED = frozenset(
72
+ {
73
+ FakerKind.FIRST_NAME,
74
+ FakerKind.LAST_NAME,
75
+ FakerKind.NAME,
76
+ FakerKind.USER_NAME,
77
+ FakerKind.STREET_ADDRESS,
78
+ FakerKind.CITY,
79
+ FakerKind.POSTCODE,
80
+ FakerKind.COMPANY,
81
+ }
82
+ )
83
+ """Kinds whose values are equal when they differ only in case and spacing."""
84
+ _CODES = frozenset({FakerKind.NATIONAL_ID, FakerKind.IBAN})
85
+ """Kinds written in groups, whose values are equal without their spaces and dashes."""
86
+ _CODE_SEPARATORS = re.compile(r"[\s-]+")
87
+ _CASED = _CASEFOLDED | _CODES | {FakerKind.EMAIL}
88
+ """Kinds whose fakes follow the input's case."""
89
+ _EMAIL_IN_TEXT = re.compile(r"(?<![A-Za-z0-9._%+-])[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+[.][A-Za-z]{2,}")
90
+ """An email. The lookbehind starts a match only where a local part starts,
91
+ which keeps long runs of text without an ``@`` from taking quadratic time."""
92
+
93
+
94
+ class AnonymizeError(Exception):
95
+ """Replacement values that cannot be generated as the rules require."""
96
+
97
+
98
+ type ValueRule = FakerRule | HashRule | FormatPreservingRule | ScrubRule | PathsRule
99
+ """Rules whose replacements are computed here, value by value."""
100
+
101
+
102
+ def new_key() -> bytes:
103
+ """A random anonymization key, for runs whose spec does not supply one."""
104
+ return secrets.token_bytes(32)
105
+
106
+
107
+ class Anonymizer:
108
+ """Computes replacements under one anonymization key."""
109
+
110
+ def __init__(self, key: bytes, locales: Iterable[Locale] = (Locale.US,)) -> None:
111
+ """Use ``key`` for every replacement, and the packs for ``locales``.
112
+
113
+ Fakes come from the first pack unless a rule names another. Scrubbing
114
+ finds the phone numbers of every pack, and hashes avoid anything the
115
+ packs' detectors would flag.
116
+ """
117
+ self._key = key
118
+ self._locales = tuple(locales)
119
+ self._detectors = Detectors(packs(self._locales))
120
+ self._fakers: dict[str, Faker] = {}
121
+
122
+ def _digest(self, *parts: str) -> bytes:
123
+ message = "\x1f".join(parts).encode()
124
+ return hmac.new(self._key, message, hashlib.sha256).digest()
125
+
126
+ def _seed(self, *parts: str) -> int:
127
+ return int.from_bytes(self._digest(*parts)[:8], "big")
128
+
129
+ def fake(
130
+ self, kind: FakerKind, value: str, attempt: int = 0, locale: Locale | None = None
131
+ ) -> str:
132
+ """A fake value of ``kind`` for ``value``; ``attempt`` varies it on collisions.
133
+
134
+ The fake comes from the pack for ``locale``, or the first pack. Inputs
135
+ that normalize alike get the same fake, shaped like each input.
136
+ """
137
+ pack = PACKS[locale or self._locales[0]]
138
+ generated = self._generate(kind, normalized(kind, value, pack), attempt, pack)
139
+ return shaped(kind, value, generated, pack)
140
+
141
+ def _faker(self, pack: Pack) -> Faker:
142
+ if pack.faker_locale not in self._fakers:
143
+ self._fakers[pack.faker_locale] = Faker(pack.faker_locale)
144
+ return self._fakers[pack.faker_locale]
145
+
146
+ def _generate(self, kind: FakerKind, key: str, attempt: int, pack: Pack) -> str:
147
+ fake = self._faker(pack)
148
+ fake.seed_instance(self._seed("faker", kind, str(attempt), key))
149
+ rng: random.Random = fake.random
150
+
151
+ def pick(name: Words) -> str:
152
+ return rng.choice(pack.vocabulary.words(name))
153
+
154
+ def user_name() -> str:
155
+ return f"{pick(Words.FIRST_NAMES)}.{pick(Words.SURNAMES)}".lower()
156
+
157
+ generators: dict[FakerKind, Callable[[], str]] = {
158
+ FakerKind.FIRST_NAME: lambda: pick(Words.FIRST_NAMES),
159
+ FakerKind.LAST_NAME: lambda: pick(Words.SURNAMES),
160
+ FakerKind.NAME: lambda: f"{pick(Words.FIRST_NAMES)} {pick(Words.SURNAMES)}",
161
+ FakerKind.EMAIL: lambda: f"{user_name()}@{fake.safe_domain_name()}",
162
+ FakerKind.USER_NAME: user_name,
163
+ FakerKind.PHONE_NUMBER: lambda: pack.phones.fake(rng),
164
+ FakerKind.STREET_ADDRESS: lambda: (
165
+ f"{rng.choice(pack.house_numbers)} {pick(Words.STREETS)}"
166
+ f" {rng.choice(pack.street_suffixes)}"
167
+ ),
168
+ FakerKind.CITY: fake.city,
169
+ FakerKind.POSTCODE: fake.postcode,
170
+ FakerKind.COMPANY: fake.company,
171
+ FakerKind.IPV4: lambda: f"192.0.2.{fake.random_int(1, 254)}",
172
+ FakerKind.URL: lambda: f"https://{fake.safe_domain_name()}/{fake.slug()}",
173
+ FakerKind.TEXT: lambda: fake.sentence(nb_words=8),
174
+ FakerKind.DATE_OF_BIRTH: lambda: fake.date_of_birth(
175
+ minimum_age=18, maximum_age=90
176
+ ).isoformat(),
177
+ FakerKind.NATIONAL_ID: lambda: pack.national_id(rng),
178
+ }
179
+ if pack.iban is not None:
180
+ generators[FakerKind.IBAN] = partial(pack.iban, rng)
181
+ generator = generators.get(kind)
182
+ if generator is None:
183
+ message = f"the {pack.name} locale pack has no {kind} fakes; name a pack that does"
184
+ raise AnonymizeError(message)
185
+ return generator()
186
+
187
+ def hash(self, value: str, length: int, kind: ColumnKind, attempt: int = 0) -> str:
188
+ """A keyed hash of ``value``: hex text, or a non-negative 32-bit integer."""
189
+ digest = self._digest("hash", str(attempt), value)
190
+ if kind is ColumnKind.INTEGER:
191
+ return str(int.from_bytes(digest, "big") % _INT32_MAX)
192
+ return digest.hex()[:length]
193
+
194
+ def preserve_format(self, value: str, *, luhn: bool, attempt: int = 0) -> str:
195
+ """Replace digits with digits and letters with letters of the same case."""
196
+ stream = self._digest("format", str(attempt), value)
197
+ while len(stream) < len(value):
198
+ stream += hashlib.sha256(stream).digest()
199
+ out: list[str] = []
200
+ for char, byte in zip(value, stream, strict=False):
201
+ if char.isascii() and char.isdigit():
202
+ out.append(str(byte % 10))
203
+ elif char.isascii() and char.isalpha():
204
+ base = ord("a") if char.islower() else ord("A")
205
+ out.append(chr(base + byte % 26))
206
+ else:
207
+ out.append(char)
208
+ result = "".join(out)
209
+ return _with_luhn_check(result) if luhn else result
210
+
211
+ def replacement(self, rule: ValueRule, kind: ColumnKind, value: str, attempt: int) -> str:
212
+ """The replacement ``rule`` gives ``value`` on a given attempt."""
213
+ match rule:
214
+ case FakerRule():
215
+ return self.fake(rule.faker, value, attempt, rule.locale)
216
+ case HashRule():
217
+ return self.hash(value, rule.hash.length, kind, attempt)
218
+ case FormatPreservingRule():
219
+ luhn = rule.format_preserving.luhn
220
+ return self.preserve_format(value, luhn=luhn, attempt=attempt)
221
+ case ScrubRule():
222
+ return self.scrub(rule.scrub, value)
223
+ case PathsRule():
224
+ return self.rewrite_json(rule, value)
225
+ case _:
226
+ assert_never(rule)
227
+
228
+ def scrub(self, kinds: Iterable[ScrubKind], value: str) -> str:
229
+ """``value`` with each email or phone number of ``kinds`` replaced by its fake.
230
+
231
+ Emails go first, so the digits of an address are replaced with it.
232
+ Phone numbers are found in every pack's formats; where two packs'
233
+ matches overlap, the one that starts first wins, then the longer, and
234
+ it gets a fake from its own pack.
235
+ """
236
+ wanted = frozenset(kinds)
237
+ if ScrubKind.EMAIL in wanted:
238
+ value = _EMAIL_IN_TEXT.sub(lambda found: self.fake(FakerKind.EMAIL, found[0]), value)
239
+ if ScrubKind.PHONE_NUMBER in wanted:
240
+ value = self._scrub_phones(value)
241
+ return value
242
+
243
+ def _scrub_phones(self, value: str) -> str:
244
+ found = sorted(
245
+ (
246
+ (match.start(), -match.end(), match[0], locale)
247
+ for locale in self._locales
248
+ for match in PACKS[locale].phones.scrub.finditer(value)
249
+ ),
250
+ key=lambda item: item[:2],
251
+ )
252
+ out: list[str] = []
253
+ done = 0
254
+ for start, end, text, locale in found:
255
+ if start < done:
256
+ continue
257
+ out.extend((value[done:start], self.fake(FakerKind.PHONE_NUMBER, text, locale=locale)))
258
+ done = -end
259
+ out.append(value[done:])
260
+ return "".join(out)
261
+
262
+ def rewrite_json(self, rule: PathsRule, value: str) -> str:
263
+ """``value`` with each path's values replaced; text that is not JSON stays as it is.
264
+
265
+ A document no path changes keeps its exact text. One that changes is
266
+ written with standard spacing, its numbers as they were.
267
+ """
268
+ try:
269
+ document = loads(value)
270
+ except DuplicateMemberError:
271
+ message = (
272
+ "a JSON document names the same member twice, so a path could miss one of "
273
+ "its values; use null on the column, or clean the duplicates at the source"
274
+ )
275
+ raise AnonymizeError(message) from None
276
+ except ValueError:
277
+ return value
278
+ before = dumps(document)
279
+ after = dumps(self._rewrite_document(rule, document))
280
+ return value if after == before else after
281
+
282
+ def _rewrite_document(self, rule: PathsRule, document: Json) -> Json:
283
+ for path, inner in rule.paths.items():
284
+ document = rewrite(document, parse_path(path), partial(self._at, path, inner))
285
+ return document
286
+
287
+ def _at(self, path: str, rule: PathRule, found: Json) -> Json:
288
+ """What ``rule`` makes of the value ``path`` found."""
289
+ if isinstance(rule, NullRule):
290
+ return None
291
+ if found is None or isinstance(found, bool):
292
+ return found
293
+ if isinstance(rule, PathsRule):
294
+ return self._nested(rule, found)
295
+ if isinstance(found, dict | list):
296
+ held = "an object" if isinstance(found, dict) else "an array"
297
+ message = (
298
+ f"JSON path {path} holds {held}; give a path to the values inside it, or use null"
299
+ )
300
+ raise AnonymizeError(message)
301
+ if isinstance(found, str):
302
+ return self._clean(rule, ColumnKind.TEXT, found)
303
+ integer = isinstance(found, int)
304
+ text = str(found) if isinstance(found, int) else found.text
305
+ kind = ColumnKind.INTEGER if integer else ColumnKind.TEXT
306
+ return number(self._clean(rule, kind, text), integer=integer)
307
+
308
+ def _clean(self, rule: ValueRule, kind: ColumnKind, value: str) -> str:
309
+ """The first replacement the PII scan passes, as ``mapping`` makes for hashes."""
310
+ attempt = 0
311
+ replacement = self.replacement(rule, kind, value, attempt)
312
+ while isinstance(rule, HashRule) and self._unsafe_hash(replacement):
313
+ attempt += 1
314
+ replacement = self.replacement(rule, kind, value, attempt)
315
+ return replacement
316
+
317
+ def _nested(self, rule: PathsRule, found: Json) -> Json:
318
+ """A ``paths`` rule inside another: on a string holding JSON, or on an object or array."""
319
+ if isinstance(found, str):
320
+ return self.rewrite_json(rule, found)
321
+ if isinstance(found, dict | list):
322
+ return self._rewrite_document(rule, found)
323
+ return found
324
+
325
+ def _unsafe_hash(self, replacement: str) -> bool:
326
+ """Whether a hash needs another attempt.
327
+
328
+ A hash is meant to look like nothing, but hex text can hold a digit
329
+ run the PII scan reads as a card number, or letters that read as an
330
+ IBAN. Hex text without a digit could also be read as a name, which
331
+ the scan only accepts from the fakes' vocabulary.
332
+ """
333
+ return bool(self._detectors.detect(replacement)) or not any(
334
+ char.isdigit() for char in replacement
335
+ )
336
+
337
+ def mapping(
338
+ self, rule: ValueRule, kind: ColumnKind, values: Iterable[str], *, unique: bool
339
+ ) -> dict[str, str]:
340
+ """Replacements for distinct ``values``; with ``unique``, no two share one."""
341
+ result: dict[str, str] = {}
342
+ taken: set[str] = set()
343
+ for value in sorted(set(values)):
344
+ for attempt in range(_MAX_ATTEMPTS):
345
+ replacement = self.replacement(rule, kind, value, attempt)
346
+ if isinstance(rule, HashRule) and self._unsafe_hash(replacement):
347
+ continue
348
+ if not unique or replacement not in taken:
349
+ break
350
+ else:
351
+ message = (
352
+ f"could not find a unique replacement after {_MAX_ATTEMPTS} attempts; "
353
+ "the rule produces too few distinct values for this column"
354
+ )
355
+ raise AnonymizeError(message)
356
+ taken.add(replacement)
357
+ result[value] = replacement
358
+ return result
359
+
360
+
361
+ def normalized(kind: FakerKind, value: str, pack: Pack) -> str:
362
+ """The form of ``value`` a fake of ``kind`` is seeded from.
363
+
364
+ Emails are trimmed and case-folded. Phone numbers keep their digits, less
365
+ the country code or trunk prefix of the pack's numbering plan. National
366
+ identifiers and IBANs lose their spaces and dashes and are case-folded.
367
+ Names, addresses and companies are trimmed, case-folded and have their
368
+ spacing collapsed. Other kinds use the value as it is.
369
+ """
370
+ if kind is FakerKind.EMAIL:
371
+ return value.strip().casefold()
372
+ if kind is FakerKind.PHONE_NUMBER:
373
+ digits = _digits(value)
374
+ return pack.phones.national(digits) or digits or value.strip().casefold()
375
+ if kind in _CODES:
376
+ return _CODE_SEPARATORS.sub("", value).casefold()
377
+ if kind in _CASEFOLDED:
378
+ return _WHITESPACE.sub(" ", value.strip()).casefold()
379
+ return value
380
+
381
+
382
+ def shaped(kind: FakerKind, value: str, fake: str, pack: Pack) -> str:
383
+ """``fake`` in the shape of ``value``: its case, a phone number's layout, a code's spacing."""
384
+ if kind is FakerKind.PHONE_NUMBER:
385
+ return _phone_layout(value, fake, pack.phones)
386
+ if kind in _CODES and not _CODE_SEPARATORS.search(value.strip()):
387
+ fake = _CODE_SEPARATORS.sub("", fake)
388
+ if kind in _CASED:
389
+ letters = [char for char in value if char.isalpha() and char.lower() != char.upper()]
390
+ if letters and all(char.isupper() for char in letters):
391
+ return fake.upper()
392
+ if letters and all(char.islower() for char in letters):
393
+ return fake.lower()
394
+ return fake
395
+
396
+
397
+ def _digits(value: str) -> str:
398
+ return "".join(char for char in value if char.isascii() and char.isdigit())
399
+
400
+
401
+ def _phone_layout(value: str, fake: str, phones: Phones) -> str:
402
+ """The fake's national digits in the input's places, when the input is only a phone number.
403
+
404
+ The input must be a national number of the pack's plan, alone or after
405
+ its country code or trunk prefix, with nothing but ``+``, parentheses,
406
+ ``-``, ``.`` and spaces between the digits. The prefix stays as written.
407
+ Anything else, such as a name beside the number, gets the generated fake
408
+ whole.
409
+ """
410
+ if any(
411
+ not (char.isascii() and char.isdigit()) and char not in _PHONE_PUNCTUATION for char in value
412
+ ):
413
+ return fake
414
+ digits = _digits(value)
415
+ if phones.national(digits) is None:
416
+ return fake
417
+ skip = len(digits) - phones.digits
418
+ replacements = iter(_digits(fake)[-phones.digits :])
419
+ out: list[str] = []
420
+ for char in value:
421
+ if char.isascii() and char.isdigit():
422
+ if skip:
423
+ skip -= 1
424
+ out.append(char)
425
+ else:
426
+ out.append(next(replacements))
427
+ else:
428
+ out.append(char)
429
+ return "".join(out)
430
+
431
+
432
+ def _with_luhn_check(digits_and_more: str) -> str:
433
+ """Set the last digit so the digits pass the Luhn check, as card numbers do."""
434
+ positions = [i for i, c in enumerate(digits_and_more) if c.isascii() and c.isdigit()]
435
+ if not positions:
436
+ return digits_and_more
437
+ digits = [int(digits_and_more[i]) for i in positions[:-1]]
438
+ total = 0
439
+ for index, digit in enumerate(reversed(digits)):
440
+ doubled = digit * 2 if index % 2 == 0 else digit
441
+ total += doubled - _LUHN_CARRY if doubled > _LUHN_CARRY else doubled
442
+ check = (10 - total % 10) % 10
443
+ chars = list(digits_and_more)
444
+ chars[positions[-1]] = str(check)
445
+ return "".join(chars)