andvari 0.2.0__tar.gz → 0.4.0__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.
- andvari-0.4.0/PKG-INFO +227 -0
- andvari-0.4.0/README.md +214 -0
- {andvari-0.2.0 → andvari-0.4.0}/pyproject.toml +2 -2
- {andvari-0.2.0 → andvari-0.4.0}/pyproject.toml.orig +2 -2
- andvari-0.4.0/src/andvari/__init__.py +3 -0
- {andvari-0.2.0 → andvari-0.4.0}/src/andvari/cli.py +41 -5
- {andvari-0.2.0 → andvari-0.4.0}/src/andvari/diff.py +106 -33
- andvari-0.4.0/src/andvari/migrate.py +473 -0
- andvari-0.2.0/PKG-INFO +0 -155
- andvari-0.2.0/README.md +0 -142
- andvari-0.2.0/src/andvari/__init__.py +0 -3
- {andvari-0.2.0 → andvari-0.4.0}/LICENSE +0 -0
- {andvari-0.2.0 → andvari-0.4.0}/src/andvari/models.py +0 -0
andvari-0.4.0/PKG-INFO
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: andvari
|
|
3
|
+
Version: 0.4.0
|
|
4
|
+
Summary: Deterministic diff of two versions of a JSON Schema, Pydantic models from one, and a migration scaffold between two
|
|
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, Pydantic models from one, and a migration scaffold between two.
|
|
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. `andvari migration` writes a Python file that moves stored JSON documents from the old version to the new one, with every decision left as a step to fill in.
|
|
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, write a migration for stored documents, fix what no longer fits and commit.
|
|
27
|
+
|
|
28
|
+
All three 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`, `migration`: 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`); the output file exists (`migration`); 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
|
+
Run `andvari migration <old.json> <new.json> <out.py>` to write a migration scaffold. On the `old.json` and `new.json` above:
|
|
109
|
+
|
|
110
|
+
```text
|
|
111
|
+
$ andvari migration old.json new.json migration.py
|
|
112
|
+
2 steps: 0 drop, 0 fill, 0 recursive, 2 todo
|
|
113
|
+
$ cat migration.py
|
|
114
|
+
# generated by andvari from two versions of a JSON Schema
|
|
115
|
+
#
|
|
116
|
+
# Replace each todo() with drop, fill, rename, convert or recursive, then commit it.
|
|
117
|
+
# A todo() raises when the migration runs.
|
|
118
|
+
|
|
119
|
+
from andvari.migrate import apply, todo
|
|
120
|
+
|
|
121
|
+
OLD = '26b8ae66c96141b28fa168da316f2953dee395b30c3ff7539884218f2dcb8591'
|
|
122
|
+
NEW = '87d61a59f8abf565a1c13296cb1bb8e50d8793f9a65a6cd79182aa8ad5d813f0'
|
|
123
|
+
|
|
124
|
+
STEPS = [
|
|
125
|
+
# breaking /note maxLength maxLength changed
|
|
126
|
+
# old 200
|
|
127
|
+
# new 100
|
|
128
|
+
todo('/note', 'maxLength changed'),
|
|
129
|
+
# breaking /owner - required property added
|
|
130
|
+
# new {"required":true,"type":"string"}
|
|
131
|
+
todo('/owner', 'required property added'),
|
|
132
|
+
]
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def migrate(document: dict) -> dict:
|
|
136
|
+
"""Return a copy of `document` moved from schema OLD to schema NEW."""
|
|
137
|
+
return apply(STEPS, document)
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
Replace each `todo` with a real step, then call `migrate(document)` on each stored document. It returns a migrated copy and leaves the input alone. The helpers live in `andvari.migrate`; each takes a diff path, where `*` is every element of a list, and does nothing where a document lacks the path:
|
|
141
|
+
|
|
142
|
+
| Helper | Effect |
|
|
143
|
+
| ---------------------- | ----------------------------------------------------------------------- |
|
|
144
|
+
| `drop(path)` | Deletes the value |
|
|
145
|
+
| `fill(path, value)` | Sets a copy of `value` where the parent object lacks the key; never overwrites |
|
|
146
|
+
| `rename(path, name)` | Moves the value to the key `name` beside it; raises if `name` is set |
|
|
147
|
+
| `convert(path, function)` | Replaces each value with `function(value)`; the path may end in `*` |
|
|
148
|
+
| `todo(path, reason)` | Raises `NotImplementedError` when the migration runs |
|
|
149
|
+
| `recursive(path, loops, *steps)` | Runs `steps` on each node `path` reaches (`/` is the document itself), then on each node that a path in `loops` leads to from a node, at every depth; the paths in `loops` and `steps` start at a node |
|
|
150
|
+
|
|
151
|
+
Only breaking changes get a step. The first row that matches applies:
|
|
152
|
+
|
|
153
|
+
| Change | Step |
|
|
154
|
+
| --------------------------------------------------------- | ------------------------------------------ |
|
|
155
|
+
| Annotation, compatible or warning | none |
|
|
156
|
+
| At `/`, at a path ending in `/*`, or at or inside a combinator branch | `todo` |
|
|
157
|
+
| Below a path whose `type` changed in a breaking way | `todo` |
|
|
158
|
+
| Path removed | `drop` |
|
|
159
|
+
| Required property added, or `required` became true | `fill` with the new `default`, else `todo` |
|
|
160
|
+
| Anything else | `todo` |
|
|
161
|
+
|
|
162
|
+
A recursive schema keeps a `$ref` in place where it refers back into itself, such as `{"items": {"$ref": "#"}}`. For each path where both versions keep the same `$ref`, the definition it points at is compared on its own, with paths relative to the definition, and its breaking changes get steps by the table above. After the other steps, these go into one `recursive` step at that path, with the paths inside the definition where both versions refer back to it as `loops`. A definition with no breaking change gets no step. The summary line counts top-level steps only: `N steps: a drop, b fill, c recursive, d todo`.
|
|
163
|
+
|
|
164
|
+
- It never overwrites `out.py`. Delete the file to generate it again.
|
|
165
|
+
- Data does not record which branch it matched, so a step inside a `oneOf`, `anyOf` or `allOf` branch is always `todo`.
|
|
166
|
+
- It does not check that a migrated document is valid against the new schema.
|
|
167
|
+
- A migration only makes sense on documents at schema `OLD`. The tool does not record which version a document is at.
|
|
168
|
+
|
|
169
|
+
## Severity
|
|
170
|
+
|
|
171
|
+
| Change | Severity |
|
|
172
|
+
| --------------------------------------------------------- | -------------------------------------------------------------- |
|
|
173
|
+
| Path removed | breaking |
|
|
174
|
+
| Path added | breaking if required or array items, otherwise warning |
|
|
175
|
+
| `title`, `description`, `examples`, `$comment`, `default` | annotation |
|
|
176
|
+
| `required` | breaking when it becomes true, compatible when false |
|
|
177
|
+
| `type` | compatible when widened (`number` covers `integer`) or removed, otherwise breaking |
|
|
178
|
+
| `enum` | breaking when added or a value is gone, warning when values are only added, compatible when removed |
|
|
179
|
+
| `minimum`, `minLength`, `minItems`, ... and the `max` set | breaking when added or tightened, compatible when loosened or removed; a non-numeric value is breaking |
|
|
180
|
+
| `oneOf` / `anyOf` branch | warning when added, breaking when removed |
|
|
181
|
+
| `allOf` branch | breaking when added, compatible when removed |
|
|
182
|
+
| `oneOf`, `anyOf`, `allOf` on an existing node | breaking when added, compatible when removed; one change, branches not listed |
|
|
183
|
+
| Any other keyword | breaking when added, removed or changed |
|
|
184
|
+
|
|
185
|
+
## What is compared
|
|
186
|
+
|
|
187
|
+
Local `$ref`s (`#/...`) are inlined first; a remote or unresolvable `$ref` is an error. A `$ref` with sibling keywords becomes `allOf: [target, siblings]` when a keyword the two share has different values, otherwise the siblings are merged into the target. `properties`, `items` and the branches of a non-empty `oneOf`, `anyOf` or `allOf` list are followed and each node gets a path (`/`, `/owner`, `/tags/*`, `/pet/oneOf:cat`, `/pet/oneOf:cat/name`). A branch is labelled by its `const` (a non-string value in canonical JSON), else by a string `title`, else by its index; if two labels in one list are equal, every branch in that list uses its index. Every other keyword on a node is compared as a whole value.
|
|
188
|
+
|
|
189
|
+
## Limits
|
|
190
|
+
|
|
191
|
+
- It compares what the schemas say. It does not decide which data is valid.
|
|
192
|
+
- A change inside a keyword that is not followed (`not`, `if`/`then`/`else`, `prefixItems`, `additionalProperties`, ...) is reported as "changed", whatever its effect.
|
|
193
|
+
- An added `oneOf` branch is rated warning, although data that now matches two branches is rejected.
|
|
194
|
+
- Branches without `const` or `title` are matched by position, so inserting one before others reports the later ones as changed.
|
|
195
|
+
- Generated models can be looser than the schema, because the generator cannot express every constraint.
|
|
196
|
+
- A change to a definition nothing references changes the fingerprint but lists no change; the command still exits 1.
|
|
197
|
+
- A recursive definition is compared once on its own, and recursion nested inside it is not planned further. Its steps become one `todo` instead of `recursive` when the path is at or inside a combinator branch, when a loop is, when no loop is the same in both versions, or when the definition holds a different `$ref` that refers back (a second recursion inside the first). A `$ref` that refers back from inside a keyword that is not followed, such as `additionalProperties` or `prefixItems`, gives a `todo` at the path holding that keyword, because no step can reach the levels below it.
|
|
198
|
+
|
|
199
|
+
## Python
|
|
200
|
+
|
|
201
|
+
```python
|
|
202
|
+
from andvari import diff, fingerprint
|
|
203
|
+
|
|
204
|
+
old = {"type": "object", "properties": {"id": {"type": "integer"}}}
|
|
205
|
+
new = {"type": "object", "properties": {"id": {"type": "string"}}}
|
|
206
|
+
|
|
207
|
+
print(fingerprint(old) == fingerprint(new))
|
|
208
|
+
for change in diff(old, new):
|
|
209
|
+
print(change.severity, change.path, change.keyword, change.reason, change.old, change.new)
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
Each change carries what was there before and after:
|
|
213
|
+
|
|
214
|
+
| Change to | `old` and `new` |
|
|
215
|
+
| ------------------- | ----------------------------------------------------------- |
|
|
216
|
+
| A keyword | Its two values |
|
|
217
|
+
| A whole path | The path's row from `flatten`: its keywords and a `required` flag |
|
|
218
|
+
| A whole combinator | Its branches, as `path -> row` |
|
|
219
|
+
|
|
220
|
+
The side with nothing is `andvari.MISSING`, because `None` is a value a schema can hold. The command line output does not show these values.
|
|
221
|
+
|
|
222
|
+
## Setup and tests
|
|
223
|
+
|
|
224
|
+
```sh
|
|
225
|
+
uv sync
|
|
226
|
+
uv run pytest
|
|
227
|
+
```
|
andvari-0.4.0/README.md
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
# andvari
|
|
2
|
+
|
|
3
|
+
Deterministic diff of two versions of a JSON Schema, Pydantic models from one, and a migration scaffold between two.
|
|
4
|
+
|
|
5
|
+
`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. `andvari migration` writes a Python file that moves stored JSON documents from the old version to the new one, with every decision left as a step to fill in.
|
|
6
|
+
|
|
7
|
+
> 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.
|
|
8
|
+
>
|
|
9
|
+
> After *Reginsmál* and the *Prose Edda*.
|
|
10
|
+
|
|
11
|
+
## Purpose
|
|
12
|
+
|
|
13
|
+
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, write a migration for stored documents, fix what no longer fits and commit.
|
|
14
|
+
|
|
15
|
+
All three commands are deterministic. They use no network and no clock, so the output depends only on the input files.
|
|
16
|
+
|
|
17
|
+
## Usage
|
|
18
|
+
|
|
19
|
+
Run `andvari diff <old.json> <new.json>`:
|
|
20
|
+
|
|
21
|
+
```text
|
|
22
|
+
$ cat old.json
|
|
23
|
+
{
|
|
24
|
+
"type": "object",
|
|
25
|
+
"required": ["id"],
|
|
26
|
+
"properties": {
|
|
27
|
+
"id": {"type": "integer"},
|
|
28
|
+
"status": {"enum": ["open", "closed"]},
|
|
29
|
+
"note": {"type": "string", "maxLength": 200}
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
$ cat new.json
|
|
33
|
+
{
|
|
34
|
+
"type": "object",
|
|
35
|
+
"required": ["id", "owner"],
|
|
36
|
+
"properties": {
|
|
37
|
+
"id": {"type": "number", "description": "Record id"},
|
|
38
|
+
"status": {"enum": ["open", "closed", "archived"]},
|
|
39
|
+
"note": {"type": "string", "maxLength": 100},
|
|
40
|
+
"owner": {"type": "string"}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
$ andvari diff old.json new.json
|
|
44
|
+
old 26b8ae66c96141b28fa168da316f2953dee395b30c3ff7539884218f2dcb8591
|
|
45
|
+
new 87d61a59f8abf565a1c13296cb1bb8e50d8793f9a65a6cd79182aa8ad5d813f0
|
|
46
|
+
breaking /note maxLength maxLength changed
|
|
47
|
+
breaking /owner - required property added
|
|
48
|
+
warning /status enum enum loosened
|
|
49
|
+
compatible /id type type loosened
|
|
50
|
+
annotation /id description description added
|
|
51
|
+
5 changes: 2 breaking, 1 warning, 1 compatible, 1 annotation
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
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.
|
|
55
|
+
|
|
56
|
+
| Exit code | Meaning |
|
|
57
|
+
| --------- | -------------------------------------------------------------------------- |
|
|
58
|
+
| 0 | `diff`: same fingerprint, prints `unchanged`. `models`, `migration`: file written |
|
|
59
|
+
| 1 | The schemas differ |
|
|
60
|
+
| 2 | Unreadable file, invalid JSON, schema not an object, or a `$ref` that cannot be inlined (`diff`); the generator failed (`models`); the output file exists (`migration`); wrong arguments |
|
|
61
|
+
|
|
62
|
+
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.
|
|
63
|
+
|
|
64
|
+
```text
|
|
65
|
+
$ cat schema.json
|
|
66
|
+
{
|
|
67
|
+
"type": "object",
|
|
68
|
+
"required": ["id"],
|
|
69
|
+
"properties": {
|
|
70
|
+
"id": {"type": "integer"},
|
|
71
|
+
"status": {"enum": ["open", "closed"]}
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
$ andvari models schema.json models.py --class-name Record
|
|
75
|
+
$ cat models.py
|
|
76
|
+
# generated by andvari from a JSON Schema; do not edit
|
|
77
|
+
|
|
78
|
+
from __future__ import annotations
|
|
79
|
+
|
|
80
|
+
from enum import Enum
|
|
81
|
+
|
|
82
|
+
from pydantic import BaseModel
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class Status(Enum):
|
|
86
|
+
open = 'open'
|
|
87
|
+
closed = 'closed'
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class Record(BaseModel):
|
|
91
|
+
id: int
|
|
92
|
+
status: Status | None = None
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
Run `andvari migration <old.json> <new.json> <out.py>` to write a migration scaffold. On the `old.json` and `new.json` above:
|
|
96
|
+
|
|
97
|
+
```text
|
|
98
|
+
$ andvari migration old.json new.json migration.py
|
|
99
|
+
2 steps: 0 drop, 0 fill, 0 recursive, 2 todo
|
|
100
|
+
$ cat migration.py
|
|
101
|
+
# generated by andvari from two versions of a JSON Schema
|
|
102
|
+
#
|
|
103
|
+
# Replace each todo() with drop, fill, rename, convert or recursive, then commit it.
|
|
104
|
+
# A todo() raises when the migration runs.
|
|
105
|
+
|
|
106
|
+
from andvari.migrate import apply, todo
|
|
107
|
+
|
|
108
|
+
OLD = '26b8ae66c96141b28fa168da316f2953dee395b30c3ff7539884218f2dcb8591'
|
|
109
|
+
NEW = '87d61a59f8abf565a1c13296cb1bb8e50d8793f9a65a6cd79182aa8ad5d813f0'
|
|
110
|
+
|
|
111
|
+
STEPS = [
|
|
112
|
+
# breaking /note maxLength maxLength changed
|
|
113
|
+
# old 200
|
|
114
|
+
# new 100
|
|
115
|
+
todo('/note', 'maxLength changed'),
|
|
116
|
+
# breaking /owner - required property added
|
|
117
|
+
# new {"required":true,"type":"string"}
|
|
118
|
+
todo('/owner', 'required property added'),
|
|
119
|
+
]
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def migrate(document: dict) -> dict:
|
|
123
|
+
"""Return a copy of `document` moved from schema OLD to schema NEW."""
|
|
124
|
+
return apply(STEPS, document)
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
Replace each `todo` with a real step, then call `migrate(document)` on each stored document. It returns a migrated copy and leaves the input alone. The helpers live in `andvari.migrate`; each takes a diff path, where `*` is every element of a list, and does nothing where a document lacks the path:
|
|
128
|
+
|
|
129
|
+
| Helper | Effect |
|
|
130
|
+
| ---------------------- | ----------------------------------------------------------------------- |
|
|
131
|
+
| `drop(path)` | Deletes the value |
|
|
132
|
+
| `fill(path, value)` | Sets a copy of `value` where the parent object lacks the key; never overwrites |
|
|
133
|
+
| `rename(path, name)` | Moves the value to the key `name` beside it; raises if `name` is set |
|
|
134
|
+
| `convert(path, function)` | Replaces each value with `function(value)`; the path may end in `*` |
|
|
135
|
+
| `todo(path, reason)` | Raises `NotImplementedError` when the migration runs |
|
|
136
|
+
| `recursive(path, loops, *steps)` | Runs `steps` on each node `path` reaches (`/` is the document itself), then on each node that a path in `loops` leads to from a node, at every depth; the paths in `loops` and `steps` start at a node |
|
|
137
|
+
|
|
138
|
+
Only breaking changes get a step. The first row that matches applies:
|
|
139
|
+
|
|
140
|
+
| Change | Step |
|
|
141
|
+
| --------------------------------------------------------- | ------------------------------------------ |
|
|
142
|
+
| Annotation, compatible or warning | none |
|
|
143
|
+
| At `/`, at a path ending in `/*`, or at or inside a combinator branch | `todo` |
|
|
144
|
+
| Below a path whose `type` changed in a breaking way | `todo` |
|
|
145
|
+
| Path removed | `drop` |
|
|
146
|
+
| Required property added, or `required` became true | `fill` with the new `default`, else `todo` |
|
|
147
|
+
| Anything else | `todo` |
|
|
148
|
+
|
|
149
|
+
A recursive schema keeps a `$ref` in place where it refers back into itself, such as `{"items": {"$ref": "#"}}`. For each path where both versions keep the same `$ref`, the definition it points at is compared on its own, with paths relative to the definition, and its breaking changes get steps by the table above. After the other steps, these go into one `recursive` step at that path, with the paths inside the definition where both versions refer back to it as `loops`. A definition with no breaking change gets no step. The summary line counts top-level steps only: `N steps: a drop, b fill, c recursive, d todo`.
|
|
150
|
+
|
|
151
|
+
- It never overwrites `out.py`. Delete the file to generate it again.
|
|
152
|
+
- Data does not record which branch it matched, so a step inside a `oneOf`, `anyOf` or `allOf` branch is always `todo`.
|
|
153
|
+
- It does not check that a migrated document is valid against the new schema.
|
|
154
|
+
- A migration only makes sense on documents at schema `OLD`. The tool does not record which version a document is at.
|
|
155
|
+
|
|
156
|
+
## Severity
|
|
157
|
+
|
|
158
|
+
| Change | Severity |
|
|
159
|
+
| --------------------------------------------------------- | -------------------------------------------------------------- |
|
|
160
|
+
| Path removed | breaking |
|
|
161
|
+
| Path added | breaking if required or array items, otherwise warning |
|
|
162
|
+
| `title`, `description`, `examples`, `$comment`, `default` | annotation |
|
|
163
|
+
| `required` | breaking when it becomes true, compatible when false |
|
|
164
|
+
| `type` | compatible when widened (`number` covers `integer`) or removed, otherwise breaking |
|
|
165
|
+
| `enum` | breaking when added or a value is gone, warning when values are only added, compatible when removed |
|
|
166
|
+
| `minimum`, `minLength`, `minItems`, ... and the `max` set | breaking when added or tightened, compatible when loosened or removed; a non-numeric value is breaking |
|
|
167
|
+
| `oneOf` / `anyOf` branch | warning when added, breaking when removed |
|
|
168
|
+
| `allOf` branch | breaking when added, compatible when removed |
|
|
169
|
+
| `oneOf`, `anyOf`, `allOf` on an existing node | breaking when added, compatible when removed; one change, branches not listed |
|
|
170
|
+
| Any other keyword | breaking when added, removed or changed |
|
|
171
|
+
|
|
172
|
+
## What is compared
|
|
173
|
+
|
|
174
|
+
Local `$ref`s (`#/...`) are inlined first; a remote or unresolvable `$ref` is an error. A `$ref` with sibling keywords becomes `allOf: [target, siblings]` when a keyword the two share has different values, otherwise the siblings are merged into the target. `properties`, `items` and the branches of a non-empty `oneOf`, `anyOf` or `allOf` list are followed and each node gets a path (`/`, `/owner`, `/tags/*`, `/pet/oneOf:cat`, `/pet/oneOf:cat/name`). A branch is labelled by its `const` (a non-string value in canonical JSON), else by a string `title`, else by its index; if two labels in one list are equal, every branch in that list uses its index. Every other keyword on a node is compared as a whole value.
|
|
175
|
+
|
|
176
|
+
## Limits
|
|
177
|
+
|
|
178
|
+
- It compares what the schemas say. It does not decide which data is valid.
|
|
179
|
+
- A change inside a keyword that is not followed (`not`, `if`/`then`/`else`, `prefixItems`, `additionalProperties`, ...) is reported as "changed", whatever its effect.
|
|
180
|
+
- An added `oneOf` branch is rated warning, although data that now matches two branches is rejected.
|
|
181
|
+
- Branches without `const` or `title` are matched by position, so inserting one before others reports the later ones as changed.
|
|
182
|
+
- Generated models can be looser than the schema, because the generator cannot express every constraint.
|
|
183
|
+
- A change to a definition nothing references changes the fingerprint but lists no change; the command still exits 1.
|
|
184
|
+
- A recursive definition is compared once on its own, and recursion nested inside it is not planned further. Its steps become one `todo` instead of `recursive` when the path is at or inside a combinator branch, when a loop is, when no loop is the same in both versions, or when the definition holds a different `$ref` that refers back (a second recursion inside the first). A `$ref` that refers back from inside a keyword that is not followed, such as `additionalProperties` or `prefixItems`, gives a `todo` at the path holding that keyword, because no step can reach the levels below it.
|
|
185
|
+
|
|
186
|
+
## Python
|
|
187
|
+
|
|
188
|
+
```python
|
|
189
|
+
from andvari import diff, fingerprint
|
|
190
|
+
|
|
191
|
+
old = {"type": "object", "properties": {"id": {"type": "integer"}}}
|
|
192
|
+
new = {"type": "object", "properties": {"id": {"type": "string"}}}
|
|
193
|
+
|
|
194
|
+
print(fingerprint(old) == fingerprint(new))
|
|
195
|
+
for change in diff(old, new):
|
|
196
|
+
print(change.severity, change.path, change.keyword, change.reason, change.old, change.new)
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
Each change carries what was there before and after:
|
|
200
|
+
|
|
201
|
+
| Change to | `old` and `new` |
|
|
202
|
+
| ------------------- | ----------------------------------------------------------- |
|
|
203
|
+
| A keyword | Its two values |
|
|
204
|
+
| A whole path | The path's row from `flatten`: its keywords and a `required` flag |
|
|
205
|
+
| A whole combinator | Its branches, as `path -> row` |
|
|
206
|
+
|
|
207
|
+
The side with nothing is `andvari.MISSING`, because `None` is a value a schema can hold. The command line output does not show these values.
|
|
208
|
+
|
|
209
|
+
## Setup and tests
|
|
210
|
+
|
|
211
|
+
```sh
|
|
212
|
+
uv sync
|
|
213
|
+
uv run pytest
|
|
214
|
+
```
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "andvari"
|
|
3
|
-
version = "0.
|
|
4
|
-
description = "Deterministic diff of two versions of a JSON Schema,
|
|
3
|
+
version = "0.4.0"
|
|
4
|
+
description = "Deterministic diff of two versions of a JSON Schema, Pydantic models from one, and a migration scaffold between two"
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
license = "MIT"
|
|
7
7
|
license-files = ["LICENSE"]
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "andvari"
|
|
3
|
-
version = "0.
|
|
4
|
-
description = "Deterministic diff of two versions of a JSON Schema,
|
|
3
|
+
version = "0.4.0"
|
|
4
|
+
description = "Deterministic diff of two versions of a JSON Schema, Pydantic models from one, and a migration scaffold between two"
|
|
5
5
|
authors = [
|
|
6
6
|
{ name = "unpunnyfuns", email = "unpunnyfuns@gmail.com" }
|
|
7
7
|
]
|
|
@@ -2,8 +2,9 @@
|
|
|
2
2
|
|
|
3
3
|
andvari diff <old.json> <new.json>
|
|
4
4
|
andvari models <schema.json> <out.py> [--class-name NAME]
|
|
5
|
+
andvari migration <old.json> <new.json> <out.py>
|
|
5
6
|
|
|
6
|
-
Exit codes: 0 for no difference (or
|
|
7
|
+
Exit codes: 0 for no difference (or a file written), 1 when the two schemas
|
|
7
8
|
differ, 2 when something went wrong. A CI job only needs the exit code.
|
|
8
9
|
"""
|
|
9
10
|
|
|
@@ -11,13 +12,21 @@ import json
|
|
|
11
12
|
import sys
|
|
12
13
|
from pathlib import Path
|
|
13
14
|
|
|
14
|
-
from andvari.diff import Change, SchemaError, diff, fingerprint
|
|
15
|
+
from andvari.diff import Change, SchemaError, describe, diff, fingerprint, one_line
|
|
16
|
+
from andvari.migrate import plan, render
|
|
15
17
|
from andvari.models import generate
|
|
16
18
|
|
|
17
19
|
# The order in which changes are printed and counted: most serious first.
|
|
18
20
|
SEVERITIES = ("breaking", "warning", "compatible", "annotation")
|
|
19
21
|
|
|
20
|
-
USAGE =
|
|
22
|
+
USAGE = (
|
|
23
|
+
"usage: andvari diff <old> <new> | andvari models <schema> <out.py> [--class-name NAME]"
|
|
24
|
+
" | andvari migration <old> <new> <out.py>"
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
# The helpers a migration step can start out as, in the order they are counted.
|
|
28
|
+
# Steps inside a `recursive` one are not counted on their own.
|
|
29
|
+
HELPERS = ("drop", "fill", "recursive", "todo")
|
|
21
30
|
|
|
22
31
|
# Printed when the fingerprints differ but the comparison found nothing. That
|
|
23
32
|
# happens when the only difference is in a definition that nothing refers to.
|
|
@@ -56,7 +65,7 @@ def report(old: dict, new: dict, changes: list[Change]) -> int:
|
|
|
56
65
|
return 0
|
|
57
66
|
|
|
58
67
|
for change in changes:
|
|
59
|
-
print(
|
|
68
|
+
print(describe(change))
|
|
60
69
|
|
|
61
70
|
if not changes:
|
|
62
71
|
print(UNLISTED)
|
|
@@ -81,6 +90,31 @@ def run_diff(args: list[str]) -> int:
|
|
|
81
90
|
return report(old, new, changes)
|
|
82
91
|
|
|
83
92
|
|
|
93
|
+
def run_migration(args: list[str]) -> int:
|
|
94
|
+
"""Handle `andvari migration <old> <new> <out.py>`."""
|
|
95
|
+
if len(args) != 3:
|
|
96
|
+
raise SchemaError(USAGE)
|
|
97
|
+
old, new = load(args[0]), load(args[1])
|
|
98
|
+
steps = plan(old, new)
|
|
99
|
+
text = render(old, new, steps)
|
|
100
|
+
|
|
101
|
+
# People edit this file by hand, so writing over it would destroy their
|
|
102
|
+
# work. Mode "x" refuses an existing file in the same call that creates
|
|
103
|
+
# it, leaving no moment between a check and the write. A fixed newline
|
|
104
|
+
# keeps the file the same byte for byte on every platform.
|
|
105
|
+
try:
|
|
106
|
+
with Path(args[2]).open("x", encoding="utf-8", newline="\n") as file:
|
|
107
|
+
file.write(text)
|
|
108
|
+
except FileExistsError:
|
|
109
|
+
raise SchemaError(f"{args[2]} exists; remove it first to write a new one") from None
|
|
110
|
+
|
|
111
|
+
counts = ", ".join(
|
|
112
|
+
f"{sum(helper == name for helper, _, _ in steps)} {name}" for name in HELPERS
|
|
113
|
+
)
|
|
114
|
+
print(f"{len(steps)} steps: {counts}")
|
|
115
|
+
return 0
|
|
116
|
+
|
|
117
|
+
|
|
84
118
|
def main(argv: list[str] | None = None) -> int:
|
|
85
119
|
"""Run the command line and return the exit code."""
|
|
86
120
|
args = sys.argv[1:] if argv is None else argv
|
|
@@ -89,9 +123,11 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
89
123
|
return run_models(args[1:])
|
|
90
124
|
if args[:1] == ["diff"]:
|
|
91
125
|
return run_diff(args[1:])
|
|
126
|
+
if args[:1] == ["migration"]:
|
|
127
|
+
return run_migration(args[1:])
|
|
92
128
|
raise SchemaError(USAGE)
|
|
93
129
|
except (OSError, ValueError, SchemaError) as error:
|
|
94
130
|
# Every failure is reported the same way: one line on stderr, exit 2,
|
|
95
131
|
# and nothing on stdout that a script could mistake for a result.
|
|
96
|
-
print(f"error: {error}", file=sys.stderr)
|
|
132
|
+
print(one_line(f"error: {error}"), file=sys.stderr)
|
|
97
133
|
return 2
|