Repository navigation
Expand file tree
/
Copy pathbuild.py
More file actions
111 lines (92 loc) · 4 KB
/
Copy pathbuild.py
File metadata and controls
111 lines (92 loc) · 4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#!/usr/bin/env python3
"""Derive the JSON Schema document from the OpenAPI document.
The two files describe the same objects. Maintaining both by hand guarantees they drift, and a
client generated from one would then disagree with a validator built on the other — the kind of
inconsistency a standard exists to prevent. So the OpenAPI document is the source, and this script
produces the JSON Schema from it.
python protocol/schema/build.py # write the JSON Schema
python protocol/schema/build.py --check # fail if it is out of date (for CI)
`components.schemas` maps to `$defs`, and internal references are rewritten from OpenAPI's
`#/components/schemas/X` to JSON Schema's `#/$defs/X`. Nothing else is transformed: the subset of
OpenAPI 3.1 used here is JSON Schema 2020-12 by construction, which is why 3.1 was chosen.
"""
from __future__ import annotations
import json
import pathlib
import sys
try:
import yaml
except ImportError: # pragma: no cover - environment guidance, not logic
sys.exit("PyYAML is required: pip install pyyaml")
HERE = pathlib.Path(__file__).parent
VERSION = "2026-10-19"
SRC = HERE / f"uhp-{VERSION}.openapi.yaml"
OUT = HERE / f"uhp-{VERSION}.schema.json"
def rewrite_refs(node):
"""`#/components/schemas/X` (OpenAPI) -> `#/$defs/X` (JSON Schema)."""
if isinstance(node, dict):
return {
k: (v.replace("#/components/schemas/", "#/$defs/")
if k == "$ref" and isinstance(v, str) else rewrite_refs(v))
for k, v in node.items()
}
if isinstance(node, list):
return [rewrite_refs(v) for v in node]
return node
# JSON Schema keywords whose value may itself be null: `default: null` and `const: null` are schema.
_NULL_OK = frozenset({"default", "const", "example"})
def find_null_keys(node, path: str = "") -> list[str]:
"""Return paths of any mapping entry whose key is null, or whose value is null where JSON Schema
gives null no meaning.
An unquoted comma inside a YAML flow mapping (e.g. `{ type: string, description: a, b }`)
splits the scalar and leaves PyYAML with a stray `b: null` key.
"""
hits: list[str] = []
if isinstance(node, dict):
for k, v in node.items():
p = f"{path}.{k}" if path else str(k)
if k is None or (v is None and k not in _NULL_OK):
hits.append(p)
hits.extend(find_null_keys(v, p))
elif isinstance(node, list):
for i, v in enumerate(node):
hits.extend(find_null_keys(v, f"{path}[{i}]"))
return hits
def build(src: pathlib.Path | None = None) -> dict:
spec = yaml.safe_load((src if src is not None else SRC).read_text())
defs = rewrite_refs(spec["components"]["schemas"])
doc = {
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": f"https://unifiedharnessprotocol.org/schema/uhp-{VERSION}.schema.json",
"title": "Unified Harness Protocol",
"description": (
f"Object definitions for UHP {VERSION}. Generated from "
f"uhp-{VERSION}.openapi.yaml by build.py — do not edit by hand."
),
"$defs": defs,
}
null_keys = find_null_keys(doc)
if null_keys:
raise ValueError(
"null-valued key(s) in generated schema (likely an unquoted comma in a YAML flow mapping): "
+ ", ".join(null_keys)
)
return doc
def main() -> int:
try:
doc = build()
except ValueError as err:
print(str(err), file=sys.stderr)
return 1
text = json.dumps(doc, indent=2, ensure_ascii=False) + "\n"
if "--check" in sys.argv:
if not OUT.exists() or OUT.read_text() != text:
print(f"{OUT.name} is out of date — run: python protocol/schema/build.py")
return 1
print(f"{OUT.name} is up to date ({len(doc['$defs'])} definitions)")
return 0
OUT.write_text(text)
print(f"wrote {OUT.name} ({len(doc['$defs'])} definitions)")
return 0
if __name__ == "__main__":
raise SystemExit(main())