map-conform 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.
Files changed (79) hide show
  1. map_conform/__init__.py +5 -0
  2. map_conform/__main__.py +7 -0
  3. map_conform/batch/__init__.py +1 -0
  4. map_conform/batch/arrow.py +80 -0
  5. map_conform/batch/columnar.py +125 -0
  6. map_conform/batch/engine.py +191 -0
  7. map_conform/batch/files.py +207 -0
  8. map_conform/cli.py +460 -0
  9. map_conform/doctor.py +178 -0
  10. map_conform/errors.py +107 -0
  11. map_conform/expr/__init__.py +6 -0
  12. map_conform/expr/compiler.py +562 -0
  13. map_conform/expr/functions.py +542 -0
  14. map_conform/expr/sandbox.py +333 -0
  15. map_conform/expr/sdk.py +116 -0
  16. map_conform/map-conform-spec.schema.json +1204 -0
  17. map_conform/mapper.py +355 -0
  18. map_conform/metadata.py +73 -0
  19. map_conform/metrics.py +62 -0
  20. map_conform/naming/__init__.py +1 -0
  21. map_conform/naming/ascii-table.json +980 -0
  22. map_conform/naming/conform.py +262 -0
  23. map_conform/naming/flatten.py +148 -0
  24. map_conform/naming/nested.py +117 -0
  25. map_conform/naming/reserved/ansi.txt +369 -0
  26. map_conform/naming/reserved/duckdb.txt +114 -0
  27. map_conform/naming/reserved/postgres.txt +105 -0
  28. map_conform/naming/reserved/snowflake.txt +90 -0
  29. map_conform/naming/reserved.py +34 -0
  30. map_conform/naming/shape.py +96 -0
  31. map_conform/naming/streams.py +76 -0
  32. map_conform/naming/translit.py +170 -0
  33. map_conform/plan/__init__.py +1 -0
  34. map_conform/plan/chain.py +667 -0
  35. map_conform/plan/compile.py +551 -0
  36. map_conform/plan/lower.py +281 -0
  37. map_conform/plan/ops.py +336 -0
  38. map_conform/plan/row.py +212 -0
  39. map_conform/plan/vector.py +71 -0
  40. map_conform/rejects.py +92 -0
  41. map_conform/settings.py +157 -0
  42. map_conform/spec/__init__.py +1 -0
  43. map_conform/spec/_struct.py +483 -0
  44. map_conform/spec/bridge.py +109 -0
  45. map_conform/spec/check.py +380 -0
  46. map_conform/spec/errors.py +22 -0
  47. map_conform/spec/importer.py +87 -0
  48. map_conform/spec/jsonschema.py +54 -0
  49. map_conform/spec/load.py +357 -0
  50. map_conform/spec/model.py +473 -0
  51. map_conform/spec/reference.py +179 -0
  52. map_conform/spec/steps.py +297 -0
  53. map_conform/spec/stream_maps.py +233 -0
  54. map_conform/spec/zamboni.py +99 -0
  55. map_conform/transforms/__init__.py +1 -0
  56. map_conform/transforms/builtins.py +63 -0
  57. map_conform/transforms/casts.py +310 -0
  58. map_conform/transforms/fake.py +150 -0
  59. map_conform/transforms/nested.py +111 -0
  60. map_conform/transforms/numeric.py +318 -0
  61. map_conform/transforms/polars_vector.py +151 -0
  62. map_conform/transforms/privacy.py +220 -0
  63. map_conform/transforms/registry.py +116 -0
  64. map_conform/transforms/temporal.py +410 -0
  65. map_conform/transforms/text.py +249 -0
  66. map_conform/transforms/vector.py +386 -0
  67. map_conform/types/__init__.py +1 -0
  68. map_conform/types/canonical.py +255 -0
  69. map_conform/types/from_jsonschema.py +177 -0
  70. map_conform/types/jsontext.py +63 -0
  71. map_conform/types/to_arrow.py +52 -0
  72. map_conform/types/to_jsonschema.py +65 -0
  73. map_conform/types/wire.py +53 -0
  74. map_conform/udfs.py +327 -0
  75. map_conform-0.1.0.dist-info/METADATA +157 -0
  76. map_conform-0.1.0.dist-info/RECORD +79 -0
  77. map_conform-0.1.0.dist-info/WHEEL +4 -0
  78. map_conform-0.1.0.dist-info/entry_points.txt +2 -0
  79. map_conform-0.1.0.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,262 @@
1
+ """Conform names so that every target accepts them (detailed design §5).
2
+
3
+ The pipeline is pure and deterministic, and each step follows the ``naming`` defaults:
4
+
5
+ 1. Unicode NFKC normalisation.
6
+ 2. ASCII: transliterate with the bundled table (ADR-0012), strip, or keep.
7
+ 3. Split camelCase and acronym boundaries (``customerID`` -> ``customer_ID``,
8
+ ``HTTPServer`` -> ``HTTP_Server``); a plural acronym stays whole (``IDs``).
9
+ 4. Apply the case.
10
+ 5. Replace characters outside the allowed set (``[a-z0-9_]`` for snake/lower).
11
+ 6. Collapse runs of ``_`` and trim it from both ends.
12
+ 7. A leading digit: prefix ``_``, turn it into a letter (SDK style) or fail.
13
+ 8. An empty result becomes ``col_<n>``, where n is the source ordinal.
14
+ 9. A reserved word of any configured dialect (case-insensitive): suffix ``_``, prefix ``_``,
15
+ fail, or ignore.
16
+ 10. Longer than ``max_length``: keep the head and add ``_`` plus 6 hex digits of the SHA-256
17
+ of the whole name, or fail.
18
+
19
+ Running the pipeline on its own output changes nothing. :meth:`NameConformer.conform_all`
20
+ also resolves names that collide under case folding within one stream or struct.
21
+
22
+ The ``sdk`` preset replaces the pipeline with the Singer SDK's SQL ``conform_name``, byte for
23
+ byte: drop everything but ASCII letters, digits, ``_``, ``-``, ``.`` and whitespace, lowercase,
24
+ trim, turn ``.``, ``-`` and spaces into ``_``, and turn a leading digit into a letter
25
+ (0 -> a). Nothing else is applied.
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ import hashlib
31
+ import re
32
+ import unicodedata
33
+ from dataclasses import dataclass, field
34
+ from typing import TYPE_CHECKING
35
+
36
+ from map_conform.naming.reserved import reserved_words
37
+ from map_conform.naming.translit import transliterate
38
+
39
+ if TYPE_CHECKING:
40
+ from collections.abc import Iterable, Sequence
41
+
42
+ from map_conform.spec.model import NamingDefaults
43
+
44
+ _CAMEL = re.compile(r"(?<=[a-z0-9])(?=[A-Z])")
45
+ # An acronym followed by a capitalised word splits before the word (HTTP_Server), but a
46
+ # plural acronym (IDs, URLs) stays whole.
47
+ _ACRONYM = re.compile(r"(?<=[A-Z])(?=[A-Z](?!s(?![a-z]))[a-z])")
48
+ _RUNS = re.compile(r"_+")
49
+ _MAX_PASSES = 5
50
+ _SEPARATORS = frozenset(" \t\n\r-_.()[]{}/\\:,;'\"")
51
+ _ALLOWED = {
52
+ "snake": re.compile(r"[^a-z0-9_]"),
53
+ "lower": re.compile(r"[^a-z0-9_]"),
54
+ "upper": re.compile(r"[^A-Z0-9_]"),
55
+ "preserve": re.compile(r"[^A-Za-z0-9_]"),
56
+ }
57
+ _ALLOWED_UNICODE = re.compile(r"[^\w]")
58
+
59
+
60
+ class NamingError(ValueError):
61
+ """A name that cannot be conformed under the configured policy."""
62
+
63
+ def __init__(self, source: str, reason: str) -> None:
64
+ """Name the source and say why."""
65
+ self.source = source
66
+ self.reason = reason
67
+ super().__init__(f"cannot conform {source!r}: {reason}")
68
+
69
+
70
+ @dataclass(frozen=True)
71
+ class Conformed:
72
+ """A conformed name and what was lost on the way."""
73
+
74
+ source: str
75
+ name: str
76
+ notes: tuple[str, ...] = field(default=())
77
+ """Lossy changes, e.g. ``dropped '%'`` or ``transliterated``; empty when nothing was lost."""
78
+
79
+ @property
80
+ def lossy(self) -> bool:
81
+ """True when characters were dropped or transliterated."""
82
+ return bool(self.notes)
83
+
84
+
85
+ class NameConformer:
86
+ """Conforms names with one ``naming`` configuration."""
87
+
88
+ def __init__(self, naming: NamingDefaults) -> None:
89
+ """Use these naming defaults."""
90
+ self.naming = naming
91
+ self.reserved = reserved_words(naming.reserved_dialects)
92
+
93
+ def conform(self, source: str, ordinal: int = 1) -> Conformed:
94
+ """Conform one name; ``ordinal`` (1-based) names an empty result ``col_<n>``.
95
+
96
+ Raises:
97
+ NamingError: when the policy says to fail (e.g. ``leading_digit: error``).
98
+ """
99
+ naming = self.naming
100
+ if naming.preset == "sdk":
101
+ return _sdk_conform(source)
102
+ notes: list[str] = []
103
+ text = unicodedata.normalize("NFKC", source)
104
+ text = self._ascii(text, notes)
105
+ if naming.case == "snake" and naming.split_camel:
106
+ text = _ACRONYM.sub("_", _CAMEL.sub("_", text))
107
+ text = self._case(text)
108
+ text = self._replace(text, notes)
109
+ text = self._settle(source, text, ordinal, notes)
110
+ return Conformed(source, text, tuple(notes))
111
+
112
+ def _settle(self, source: str, text: str, ordinal: int, notes: list[str]) -> str:
113
+ """Steps 6-10, repeated until the name is a fixed point.
114
+
115
+ One pass is usually enough. A truncation can cut a name back to something a step
116
+ would change again (``_0000`` truncated to ``_`` plus a hash), so the steps repeat
117
+ until nothing changes; that is what makes conforming idempotent.
118
+ """
119
+ for _ in range(_MAX_PASSES):
120
+ before = text
121
+ if self.naming.collapse:
122
+ text = _RUNS.sub("_", text).strip("_")
123
+ text = self._leading_digit(source, text)
124
+ if not text:
125
+ text = self._case(f"col_{ordinal}")
126
+ notes.append(f"nothing usable was left, so it is named {text}")
127
+ text = self._reserved(source, text)
128
+ text = self._truncate(source, text, notes)
129
+ if text == before:
130
+ return text
131
+ raise NamingError(source, f"the naming steps do not settle (last result {text!r})")
132
+
133
+ def conform_all(self, sources: Sequence[str]) -> list[Conformed]:
134
+ """Conform the names of one stream (or struct) and make them unique.
135
+
136
+ Names that collide under case folding are an error, or with ``on_collision: suffix``
137
+ the later ones get ``_2``, ``_3``, ... in input order, still within ``max_length``.
138
+
139
+ Raises:
140
+ NamingError: on a collision under ``on_collision: error``, or from :meth:`conform`.
141
+ """
142
+ results = [self.conform(source, ordinal) for ordinal, source in enumerate(sources, 1)]
143
+ # First occurrences claim their names before any suffix is chosen, so a source that is
144
+ # genuinely called order_id_2 keeps that name.
145
+ owners: dict[str, Conformed] = {}
146
+ for result in results:
147
+ owners.setdefault(result.name.casefold(), result)
148
+ taken = set(owners)
149
+ out: list[Conformed] = []
150
+ for result in results:
151
+ first = owners[result.name.casefold()]
152
+ if first is result:
153
+ out.append(result)
154
+ continue
155
+ if self.naming.on_collision == "error":
156
+ raise NamingError(
157
+ result.source,
158
+ f"it conforms to {result.name!r}, as {first.source!r} does "
159
+ "(on_collision: error)",
160
+ )
161
+ unique = self._suffixed(result.name, taken)
162
+ taken.add(unique.casefold())
163
+ note = f"renamed from {result.name!r}: {first.source!r} has that name"
164
+ out.append(Conformed(result.source, unique, (*result.notes, note)))
165
+ return out
166
+
167
+ def _suffixed(self, name: str, taken: set[str]) -> str:
168
+ n = 2
169
+ while True:
170
+ suffix = f"_{n}"
171
+ head = name[: self.naming.max_length - len(suffix)].rstrip("_")
172
+ candidate = head + suffix
173
+ if candidate.casefold() not in taken:
174
+ return candidate
175
+ n += 1
176
+
177
+ def _truncate(self, source: str, text: str, notes: list[str]) -> str:
178
+ limit = self.naming.max_length
179
+ if len(text) <= limit:
180
+ return text
181
+ if self.naming.truncate == "error":
182
+ raise NamingError(source, f"{text!r} is longer than {limit} (truncate: error)")
183
+ digest = self._case(hashlib.sha256(text.encode()).hexdigest()[:6])
184
+ head = text[: limit - len(digest) - 1].rstrip("_")
185
+ notes.append(f"truncated from {len(text)} characters")
186
+ return f"{head}_{digest}"
187
+
188
+ def _reserved(self, source: str, text: str) -> str:
189
+ policy = self.naming.reserved_words
190
+ if policy == "ignore" or text.lower() not in self.reserved:
191
+ return text
192
+ if policy == "suffix":
193
+ return text + "_"
194
+ if policy == "prefix":
195
+ return "_" + text
196
+ raise NamingError(source, f"{text!r} is a reserved word (reserved_words: error)")
197
+
198
+ def _ascii(self, text: str, notes: list[str]) -> str:
199
+ if self.naming.ascii == "keep" or text.isascii():
200
+ return text
201
+ if self.naming.ascii == "strip":
202
+ kept = "".join(c for c in text if c.isascii())
203
+ notes.append(f"dropped non-ASCII {_quote(c for c in text if not c.isascii())}")
204
+ return kept
205
+ ascii_, dropped = transliterate(text)
206
+ if len(dropped) < sum(1 for c in text if not c.isascii()):
207
+ notes.append("transliterated to ASCII")
208
+ if dropped:
209
+ notes.append(f"dropped {_quote(dropped)} (no transliteration)")
210
+ return ascii_
211
+
212
+ def _case(self, text: str) -> str:
213
+ case = self.naming.case
214
+ if case in {"snake", "lower"}:
215
+ return text.lower()
216
+ if case == "upper":
217
+ return text.upper()
218
+ return text
219
+
220
+ def _replace(self, text: str, notes: list[str]) -> str:
221
+ pattern = _ALLOWED_UNICODE if self.naming.ascii == "keep" else _ALLOWED[self.naming.case]
222
+ lost = [c for c in pattern.findall(text) if c not in _SEPARATORS]
223
+ if lost:
224
+ notes.append(f"dropped {_quote(lost)}")
225
+ return pattern.sub(self.naming.replace_invalid, text)
226
+
227
+ def _leading_digit(self, source: str, text: str) -> str:
228
+ if not text or not text[0].isdigit():
229
+ return text
230
+ policy = self.naming.leading_digit
231
+ value = unicodedata.digit(text[0], None)
232
+ if policy == "prefix" or (policy == "letter" and value is None):
233
+ # A digit-like character with no digit value (e.g. U+11052 BRAHMI NUMBER ONE,
234
+ # kept by ascii: keep) cannot become a letter, so it is prefixed instead.
235
+ return "_" + text
236
+ if policy == "letter" and value is not None:
237
+ return self._case("abcdefghij"[value]) + text[1:]
238
+ raise NamingError(source, "it starts with a digit (leading_digit: error)")
239
+
240
+
241
+ def _quote(chars: Iterable[str]) -> str:
242
+ return ", ".join(repr(c) for c in dict.fromkeys(chars))
243
+
244
+
245
+ _SDK_DROP = re.compile(r"[^a-zA-Z0-9_\-\.\s]")
246
+
247
+
248
+ def _sdk_conform(source: str) -> Conformed:
249
+ """The Singer SDK's ``SQLSink.conform_name``, byte for byte.
250
+
251
+ Raises:
252
+ NamingError: when nothing is left, where the SDK fails with an IndexError.
253
+ """
254
+ kept = _SDK_DROP.sub("", source)
255
+ notes = ["characters outside [a-zA-Z0-9_-. ] dropped"] if kept != source else []
256
+ name = kept.lower().lstrip().rstrip().replace(".", "_").replace("-", "_").replace(" ", "_")
257
+ if not name:
258
+ raise NamingError(source, "nothing is left under naming: sdk")
259
+ if name[0] in "0123456789":
260
+ name = "abcdefghij"[int(name[0])] + name[1:]
261
+ notes.append("leading digit turned into a letter (SDK style)")
262
+ return Conformed(source, name, tuple(notes))
@@ -0,0 +1,148 @@
1
+ """Flatten nested objects into columns, with the Singer SDK's semantics (WBS 12.7).
2
+
3
+ For ``nested: flatten``, undeclared object properties of the tap SCHEMA become columns named
4
+ by joining the path with ``flatten.separator``, down to ``flatten.max_depth`` levels. This is
5
+ the SDK's algorithm (``singer_sdk.helpers._flattening``) re-implemented, so that keys,
6
+ types and values are the same:
7
+
8
+ - A key at least ``max_key_length`` long is shortened from its first part on: each part is
9
+ camelized and reduced to its capitals (``user_profile`` -> ``up``), or to its first three
10
+ letters when that leaves one letter or none, until the key fits.
11
+ - Below the depth limit, objects and arrays become JSON text, and their SCHEMA type a string.
12
+ - A typeless property becomes a nullable string; for ``anyOf``-style properties the first
13
+ branch is used.
14
+ - Two paths flattening to the same key are an error.
15
+
16
+ Columns the spec declares by name (the object itself, or a source of a column) are not
17
+ flattened: the spec decides what happens to them.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import re
23
+ from collections.abc import Mapping, MutableMapping
24
+ from dataclasses import dataclass
25
+ from typing import Any
26
+
27
+ from map_conform.types.jsontext import dumps
28
+
29
+ _LOWER = re.compile(r"[a-z]")
30
+ _CAMEL = re.compile(r"(?:^|_)(.)")
31
+
32
+
33
+ class FlattenError(ValueError):
34
+ """Two nested paths flatten to the same column name."""
35
+
36
+
37
+ def _camelize(word: str) -> str:
38
+ """``inflection.camelize``: upper the first letter and each letter after ``_``."""
39
+ return _CAMEL.sub(lambda m: m.group(1).upper(), word)
40
+
41
+
42
+ def flatten_key(name: str, parents: list[str], separator: str, max_key_length: int) -> str:
43
+ """The flattened key, shortened like the SDK's when it is too long."""
44
+ parts = [*parents, name]
45
+ index = 0
46
+ while len(separator.join(parts)) >= max_key_length and index < len(parts):
47
+ reduced = _LOWER.sub("", _camelize(parts[index]))
48
+ parts[index] = (reduced if len(reduced) > 1 else parts[index][:3]).lower()
49
+ index += 1
50
+ return separator.join(parts)
51
+
52
+
53
+ def _types(schema: Mapping[str, Any]) -> list[str]:
54
+ declared = schema.get("type", [])
55
+ return [declared] if isinstance(declared, str) else list(declared)
56
+
57
+
58
+ @dataclass(frozen=True)
59
+ class Flattener:
60
+ """Flattens one stream's SCHEMA properties and records."""
61
+
62
+ separator: str
63
+ max_depth: int
64
+ max_key_length: int
65
+ keep: frozenset[str]
66
+ """Top-level properties the spec names; they are left as they are."""
67
+ typed_leaves: bool = False
68
+ """For a declared shape: arrays and objects below the depth keep their declared types
69
+ (list, struct, json) instead of becoming JSON text as the SDK makes them."""
70
+
71
+ def properties(self, properties: Mapping[str, Any]) -> dict[str, Any]:
72
+ """The flattened SCHEMA properties, in the SDK's order.
73
+
74
+ Raises:
75
+ FlattenError: when two paths give the same key.
76
+ """
77
+ items: list[tuple[str, Any]] = []
78
+ for name, schema in properties.items():
79
+ if name in self.keep:
80
+ items.append((name, schema))
81
+ else:
82
+ items.extend(self._schema({name: schema}, [], 0))
83
+ out: dict[str, Any] = {}
84
+ for key, schema in items:
85
+ if key in out:
86
+ msg = f"two nested paths flatten to the column {key!r}"
87
+ raise FlattenError(msg)
88
+ out[key] = schema
89
+ return out
90
+
91
+ def _schema(
92
+ self, properties: Mapping[str, Any], parents: list[str], level: int
93
+ ) -> list[tuple[str, Any]]:
94
+ items: list[tuple[str, Any]] = []
95
+ for name, schema in properties.items():
96
+ key = flatten_key(name, parents, self.separator, self.max_key_length)
97
+ if "type" in schema:
98
+ types = _types(schema)
99
+ if "object" in types and "properties" in schema and level < self.max_depth:
100
+ items.extend(self._schema(schema["properties"], [*parents, name], level + 1))
101
+ elif self.typed_leaves:
102
+ items.append((key, schema))
103
+ elif "array" in types or ("object" in types and self.max_depth > 0):
104
+ items.append(
105
+ (key, {"type": ["string", "null"] if "null" in types else "string"})
106
+ )
107
+ else:
108
+ items.append((key, schema))
109
+ elif (
110
+ (composite := next(iter(schema.values()), None))
111
+ and isinstance(composite, list)
112
+ and (first := composite[0])
113
+ ):
114
+ # anyOf and friends: the first branch, made nullable (or dropped, as the SDK
115
+ # does, when it is not a string, array or object)
116
+ if isinstance(first, Mapping) and first.get("type") in (
117
+ "string",
118
+ "array",
119
+ "object",
120
+ ):
121
+ items.append((key, {**first, "type": ["null", first["type"]]}))
122
+ else:
123
+ items.append((key, {"type": ["null", "string"]}))
124
+ return items
125
+
126
+ def record(self, record: Mapping[str, Any], schema: Mapping[str, Any]) -> dict[str, Any]:
127
+ """The record with nested objects flattened as its SCHEMA was."""
128
+ out: dict[str, Any] = {}
129
+ for name, value in record.items():
130
+ if name in self.keep:
131
+ out[name] = value
132
+ else:
133
+ out.update(self._record({name: value}, schema, [], 0))
134
+ return out
135
+
136
+ def _record(
137
+ self, node: Mapping[str, Any], schema: Mapping[str, Any], parents: list[str], level: int
138
+ ) -> dict[str, Any]:
139
+ items: dict[str, Any] = {}
140
+ for name, value in node.items():
141
+ key = flatten_key(name, parents, self.separator, self.max_key_length)
142
+ if isinstance(value, MutableMapping) and key not in schema and level < self.max_depth:
143
+ items.update(self._record(value, schema, [*parents, name], level + 1))
144
+ elif isinstance(value, (dict, list)):
145
+ items[key] = dumps(value, compact=True)
146
+ else:
147
+ items[key] = value
148
+ return items
@@ -0,0 +1,117 @@
1
+ """Conform member names inside struct shapes (``naming.nested``).
2
+
3
+ A struct's members are conformed like a stream's columns: the same pipeline, with
4
+ collisions checked within each struct. Lists are transparent: the members of
5
+ ``list<struct<...>>`` are the struct's. Two shapes are supported:
6
+
7
+ - declared CTypes (``struct<customerID: string, ...>``), and
8
+ - tap SCHEMA objects (``{"type": "object", "properties": {...}}``), for undeclared columns
9
+ kept as typed structs (``nested: keep``).
10
+
11
+ Each returns the conformed shape and a :class:`MemberNames` tree, which
12
+ :func:`rename_value` uses to rename the keys of record values at run time.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from collections.abc import Mapping
18
+ from dataclasses import dataclass, field, replace
19
+ from types import MappingProxyType
20
+ from typing import TYPE_CHECKING, Any
21
+
22
+ if TYPE_CHECKING:
23
+ from map_conform.naming.conform import NameConformer
24
+ from map_conform.types.canonical import CType
25
+
26
+
27
+ def _empty() -> Mapping[str, Any]:
28
+ return MappingProxyType({})
29
+
30
+
31
+ @dataclass(frozen=True)
32
+ class MemberNames:
33
+ """Source-to-conformed member names of one struct, and of the structs inside it."""
34
+
35
+ names: Mapping[str, str] = field(default_factory=_empty)
36
+ children: Mapping[str, MemberNames] = field(default_factory=_empty)
37
+
38
+
39
+ def conform_ctype(ctype: CType, conformer: NameConformer) -> tuple[CType, MemberNames | None]:
40
+ """Conform the member names of a struct CType, recursively.
41
+
42
+ Returns:
43
+ The conformed CType and its name tree, or the CType unchanged and None when it has no
44
+ struct inside or ``naming.nested`` is off.
45
+ """
46
+ if not conformer.naming.nested:
47
+ return ctype, None
48
+ if ctype.kind == "list" and ctype.item is not None:
49
+ item, names = conform_ctype(ctype.item, conformer)
50
+ return replace(ctype, item=item), names
51
+ if ctype.kind != "struct":
52
+ return ctype, None
53
+ sources = [name for name, _ in ctype.members]
54
+ conformed = [c.name for c in conformer.conform_all(sources)]
55
+ members: list[tuple[str, CType]] = []
56
+ children: dict[str, MemberNames] = {}
57
+ for (source, member_type), name in zip(ctype.members, conformed, strict=True):
58
+ inner, inner_names = conform_ctype(member_type, conformer)
59
+ members.append((name, inner))
60
+ if inner_names is not None:
61
+ children[source] = inner_names
62
+ tree = MemberNames(
63
+ MappingProxyType(dict(zip(sources, conformed, strict=True))),
64
+ MappingProxyType(children),
65
+ )
66
+ return replace(ctype, members=tuple(members)), tree
67
+
68
+
69
+ def conform_schema(
70
+ schema: Mapping[str, Any], conformer: NameConformer
71
+ ) -> tuple[dict[str, Any], MemberNames | None]:
72
+ """Conform the property names of a JSON Schema object, recursively.
73
+
74
+ ``required`` lists are renamed with their properties. Other keywords are kept.
75
+
76
+ Returns:
77
+ A new schema and its name tree, or a copy and None when there is nothing to conform.
78
+ """
79
+ out = dict(schema)
80
+ if not conformer.naming.nested:
81
+ return out, None
82
+ if isinstance(schema.get("items"), Mapping):
83
+ out["items"], names = conform_schema(schema["items"], conformer)
84
+ return out, names
85
+ properties = schema.get("properties")
86
+ if not isinstance(properties, Mapping):
87
+ return out, None
88
+ sources = list(properties)
89
+ conformed = [c.name for c in conformer.conform_all(sources)]
90
+ mapping = dict(zip(sources, conformed, strict=True))
91
+ new_properties: dict[str, Any] = {}
92
+ children: dict[str, MemberNames] = {}
93
+ for source, name in mapping.items():
94
+ new_properties[name], inner = conform_schema(properties[source], conformer)
95
+ if inner is not None:
96
+ children[source] = inner
97
+ out["properties"] = new_properties
98
+ if isinstance(schema.get("required"), list):
99
+ out["required"] = [mapping.get(r, r) for r in schema["required"]]
100
+ return out, MemberNames(MappingProxyType(mapping), MappingProxyType(children))
101
+
102
+
103
+ def rename_value(value: object, names: MemberNames) -> object:
104
+ """Rename the keys of a nested record value; lists are walked item by item.
105
+
106
+ Keys the tree does not know are kept as they are.
107
+ """
108
+ if isinstance(value, Mapping):
109
+ return {
110
+ names.names.get(key, key): (
111
+ rename_value(item, names.children[key]) if key in names.children else item
112
+ )
113
+ for key, item in value.items()
114
+ }
115
+ if isinstance(value, list):
116
+ return [rename_value(item, names) for item in value]
117
+ return value