/
json_schema.py
150 lines (128 loc) · 4.89 KB
/
json_schema.py
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
from __future__ import annotations
import dataclasses
import sys
from pathlib import Path
from typing import Any, Union
from packaging.specifiers import SpecifierSet
from packaging.version import Version
from .._compat.builtins import ExceptionGroup
from .._compat.typing import Annotated, Literal, get_args, get_origin
from .documentation import pull_docs
__all__ = ["FailedConversionError", "convert_type", "to_json_schema"]
def __dir__() -> list[str]:
return __all__
class FailedConversionError(TypeError):
pass
def to_json_schema(dclass: type[Any], *, normalize_keys: bool) -> dict[str, Any]:
assert dataclasses.is_dataclass(dclass)
props = {}
errs = []
required = []
for field in dataclasses.fields(dclass):
if dataclasses.is_dataclass(field.type):
props[field.name] = to_json_schema(
field.type, normalize_keys=normalize_keys
)
continue
if get_origin(field.type) is Annotated:
if get_args(field.type)[1] == "EnvVar":
full = convert_type(
get_args(field.type)[0], normalize_keys=normalize_keys
)
types = full["patternProperties"][".+"]
full["patternProperties"][".+"] = {
"oneOf": [
types,
{
"type": "object",
"additionalProperties": False,
"required": ["env"],
"properties": {
"env": {"type": "string", "minLength": 1},
"default": types,
},
},
]
}
props[field.name] = full
continue
msg = "Only EnvVar is supported for Annotated"
raise FailedConversionError(msg)
try:
props[field.name] = convert_type(field.type, normalize_keys=normalize_keys)
except FailedConversionError as err:
if sys.version_info < (3, 11):
notes = "__notes__" # set so linter's won't try to be clever
setattr(err, notes, [*getattr(err, notes, []), f"Field: {field.name}"])
else:
# pylint: disable-next=no-member
err.add_note(f"Field: {field.name}")
errs.append(err)
continue
if field.default is not dataclasses.MISSING and field.default is not None:
props[field.name]["default"] = (
str(field.default)
if isinstance(field.default, (Version, Path, SpecifierSet))
else field.default
)
if (
field.default_factory is dataclasses.MISSING
and field.default is dataclasses.MISSING
):
required.append(field.name)
if errs:
msg = f"Failed Conversion to JSON Schema on {dclass.__name__}"
raise ExceptionGroup(msg, errs)
docs = pull_docs(dclass)
for k, v in docs.items():
props[k]["description"] = v
if "DEPRECATED" in v:
props[k]["deprecated"] = True
if normalize_keys:
props = {k.replace("_", "-"): v for k, v in props.items()}
if required:
return {
"type": "object",
"additionalProperties": False,
"required": required,
"properties": props,
}
return {"type": "object", "additionalProperties": False, "properties": props}
def convert_type(t: Any, *, normalize_keys: bool) -> dict[str, Any]:
if dataclasses.is_dataclass(t):
return to_json_schema(t, normalize_keys=normalize_keys)
if t is str or t is Path or t is Version or t is SpecifierSet:
return {"type": "string"}
if t is bool:
return {"type": "boolean"}
origin = get_origin(t)
args = get_args(t)
if origin is list:
assert len(args) == 1
return {
"type": "array",
"items": convert_type(args[0], normalize_keys=normalize_keys),
}
if origin is dict:
assert len(args) == 2
assert args[0] is str
if args[1] is Any:
return {"type": "object"}
return {
"type": "object",
"patternProperties": {
".+": convert_type(args[1], normalize_keys=normalize_keys)
},
}
if origin is Union:
# Ignore optional
if len(args) == 2 and any(a is type(None) for a in args):
return convert_type(
next(iter(a for a in args if a is not type(None))),
normalize_keys=normalize_keys,
)
return {"oneOf": [convert_type(a, normalize_keys=normalize_keys) for a in args]}
if origin is Literal:
return {"enum": list(args)}
msg = f"Cannot convert type {t} to JSON Schema"
raise FailedConversionError(msg)