andvari 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.
- andvari/__init__.py +3 -0
- andvari/cli.py +97 -0
- andvari/diff.py +304 -0
- andvari/models.py +60 -0
- andvari-0.1.0.dist-info/METADATA +150 -0
- andvari-0.1.0.dist-info/RECORD +9 -0
- andvari-0.1.0.dist-info/WHEEL +4 -0
- andvari-0.1.0.dist-info/entry_points.txt +3 -0
- andvari-0.1.0.dist-info/licenses/LICENSE +21 -0
andvari/__init__.py
ADDED
andvari/cli.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"""The `andvari` command.
|
|
2
|
+
|
|
3
|
+
andvari diff <old.json> <new.json>
|
|
4
|
+
andvari models <schema.json> <out.py> [--class-name NAME]
|
|
5
|
+
|
|
6
|
+
Exit codes: 0 for no difference (or models written), 1 when the two schemas
|
|
7
|
+
differ, 2 when something went wrong. A CI job only needs the exit code.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import sys
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
from andvari.diff import Change, SchemaError, diff, fingerprint
|
|
15
|
+
from andvari.models import generate
|
|
16
|
+
|
|
17
|
+
# The order in which changes are printed and counted: most serious first.
|
|
18
|
+
SEVERITIES = ("breaking", "warning", "compatible", "annotation")
|
|
19
|
+
|
|
20
|
+
USAGE = "usage: andvari diff <old> <new> | andvari models <schema> <out.py> [--class-name NAME]"
|
|
21
|
+
|
|
22
|
+
# Printed when the fingerprints differ but the comparison found nothing. That
|
|
23
|
+
# happens when the only difference is in a definition that nothing refers to.
|
|
24
|
+
UNLISTED = "no change listed: the difference is in a definition nothing references"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def run_models(args: list[str]) -> int:
|
|
28
|
+
"""Handle `andvari models <schema> <out.py> [--class-name NAME]`."""
|
|
29
|
+
if len(args) == 2:
|
|
30
|
+
class_name = None
|
|
31
|
+
elif len(args) == 4 and args[2] == "--class-name":
|
|
32
|
+
class_name = args[3]
|
|
33
|
+
else:
|
|
34
|
+
raise SchemaError(USAGE)
|
|
35
|
+
generate(Path(args[0]), Path(args[1]), class_name)
|
|
36
|
+
return 0
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def load(path: str) -> dict:
|
|
40
|
+
"""Read one schema file. A schema has to be a JSON object to be compared."""
|
|
41
|
+
schema = json.loads(Path(path).read_text(encoding="utf-8"))
|
|
42
|
+
if not isinstance(schema, dict):
|
|
43
|
+
raise SchemaError("a schema is not a JSON object")
|
|
44
|
+
return schema
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def report(old: dict, new: dict, changes: list[Change]) -> int:
|
|
48
|
+
"""Print the result of a comparison and return the exit code."""
|
|
49
|
+
print(f"old {fingerprint(old)}")
|
|
50
|
+
print(f"new {fingerprint(new)}")
|
|
51
|
+
|
|
52
|
+
# The fingerprint decides whether anything changed. The list of changes
|
|
53
|
+
# only explains what.
|
|
54
|
+
if fingerprint(old) == fingerprint(new):
|
|
55
|
+
print("unchanged")
|
|
56
|
+
return 0
|
|
57
|
+
|
|
58
|
+
for change in changes:
|
|
59
|
+
print(f"{change.severity} {change.path} {change.keyword or '-'} {change.reason}")
|
|
60
|
+
|
|
61
|
+
if not changes:
|
|
62
|
+
print(UNLISTED)
|
|
63
|
+
return 1
|
|
64
|
+
|
|
65
|
+
counts = ", ".join(
|
|
66
|
+
f"{sum(change.severity == severity for change in changes)} {severity}"
|
|
67
|
+
for severity in SEVERITIES
|
|
68
|
+
)
|
|
69
|
+
print(f"{len(changes)} changes: {counts}")
|
|
70
|
+
return 1
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def run_diff(args: list[str]) -> int:
|
|
74
|
+
"""Handle `andvari diff <old> <new>`."""
|
|
75
|
+
if len(args) != 2:
|
|
76
|
+
raise SchemaError(USAGE)
|
|
77
|
+
old, new = load(args[0]), load(args[1])
|
|
78
|
+
# `diff` returns changes sorted by path. Python's sort keeps that order
|
|
79
|
+
# within each severity, so this only groups them by severity.
|
|
80
|
+
changes = sorted(diff(old, new), key=lambda change: SEVERITIES.index(change.severity))
|
|
81
|
+
return report(old, new, changes)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def main(argv: list[str] | None = None) -> int:
|
|
85
|
+
"""Run the command line and return the exit code."""
|
|
86
|
+
args = sys.argv[1:] if argv is None else argv
|
|
87
|
+
try:
|
|
88
|
+
if args[:1] == ["models"]:
|
|
89
|
+
return run_models(args[1:])
|
|
90
|
+
if args[:1] == ["diff"]:
|
|
91
|
+
return run_diff(args[1:])
|
|
92
|
+
raise SchemaError(USAGE)
|
|
93
|
+
except (OSError, ValueError, SchemaError) as error:
|
|
94
|
+
# Every failure is reported the same way: one line on stderr, exit 2,
|
|
95
|
+
# and nothing on stdout that a script could mistake for a result.
|
|
96
|
+
print(f"error: {error}", file=sys.stderr)
|
|
97
|
+
return 2
|
andvari/diff.py
ADDED
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
"""Compare two versions of a JSON Schema and say what changed.
|
|
2
|
+
|
|
3
|
+
The comparison works on what the schemas say, not on which data they accept:
|
|
4
|
+
|
|
5
|
+
1. `inline_refs` replaces every local `$ref` with the thing it points at, so a
|
|
6
|
+
change inside a shared definition shows up at each place that uses it.
|
|
7
|
+
2. `flatten` turns the schema into a flat table: one row per field, keyed by a
|
|
8
|
+
path such as `/address/street`, holding the keywords set on that field.
|
|
9
|
+
3. `diff` compares the two tables row by row and keyword by keyword, and
|
|
10
|
+
`classify` labels each difference with a severity.
|
|
11
|
+
|
|
12
|
+
Only `properties` and `items` are followed into. Everything else on a field
|
|
13
|
+
(`oneOf`, `if`, `pattern`, ...) is compared as one value: if it differs at all,
|
|
14
|
+
that is reported, with no attempt to work out what the difference means.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
import hashlib
|
|
18
|
+
import json
|
|
19
|
+
from typing import NamedTuple
|
|
20
|
+
|
|
21
|
+
# Keywords whose values are plain data, not schemas. A `{"$ref": ...}` object
|
|
22
|
+
# found inside one of these is somebody's example or default, not a reference.
|
|
23
|
+
DATA = ("enum", "const", "default", "examples")
|
|
24
|
+
|
|
25
|
+
# Keywords that describe a field without constraining its value.
|
|
26
|
+
ANNOTATIONS = ("title", "description", "examples", "$comment", "default")
|
|
27
|
+
|
|
28
|
+
LOWER_BOUNDS = ("minimum", "exclusiveMinimum", "minLength", "minItems", "minProperties")
|
|
29
|
+
UPPER_BOUNDS = ("maximum", "exclusiveMaximum", "maxLength", "maxItems", "maxProperties")
|
|
30
|
+
|
|
31
|
+
# The only keywords for which the direction of a change is judged. For these a
|
|
32
|
+
# change can be a loosening (accepts more than before) and therefore harmless.
|
|
33
|
+
# A change to any other keyword is always reported as breaking.
|
|
34
|
+
RELAXABLE = ("required", "type", "enum", *LOWER_BOUNDS, *UPPER_BOUNDS)
|
|
35
|
+
|
|
36
|
+
# Stands for "this keyword is not set", which is different from it being set
|
|
37
|
+
# to null. `None` cannot be used because `{"const": null}` is a real schema.
|
|
38
|
+
MISSING = object()
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class SchemaError(Exception):
|
|
42
|
+
"""The input cannot be compared: a bad `$ref`, or two fields on one path."""
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class Change(NamedTuple):
|
|
46
|
+
"""One difference between the old and the new schema.
|
|
47
|
+
|
|
48
|
+
`keyword` is None when a whole field was added or removed, and the name of
|
|
49
|
+
the keyword when a field exists in both and one of its keywords differs.
|
|
50
|
+
"""
|
|
51
|
+
|
|
52
|
+
path: str
|
|
53
|
+
keyword: str | None
|
|
54
|
+
severity: str
|
|
55
|
+
reason: str
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def canonical(value: object) -> str:
|
|
59
|
+
"""Serialise JSON so that equal values always give equal text.
|
|
60
|
+
|
|
61
|
+
Keys are sorted and whitespace is removed, so two files that differ only
|
|
62
|
+
in key order or formatting produce the same string.
|
|
63
|
+
"""
|
|
64
|
+
return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def fingerprint(schema: object) -> str:
|
|
68
|
+
"""Return the SHA-256 of the canonical form: the identity of a schema version."""
|
|
69
|
+
return hashlib.sha256(canonical(schema).encode("utf-8")).hexdigest()
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def resolve(root: object, ref: str) -> object:
|
|
73
|
+
"""Follow a local `$ref` such as `#/definitions/address` from the schema root.
|
|
74
|
+
|
|
75
|
+
Anything that does not point inside this document is refused. Fetching
|
|
76
|
+
another file would make the result depend on something outside the input.
|
|
77
|
+
"""
|
|
78
|
+
if not ref.startswith("#"):
|
|
79
|
+
raise SchemaError(f"$ref outside this schema: {ref}")
|
|
80
|
+
if ref == "#":
|
|
81
|
+
return root
|
|
82
|
+
if not ref.startswith("#/"):
|
|
83
|
+
raise SchemaError(f"unresolvable $ref: {ref}")
|
|
84
|
+
|
|
85
|
+
node = root
|
|
86
|
+
for raw in ref[2:].split("/"):
|
|
87
|
+
# JSON Pointer escapes: `~1` is a slash and `~0` is a tilde inside a name.
|
|
88
|
+
token = raw.replace("~1", "/").replace("~0", "~")
|
|
89
|
+
if not isinstance(node, dict) or token not in node:
|
|
90
|
+
raise SchemaError(f"unresolvable $ref: {ref}")
|
|
91
|
+
node = node[token]
|
|
92
|
+
return node
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def expand(node: object, root: object, active: frozenset[str]) -> object:
|
|
96
|
+
"""Return a copy of `node` with every local `$ref` replaced by its target.
|
|
97
|
+
|
|
98
|
+
`active` holds the references currently being expanded. Meeting one of them
|
|
99
|
+
again means the schema is recursive; that reference is left as it is, which
|
|
100
|
+
is what stops the expansion from running forever.
|
|
101
|
+
"""
|
|
102
|
+
if isinstance(node, list):
|
|
103
|
+
return [expand(item, root, active) for item in node]
|
|
104
|
+
if not isinstance(node, dict):
|
|
105
|
+
return node
|
|
106
|
+
|
|
107
|
+
# Expand everything nested in this node first, leaving data values alone.
|
|
108
|
+
walked = {
|
|
109
|
+
key: value if key in DATA else expand(value, root, active) for key, value in node.items()
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
ref = node.get("$ref")
|
|
113
|
+
if not isinstance(ref, str) or ref in active:
|
|
114
|
+
return walked
|
|
115
|
+
|
|
116
|
+
target = expand(resolve(root, ref), root, active | {ref})
|
|
117
|
+
siblings = {key: value for key, value in walked.items() if key != "$ref"}
|
|
118
|
+
|
|
119
|
+
if not siblings:
|
|
120
|
+
return target
|
|
121
|
+
|
|
122
|
+
# Keywords written next to the `$ref` apply in addition to the target.
|
|
123
|
+
# If they do not overlap with the target they can simply be merged in.
|
|
124
|
+
if isinstance(target, dict) and target.keys().isdisjoint(siblings):
|
|
125
|
+
return {**target, **siblings}
|
|
126
|
+
|
|
127
|
+
# If they do overlap, merging would let one side overwrite the other and
|
|
128
|
+
# hide a change to the overwritten one. Keeping both under `allOf` says
|
|
129
|
+
# the same thing and loses nothing.
|
|
130
|
+
return {"allOf": [target, siblings]}
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def inline_refs(schema: dict) -> dict:
|
|
134
|
+
"""Return the schema with local references expanded and definitions removed.
|
|
135
|
+
|
|
136
|
+
The definitions are dropped because their content now sits wherever it is
|
|
137
|
+
used. A definition nothing refers to therefore disappears here, which is
|
|
138
|
+
why a change to one alters the fingerprint but lists no change.
|
|
139
|
+
"""
|
|
140
|
+
# Starting with "#" as active makes a reference to the whole document
|
|
141
|
+
# count as recursive from the outset.
|
|
142
|
+
expanded = expand(schema, schema, frozenset({"#"}))
|
|
143
|
+
return {key: value for key, value in expanded.items() if key not in ("definitions", "$defs")}
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def flatten(node: object, path: str = "/", required: bool = False, out: dict | None = None) -> dict:
|
|
147
|
+
"""Turn a schema into a table of `path -> keywords set on that field`.
|
|
148
|
+
|
|
149
|
+
The root is `/`, a property is `/name`, the items of an array are `/name/*`.
|
|
150
|
+
Each row carries a `required` flag saying whether the parent demands the
|
|
151
|
+
field, followed by the field's own keywords exactly as written.
|
|
152
|
+
"""
|
|
153
|
+
out = {} if out is None else out
|
|
154
|
+
|
|
155
|
+
# A property literally named `*` beside `items` would land on the same
|
|
156
|
+
# path as the items. One row would silently replace the other, so stop.
|
|
157
|
+
if path in out:
|
|
158
|
+
raise SchemaError(f"two schemas share the path {path}")
|
|
159
|
+
|
|
160
|
+
# A schema may be `true` or `false` instead of an object. Record the value
|
|
161
|
+
# so that a change between them is still seen.
|
|
162
|
+
if not isinstance(node, dict):
|
|
163
|
+
out[path] = {"required": required, "schema": node}
|
|
164
|
+
return out
|
|
165
|
+
|
|
166
|
+
# The keywords that are followed into rather than stored on the row.
|
|
167
|
+
walked = {key for key in ("properties", "items") if isinstance(node.get(key), dict)}
|
|
168
|
+
skipped = walked | {"required", "definitions", "$defs"}
|
|
169
|
+
out[path] = {
|
|
170
|
+
"required": required,
|
|
171
|
+
**{key: value for key, value in node.items() if key not in skipped},
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
properties = node["properties"] if "properties" in walked else {}
|
|
175
|
+
|
|
176
|
+
# `required` lists names on the parent. It is turned into a flag on each
|
|
177
|
+
# child row, so that "this field became required" is a change to the field.
|
|
178
|
+
names = node.get("required", [])
|
|
179
|
+
if not isinstance(names, list):
|
|
180
|
+
# Not a list, so not understood. Keep it visible instead of ignoring it.
|
|
181
|
+
out[path]["required names"] = names
|
|
182
|
+
names = []
|
|
183
|
+
else:
|
|
184
|
+
# Names that are required but not declared have no child row to carry
|
|
185
|
+
# the flag. Keep them on the parent so a change to them is not lost.
|
|
186
|
+
undeclared = [name for name in names if name not in properties]
|
|
187
|
+
if undeclared:
|
|
188
|
+
out[path]["required names"] = undeclared
|
|
189
|
+
|
|
190
|
+
prefix = "" if path == "/" else path
|
|
191
|
+
for name, child in properties.items():
|
|
192
|
+
# Escape `/` and `~` in the name so the path stays unambiguous.
|
|
193
|
+
escaped = name.replace("~", "~0").replace("/", "~1")
|
|
194
|
+
flatten(child, f"{prefix}/{escaped}", name in names, out)
|
|
195
|
+
if "items" in walked:
|
|
196
|
+
flatten(node["items"], f"{prefix}/*", False, out)
|
|
197
|
+
return out
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def loosened(key: str, old: object, new: object) -> bool:
|
|
201
|
+
"""Say whether a relaxable keyword now accepts at least everything it did before."""
|
|
202
|
+
if key == "required":
|
|
203
|
+
return not new
|
|
204
|
+
|
|
205
|
+
if key in ("type", "enum"):
|
|
206
|
+
# Both keywords name a set of allowed things. It is a loosening when
|
|
207
|
+
# every old member is still there. Members are compared in canonical
|
|
208
|
+
# form so that `1` and `true`, or two equal objects, are told apart
|
|
209
|
+
# correctly.
|
|
210
|
+
old_values = [canonical(v) for v in (old if isinstance(old, list) else [old])]
|
|
211
|
+
new_values = [canonical(v) for v in (new if isinstance(new, list) else [new])]
|
|
212
|
+
if key == "type" and '"number"' in new_values:
|
|
213
|
+
# Every integer is a number, so `number` also allows `integer`.
|
|
214
|
+
new_values.append('"integer"')
|
|
215
|
+
return all(value in new_values for value in old_values)
|
|
216
|
+
|
|
217
|
+
# What is left are the numeric bounds. A bound that is not a number is not
|
|
218
|
+
# understood, and is never called a loosening. `bool` is excluded on
|
|
219
|
+
# purpose: in Python it would otherwise pass as an integer.
|
|
220
|
+
if not all(type(value) in (int, float) for value in (old, new)):
|
|
221
|
+
return False
|
|
222
|
+
if key in UPPER_BOUNDS:
|
|
223
|
+
return new >= old
|
|
224
|
+
return new <= old
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def classify(key: str, old: object, new: object) -> tuple[str, str]:
|
|
228
|
+
"""Label one keyword difference on a field with a severity and a reason."""
|
|
229
|
+
if old is MISSING:
|
|
230
|
+
verb = "added"
|
|
231
|
+
elif new is MISSING:
|
|
232
|
+
verb = "removed"
|
|
233
|
+
else:
|
|
234
|
+
verb = "changed"
|
|
235
|
+
|
|
236
|
+
if key in ANNOTATIONS:
|
|
237
|
+
return "annotation", f"{key} {verb}"
|
|
238
|
+
|
|
239
|
+
# Outside the relaxable set nothing is known about direction, so any
|
|
240
|
+
# difference needs a person to look at it. A newly added constraint is
|
|
241
|
+
# breaking for every keyword, relaxable or not.
|
|
242
|
+
if key not in RELAXABLE or old is MISSING:
|
|
243
|
+
return "breaking", f"{key} {verb}"
|
|
244
|
+
|
|
245
|
+
# Taking a constraint away cannot reject anything that was accepted.
|
|
246
|
+
if new is MISSING:
|
|
247
|
+
return "compatible", f"{key} removed"
|
|
248
|
+
|
|
249
|
+
if loosened(key, old, new):
|
|
250
|
+
# A longer `enum` is harmless to existing data, but it is a new choice
|
|
251
|
+
# that whoever displays the field has to know about.
|
|
252
|
+
severity = "warning" if key == "enum" else "compatible"
|
|
253
|
+
return severity, f"{key} loosened"
|
|
254
|
+
|
|
255
|
+
return "breaking", f"{key} changed"
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def parent(path: str) -> str:
|
|
259
|
+
"""Return the path one level up: `/a/b` gives `/a`, and `/a` gives `/`."""
|
|
260
|
+
return path.rsplit("/", 1)[0] or "/"
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def diff(old: dict, new: dict) -> list[Change]:
|
|
264
|
+
"""List every difference between two schemas, sorted by path then keyword."""
|
|
265
|
+
before = flatten(inline_refs(old))
|
|
266
|
+
after = flatten(inline_refs(new))
|
|
267
|
+
gone = before.keys() - after.keys()
|
|
268
|
+
fresh = after.keys() - before.keys()
|
|
269
|
+
changes = []
|
|
270
|
+
|
|
271
|
+
# Removed fields. When a whole object goes, only the object is reported,
|
|
272
|
+
# not every field that was inside it.
|
|
273
|
+
for path in gone:
|
|
274
|
+
if parent(path) not in gone:
|
|
275
|
+
changes.append(Change(path, None, "breaking", "path removed"))
|
|
276
|
+
|
|
277
|
+
# Added fields, with the same rule for whole objects.
|
|
278
|
+
for path in fresh:
|
|
279
|
+
if parent(path) in fresh:
|
|
280
|
+
continue
|
|
281
|
+
if after[path]["required"]:
|
|
282
|
+
changes.append(Change(path, None, "breaking", "required property added"))
|
|
283
|
+
elif path.endswith("/*"):
|
|
284
|
+
# An array that had no item schema accepted anything in it.
|
|
285
|
+
changes.append(Change(path, None, "breaking", "items added"))
|
|
286
|
+
else:
|
|
287
|
+
changes.append(Change(path, None, "warning", "optional property added"))
|
|
288
|
+
|
|
289
|
+
# Fields present in both: compare every keyword either side has.
|
|
290
|
+
for path in before.keys() & after.keys():
|
|
291
|
+
a, b = before[path], after[path]
|
|
292
|
+
for key in a.keys() | b.keys():
|
|
293
|
+
old_value = a.get(key, MISSING)
|
|
294
|
+
new_value = b.get(key, MISSING)
|
|
295
|
+
if old_value is MISSING or new_value is MISSING:
|
|
296
|
+
differs = True
|
|
297
|
+
else:
|
|
298
|
+
differs = canonical(old_value) != canonical(new_value)
|
|
299
|
+
if differs:
|
|
300
|
+
changes.append(Change(path, key, *classify(key, old_value, new_value)))
|
|
301
|
+
|
|
302
|
+
# The loops above run over sets, whose order is not fixed. Sorting makes
|
|
303
|
+
# the output the same on every run.
|
|
304
|
+
return sorted(changes, key=lambda change: (change.path, change.keyword or ""))
|
andvari/models.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""Write Pydantic v2 models for a JSON Schema.
|
|
2
|
+
|
|
3
|
+
This is glue. The conversion is done by `datamodel-code-generator`; the only
|
|
4
|
+
thing added here is a fixed set of flags, so that the same schema always
|
|
5
|
+
produces the same file.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import subprocess
|
|
9
|
+
import sys
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
from andvari.diff import SchemaError
|
|
13
|
+
|
|
14
|
+
FLAGS = (
|
|
15
|
+
# The input is a JSON Schema, not OpenAPI or sample data.
|
|
16
|
+
"--input-file-type",
|
|
17
|
+
"jsonschema",
|
|
18
|
+
# Emit Pydantic v2 classes.
|
|
19
|
+
"--output-model-type",
|
|
20
|
+
"pydantic_v2.BaseModel",
|
|
21
|
+
# The default header contains the time of generation, which would make
|
|
22
|
+
# every run produce a different file.
|
|
23
|
+
"--disable-timestamp",
|
|
24
|
+
# Format with the generator's own formatter, so the result does not depend
|
|
25
|
+
# on which other formatters happen to be installed.
|
|
26
|
+
"--formatters",
|
|
27
|
+
"builtin",
|
|
28
|
+
# Never download a schema referenced by URL.
|
|
29
|
+
"--no-allow-remote-refs",
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
# Replaces the default header, which names the input file. With that name in
|
|
33
|
+
# it, the same schema under two file names would give two different outputs.
|
|
34
|
+
HEADER = "# generated by andvari from a JSON Schema; do not edit"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def generate(schema: Path, out: Path, class_name: str | None = None) -> None:
|
|
38
|
+
"""Run the generator on `schema` and write the models to `out`.
|
|
39
|
+
|
|
40
|
+
`class_name` names the root model. Without it the generator picks a name
|
|
41
|
+
from the schema's `title`, or falls back to `Model`.
|
|
42
|
+
"""
|
|
43
|
+
# Remove any earlier output first. Otherwise a run that fails without
|
|
44
|
+
# writing anything would leave the old file in place and look successful.
|
|
45
|
+
out.unlink(missing_ok=True)
|
|
46
|
+
|
|
47
|
+
# Run the generator with the interpreter that is running andvari, so it is
|
|
48
|
+
# the pinned version from this environment and not another one on PATH.
|
|
49
|
+
command = [sys.executable, "-m", "datamodel_code_generator", *FLAGS]
|
|
50
|
+
command += ["--input", str(schema), "--output", str(out), "--custom-file-header", HEADER]
|
|
51
|
+
if class_name:
|
|
52
|
+
command += ["--class-name", class_name]
|
|
53
|
+
|
|
54
|
+
done = subprocess.run(command, capture_output=True, text=True, check=False)
|
|
55
|
+
if done.returncode != 0 or not out.exists():
|
|
56
|
+
raise SchemaError(done.stderr.strip() or "no output written")
|
|
57
|
+
|
|
58
|
+
# On success the generator uses stderr to say what it could not express,
|
|
59
|
+
# for example an unknown `format`. Pass that on untouched.
|
|
60
|
+
sys.stderr.write(done.stderr)
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: andvari
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Deterministic diff of two versions of a JSON Schema, and Pydantic models from one
|
|
5
|
+
Author: unpunnyfuns
|
|
6
|
+
Author-email: unpunnyfuns <unpunnyfuns@gmail.com>
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Requires-Dist: datamodel-code-generator==0.106.0
|
|
10
|
+
Requires-Python: >=3.11
|
|
11
|
+
Project-URL: Repository, https://github.com/unpunnyfuns/andvari
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
|
|
14
|
+
# andvari
|
|
15
|
+
|
|
16
|
+
Deterministic diff of two versions of a JSON Schema, and Pydantic models from one.
|
|
17
|
+
|
|
18
|
+
`andvari diff` lists what changed between two versions of a schema, with a severity for each change. `andvari models` writes Pydantic v2 models for a schema.
|
|
19
|
+
|
|
20
|
+
> Andvari was a dwarf who lived beneath a waterfall, often in the shape of a pike, and kept a hoard of gold. Loki caught him in a net and took all of it, down to the last ring. Andvari could not stop him, so he laid a curse on the ring: it would be the death of whoever owned it.
|
|
21
|
+
>
|
|
22
|
+
> After *Reginsmál* and the *Prose Edda*.
|
|
23
|
+
|
|
24
|
+
## Purpose
|
|
25
|
+
|
|
26
|
+
Use it for a schema that someone else publishes and may change without notice. Keep a copy of the schema in your repository. In CI, fetch the current schema and run andvari against the copy: any difference fails the build and prints what changed. To accept a change, replace the copy, regenerate the models, fix what no longer fits and commit.
|
|
27
|
+
|
|
28
|
+
Both commands are deterministic. They use no network and no clock, so the output depends only on the input files.
|
|
29
|
+
|
|
30
|
+
## Usage
|
|
31
|
+
|
|
32
|
+
Run `andvari diff <old.json> <new.json>`:
|
|
33
|
+
|
|
34
|
+
```text
|
|
35
|
+
$ cat old.json
|
|
36
|
+
{
|
|
37
|
+
"type": "object",
|
|
38
|
+
"required": ["id"],
|
|
39
|
+
"properties": {
|
|
40
|
+
"id": {"type": "integer"},
|
|
41
|
+
"status": {"enum": ["open", "closed"]},
|
|
42
|
+
"note": {"type": "string", "maxLength": 200}
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
$ cat new.json
|
|
46
|
+
{
|
|
47
|
+
"type": "object",
|
|
48
|
+
"required": ["id", "owner"],
|
|
49
|
+
"properties": {
|
|
50
|
+
"id": {"type": "number", "description": "Record id"},
|
|
51
|
+
"status": {"enum": ["open", "closed", "archived"]},
|
|
52
|
+
"note": {"type": "string", "maxLength": 100},
|
|
53
|
+
"owner": {"type": "string"}
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
$ andvari diff old.json new.json
|
|
57
|
+
old 26b8ae66c96141b28fa168da316f2953dee395b30c3ff7539884218f2dcb8591
|
|
58
|
+
new 87d61a59f8abf565a1c13296cb1bb8e50d8793f9a65a6cd79182aa8ad5d813f0
|
|
59
|
+
breaking /note maxLength maxLength changed
|
|
60
|
+
breaking /owner - required property added
|
|
61
|
+
warning /status enum enum loosened
|
|
62
|
+
compatible /id type type loosened
|
|
63
|
+
annotation /id description description added
|
|
64
|
+
5 changes: 2 breaking, 1 warning, 1 compatible, 1 annotation
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
The fingerprints are the SHA-256 of each schema's canonical JSON (sorted keys, no whitespace), so key order and formatting do not count as changes.
|
|
68
|
+
|
|
69
|
+
| Exit code | Meaning |
|
|
70
|
+
| --------- | -------------------------------------------------------------------------- |
|
|
71
|
+
| 0 | `diff`: same fingerprint, prints `unchanged`. `models`: file written |
|
|
72
|
+
| 1 | The schemas differ |
|
|
73
|
+
| 2 | Unreadable file, invalid JSON, schema not an object, or a `$ref` that cannot be inlined (`diff`); the generator failed (`models`); wrong arguments |
|
|
74
|
+
|
|
75
|
+
Run `andvari models <schema.json> <out.py> [--class-name NAME]` to write Pydantic v2 models. The same schema and class name always give the same file; remote `$ref`s are not fetched.
|
|
76
|
+
|
|
77
|
+
```text
|
|
78
|
+
$ cat schema.json
|
|
79
|
+
{
|
|
80
|
+
"type": "object",
|
|
81
|
+
"required": ["id"],
|
|
82
|
+
"properties": {
|
|
83
|
+
"id": {"type": "integer"},
|
|
84
|
+
"status": {"enum": ["open", "closed"]}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
$ andvari models schema.json models.py --class-name Record
|
|
88
|
+
$ cat models.py
|
|
89
|
+
# generated by andvari from a JSON Schema; do not edit
|
|
90
|
+
|
|
91
|
+
from __future__ import annotations
|
|
92
|
+
|
|
93
|
+
from enum import Enum
|
|
94
|
+
|
|
95
|
+
from pydantic import BaseModel
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class Status(Enum):
|
|
99
|
+
open = 'open'
|
|
100
|
+
closed = 'closed'
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
class Record(BaseModel):
|
|
104
|
+
id: int
|
|
105
|
+
status: Status | None = None
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
## Severity
|
|
109
|
+
|
|
110
|
+
| Change | Severity |
|
|
111
|
+
| --------------------------------------------------------- | -------------------------------------------------------------- |
|
|
112
|
+
| Path removed | breaking |
|
|
113
|
+
| Path added | breaking if required or array items, otherwise warning |
|
|
114
|
+
| `title`, `description`, `examples`, `$comment`, `default` | annotation |
|
|
115
|
+
| `required` | breaking when it becomes true, compatible when false |
|
|
116
|
+
| `type` | compatible when widened (`number` covers `integer`) or removed, otherwise breaking |
|
|
117
|
+
| `enum` | breaking when added or a value is gone, warning when values are only added, compatible when removed |
|
|
118
|
+
| `minimum`, `minLength`, `minItems`, ... and the `max` set | breaking when added or tightened, compatible when loosened or removed; a non-numeric value is breaking |
|
|
119
|
+
| Any other keyword | breaking when added, removed or changed |
|
|
120
|
+
|
|
121
|
+
## What is compared
|
|
122
|
+
|
|
123
|
+
Local `$ref`s (`#/...`) are inlined first; a remote or unresolvable `$ref` is an error. A `$ref` with sibling keywords becomes `allOf: [target, siblings]` when the two share a keyword, otherwise the siblings are merged into the target. `properties` and `items` are followed and each node gets a path (`/`, `/owner`, `/tags/*`). Every other keyword on a node is compared as a whole value.
|
|
124
|
+
|
|
125
|
+
## Limits
|
|
126
|
+
|
|
127
|
+
- It compares what the schemas say. It does not decide which data is valid.
|
|
128
|
+
- A change inside a combinator or conditional (`oneOf`, `anyOf`, `allOf`, `if`, ...) is reported as "changed", whatever its effect.
|
|
129
|
+
- Generated models can be looser than the schema, because the generator cannot express every constraint.
|
|
130
|
+
- A change to a definition nothing references changes the fingerprint but lists no change; the command still exits 1.
|
|
131
|
+
|
|
132
|
+
## Python
|
|
133
|
+
|
|
134
|
+
```python
|
|
135
|
+
from andvari import diff, fingerprint
|
|
136
|
+
|
|
137
|
+
old = {"type": "object", "properties": {"id": {"type": "integer"}}}
|
|
138
|
+
new = {"type": "object", "properties": {"id": {"type": "string"}}}
|
|
139
|
+
|
|
140
|
+
print(fingerprint(old) == fingerprint(new))
|
|
141
|
+
for change in diff(old, new):
|
|
142
|
+
print(change.severity, change.path, change.keyword, change.reason)
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
## Setup and tests
|
|
146
|
+
|
|
147
|
+
```sh
|
|
148
|
+
uv sync
|
|
149
|
+
uv run pytest
|
|
150
|
+
```
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
andvari/__init__.py,sha256=0ozykDRKvUVLgD01ZISB9HGWNMlVPFesAtFwa5Hukzg,172
|
|
2
|
+
andvari/cli.py,sha256=FLPAgHkAmEJFjtQr4eImDecl4XVXhq15dnE15aUAJiw,3425
|
|
3
|
+
andvari/diff.py,sha256=ZTKULxur_jCe1PpeaThYwtWSFYtrT9vgnv80SFj3dM4,12676
|
|
4
|
+
andvari/models.py,sha256=zg6RlLHJZlSGCTWP0d3UKeQS5NrXaBXhV5KV39w0ys0,2379
|
|
5
|
+
andvari-0.1.0.dist-info/licenses/LICENSE,sha256=xXoxW037RSjlEoqgwq_bXgdstMsJPS_2He8uihbexoE,1068
|
|
6
|
+
andvari-0.1.0.dist-info/WHEEL,sha256=kiPuyMTIXtn3KwIlb6zIkrxfbMkdQGyzN-kjAsvva48,81
|
|
7
|
+
andvari-0.1.0.dist-info/entry_points.txt,sha256=OxumwnqwBnMAaOKa7Cl1CpOu5R3LIoI4JcgcPigVxio,46
|
|
8
|
+
andvari-0.1.0.dist-info/METADATA,sha256=wpBBEL_JDErUMgkalXNqWTz8QyXm_Alew8V5kOuTXJA,6518
|
|
9
|
+
andvari-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 unpunnyfuns
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|