JSONSchema2PoPo2 3.0.2__py3-none-any.whl → 3.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.
- jsonschema2popo/__init__.py +1 -1
- jsonschema2popo/classes.py +13 -0
- jsonschema2popo/go/go.py +4 -1
- jsonschema2popo/go/go_struct.tmpl +4 -4
- jsonschema2popo/js/js.py +14 -1
- jsonschema2popo/js/js_class.tmpl +11 -23
- jsonschema2popo/jsonschema2popo.py +208 -4
- jsonschema2popo/python/python.py +4 -1
- jsonschema2popo/python/python_class.tmpl +7 -7
- {JSONSchema2PoPo2-3.0.2.dist-info → jsonschema2popo2-3.1.0.dist-info}/METADATA +22 -11
- jsonschema2popo2-3.1.0.dist-info/RECORD +19 -0
- {JSONSchema2PoPo2-3.0.2.dist-info → jsonschema2popo2-3.1.0.dist-info}/WHEEL +1 -1
- {JSONSchema2PoPo2-3.0.2.dist-info → jsonschema2popo2-3.1.0.dist-info}/entry_points.txt +0 -1
- JSONSchema2PoPo2-3.0.2.dist-info/RECORD +0 -19
- {JSONSchema2PoPo2-3.0.2.dist-info → jsonschema2popo2-3.1.0.dist-info/licenses}/LICENSE.txt +0 -0
- {JSONSchema2PoPo2-3.0.2.dist-info → jsonschema2popo2-3.1.0.dist-info}/top_level.txt +0 -0
jsonschema2popo/__init__.py
CHANGED
jsonschema2popo/classes.py
CHANGED
|
@@ -1,10 +1,16 @@
|
|
|
1
1
|
import abc
|
|
2
2
|
import argparse
|
|
3
|
+
import re
|
|
3
4
|
from typing import Dict, Any, List, Set, Optional, Callable, Type
|
|
4
5
|
|
|
5
6
|
extra_generation_options = dict()
|
|
6
7
|
|
|
7
8
|
|
|
9
|
+
def is_identifier(name: str) -> bool:
|
|
10
|
+
"""Unicode letters, digits and '_', not starting with a digit. Never matches quotes, operators or whitespace."""
|
|
11
|
+
return name.isidentifier() or re.fullmatch(r"[^\W\d]\w*", name) is not None
|
|
12
|
+
|
|
13
|
+
|
|
8
14
|
def translate_properties():
|
|
9
15
|
return extra_generation_options.get("translate_properties", False)
|
|
10
16
|
|
|
@@ -311,5 +317,12 @@ class CodeGenPlugin(abc.ABC):
|
|
|
311
317
|
def extra_jinja_inputs(self) -> Dict[str, Any]:
|
|
312
318
|
return {}
|
|
313
319
|
|
|
320
|
+
def is_valid_identifier(self, name: str, enum_member: bool = False) -> bool:
|
|
321
|
+
"""
|
|
322
|
+
Whether a name from the schema can be emitted as an identifier by this plugin's template. Plugins that
|
|
323
|
+
emit names as identifiers should reject anything that could end one (quotes, operators, whitespace...).
|
|
324
|
+
"""
|
|
325
|
+
return True
|
|
326
|
+
|
|
314
327
|
def after_generation(self, filename: Optional[str] = None) -> None:
|
|
315
328
|
pass
|
jsonschema2popo/go/go.py
CHANGED
|
@@ -3,7 +3,7 @@ import os
|
|
|
3
3
|
from typing import Dict, Callable, Any
|
|
4
4
|
|
|
5
5
|
from jsonschema2popo import version
|
|
6
|
-
from jsonschema2popo.classes import CodeGenPlugin
|
|
6
|
+
from jsonschema2popo.classes import CodeGenPlugin, is_identifier
|
|
7
7
|
from jsonschema2popo.python.python import Python
|
|
8
8
|
|
|
9
9
|
|
|
@@ -27,6 +27,9 @@ class Go(CodeGenPlugin):
|
|
|
27
27
|
def extra_jinja_inputs(self) -> Dict[str, Any]:
|
|
28
28
|
return {"package_name": self.package_name}
|
|
29
29
|
|
|
30
|
+
def is_valid_identifier(self, name: str, enum_member: bool = False) -> bool:
|
|
31
|
+
return is_identifier(name)
|
|
32
|
+
|
|
30
33
|
def template(self) -> str:
|
|
31
34
|
return "go_struct.tmpl"
|
|
32
35
|
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
{{ (model.full_name_python_path()) | replace(".", "")}}
|
|
6
6
|
{%- endmacro -%}
|
|
7
7
|
{% macro translate_bool(bool) %}{% if bool is sameas True %}true{% elif bool is sameas False %}false{% elif bool is none
|
|
8
|
-
%}nil{% elif bool is number %}int64({{bool}}){% else %}{{ bool }}{% endif %}{% endmacro %}
|
|
8
|
+
%}nil{% elif bool is number %}int64({{bool}}){% else %}{{ bool | json_value }}{% endif %}{% endmacro %}
|
|
9
9
|
|
|
10
10
|
{%- macro translate_type(prop) -%}
|
|
11
11
|
{% if prop is string %}
|
|
@@ -44,13 +44,13 @@ package {{package_name}}
|
|
|
44
44
|
{% if not model.type == "enum" %}
|
|
45
45
|
var {{go_name(model)}}Formats = map[string]string {
|
|
46
46
|
{% for prop in model.properties if prop.format %}
|
|
47
|
-
"{{trn(prop.name)}}":
|
|
47
|
+
"{{trn(prop.name)}}": {{ prop.format | json_quote('"', 'go') }},
|
|
48
48
|
{% endfor %}
|
|
49
49
|
}
|
|
50
50
|
var {{go_name(model)}}Validations = map[string]map[string]interface{} {
|
|
51
51
|
{% for prop in model.properties if prop.validations %}
|
|
52
52
|
"{{ trn(prop.name) }}": { {% for type, value in prop.validations.items() %}"{{ type }}": {% if type ==
|
|
53
|
-
"pattern" %}
|
|
53
|
+
"pattern" %}{{ value | string | json_literal }}{% else %}{{ translate_bool(value) }}{%endif%},{% endfor %}},
|
|
54
54
|
{% endfor %}
|
|
55
55
|
}
|
|
56
56
|
|
|
@@ -83,7 +83,7 @@ var {{ go_name(model) }}Options = struct{
|
|
|
83
83
|
{% endfor %}
|
|
84
84
|
}{
|
|
85
85
|
{% for name, value in model.values.items() %}
|
|
86
|
-
{{name}}: {% if model.value_type.type == "string" %}
|
|
86
|
+
{{name}}: {% if model.value_type.type == "string" %}{{ value | json_quote('"', 'go') }}{% else %}{{ value | json_value }}{% endif %},
|
|
87
87
|
|
|
88
88
|
{% endfor %}
|
|
89
89
|
|
jsonschema2popo/js/js.py
CHANGED
|
@@ -1,9 +1,16 @@
|
|
|
1
1
|
import argparse
|
|
2
2
|
import os
|
|
3
|
+
import re
|
|
3
4
|
from typing import Union, Dict, Callable, Any
|
|
4
5
|
|
|
5
6
|
from jsonschema2popo import version
|
|
6
|
-
from jsonschema2popo.classes import
|
|
7
|
+
from jsonschema2popo.classes import (
|
|
8
|
+
Definition,
|
|
9
|
+
ListNode,
|
|
10
|
+
ReferenceNode,
|
|
11
|
+
CodeGenPlugin,
|
|
12
|
+
is_identifier,
|
|
13
|
+
)
|
|
7
14
|
from jsonschema2popo.jsonschema2popo import string_to_type
|
|
8
15
|
from jsonschema2popo.python.python import Python
|
|
9
16
|
|
|
@@ -42,6 +49,12 @@ class JS(CodeGenPlugin):
|
|
|
42
49
|
def template(self) -> str:
|
|
43
50
|
return "js_class.tmpl"
|
|
44
51
|
|
|
52
|
+
def is_valid_identifier(self, name: str, enum_member: bool = False) -> bool:
|
|
53
|
+
# JS identifiers may contain '$', and enum member names are object keys, which may also be numbers
|
|
54
|
+
if enum_member and re.fullmatch(r"\d+(\.\d*)?([eE][+-]?\d+)?", name):
|
|
55
|
+
return True
|
|
56
|
+
return is_identifier(name.replace("$", "_"))
|
|
57
|
+
|
|
45
58
|
def jinja_globals(self) -> Dict[str, Callable]:
|
|
46
59
|
return {"jsdoc_type": self.jsdoc_type, "python_type": Python.python_type}
|
|
47
60
|
|
jsonschema2popo/js/js_class.tmpl
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
or prop.definition, relative_to=relativeTo, with_namespace=withNamespace)) }}{% if get_type(prop, sub=False, module=True) == "Array" %}[]{% endif %}{% raw %}}{% endraw %}
|
|
6
6
|
{%- endmacro -%}
|
|
7
7
|
{% macro jsdoc_param(name, prop) %}
|
|
8
|
-
@param {{ name }} {{ jsdoc_typ(prop, withNamespace=True) }} {% if prop.comment %}{{ prop.comment | indent(7) }}{% endif %}
|
|
8
|
+
@param {{ name }} {{ jsdoc_typ(prop, withNamespace=True) }} {% if prop.comment %}{{ prop.comment | block_comment | indent(7) }}{% endif %}
|
|
9
9
|
{% endmacro %}
|
|
10
10
|
{%- macro translate_type(type, module=False) -%}
|
|
11
11
|
{%- if type is none -%}
|
|
@@ -39,18 +39,6 @@ typeof {{ var }} === "number"
|
|
|
39
39
|
{%- endif -%}
|
|
40
40
|
{%- endmacro -%}
|
|
41
41
|
|
|
42
|
-
{% macro translate_bool(bool) %}
|
|
43
|
-
{% if bool is sameas True %}
|
|
44
|
-
true
|
|
45
|
-
{% elif bool is sameas False %}
|
|
46
|
-
false
|
|
47
|
-
{% elif bool is none %}
|
|
48
|
-
null
|
|
49
|
-
{% else %}
|
|
50
|
-
{{ bool }}
|
|
51
|
-
{% endif %}
|
|
52
|
-
{% endmacro %}
|
|
53
|
-
|
|
54
42
|
{% macro get_type(prop, relativeTo=None, sub=True, module=False) -%}{{ translate_type(python_type(sub and prop.definition|attr("item_type") or prop.definition or None, relative_to=relativeTo))-}}{%-
|
|
55
43
|
endmacro -%}
|
|
56
44
|
{% macro type_check(prop, name=None, relativeTo=None) %}
|
|
@@ -68,7 +56,7 @@ if ({{ name or trn(prop.name) }} !== null && !{{ name or trn(prop.name) }}.every
|
|
|
68
56
|
|
|
69
57
|
{%- macro generate_class(model) -%}
|
|
70
58
|
/**
|
|
71
|
-
* {% if model.comment %}{{ model.comment | indent(3) }}{% endif %}
|
|
59
|
+
* {% if model.comment %}{{ model.comment | block_comment | indent(3) }}{% endif %}
|
|
72
60
|
|
|
73
61
|
*
|
|
74
62
|
* @class
|
|
@@ -88,7 +76,7 @@ class {{model.python_type_name}}{% if model.extends %} extends {{ model.extends
|
|
|
88
76
|
*/
|
|
89
77
|
constructor(
|
|
90
78
|
{% for prop in model.properties %}
|
|
91
|
-
{{trn(prop.name)}}={{
|
|
79
|
+
{{trn(prop.name)}}={% if prop.definition.string_type == "string" and prop.default is not none %}{{ prop.default | json_literal }}{% else %}{{ prop.default | json_value }}{% endif %},
|
|
92
80
|
{% endfor %}
|
|
93
81
|
{% if model.extends %}
|
|
94
82
|
...superArgs
|
|
@@ -118,7 +106,7 @@ class {{model.python_type_name}}{% if model.extends %} extends {{ model.extends
|
|
|
118
106
|
|
|
119
107
|
{% for prop in model.properties %}
|
|
120
108
|
/**
|
|
121
|
-
{% if prop.comment %} * {{ prop.comment | indent(7) }}
|
|
109
|
+
{% if prop.comment %} * {{ prop.comment | block_comment | indent(7) }}
|
|
122
110
|
{% endif %}
|
|
123
111
|
* @returns {{ jsdoc_typ(prop, relativeTo=None, withNamespace=True) }}
|
|
124
112
|
|
|
@@ -190,14 +178,14 @@ class {{model.python_type_name}}{% if model.extends %} extends {{ model.extends
|
|
|
190
178
|
Object.defineProperty({{ model.full_name_python_path() }}, "options", {
|
|
191
179
|
value: {
|
|
192
180
|
{% for name, value in model.values.items() %}
|
|
193
|
-
{{ name }}: {% if model.value_type.type == "string" %}
|
|
181
|
+
{{ name }}: {% if model.value_type.type == "string" %}{{ value | json_quote('"') }}{% else %}{{ value | json_value }}{% endif %},
|
|
194
182
|
{% endfor %}
|
|
195
183
|
}
|
|
196
184
|
});
|
|
197
185
|
Object.defineProperty({{ model.full_name_python_path() }}, "optionsFlipped", {
|
|
198
186
|
value: {
|
|
199
187
|
{% for name, value in model.values.items() %}
|
|
200
|
-
{% if model.value_type.type == "string" %}
|
|
188
|
+
{% if model.value_type.type == "string" %}{{ value | json_quote('"') }}{% else %}{{ value | json_value }}{% endif %}: "{{ name }}",
|
|
201
189
|
{% endfor %}
|
|
202
190
|
}
|
|
203
191
|
});
|
|
@@ -209,7 +197,7 @@ Object.defineProperty({{ model.full_name_python_path() }}, "optionsFlipped", {
|
|
|
209
197
|
* @readonly
|
|
210
198
|
*/
|
|
211
199
|
Object.defineProperty({{ model.full_name_python_path() }}, "{{ name }}", {
|
|
212
|
-
value: new {{ model.full_name_python_path() }}({% if model.value_type.type == "string" %}
|
|
200
|
+
value: new {{ model.full_name_python_path() }}({% if model.value_type.type == "string" %}{{ value | json_quote('"') }}{% else %}{{ value | json_value }}{% endif %})
|
|
213
201
|
});
|
|
214
202
|
{% endfor %}
|
|
215
203
|
{% endif %}
|
|
@@ -233,14 +221,14 @@ Object.defineProperty({{ model.full_name_python_path() }}, "typesMap", {
|
|
|
233
221
|
Object.defineProperty({{ model.full_name_python_path() }}, "formatsMap", {
|
|
234
222
|
value: {
|
|
235
223
|
{% for prop in model.properties if prop.format %}
|
|
236
|
-
{{trn(prop.name)}}:
|
|
224
|
+
{{trn(prop.name)}}: {{ prop.format | json_quote("'") }},
|
|
237
225
|
{% endfor %}
|
|
238
226
|
}
|
|
239
227
|
});
|
|
240
228
|
Object.defineProperty({{ model.full_name_python_path() }}, "validationsMap", {
|
|
241
229
|
value: {
|
|
242
230
|
{% for prop in model.properties if prop.validations %}
|
|
243
|
-
'{{ trn(prop.name) }}': { {% for type, value in prop.validations.items() %}'{{ type }}': {% if type == "pattern" %}
|
|
231
|
+
'{{ trn(prop.name) }}': { {% for type, value in prop.validations.items() %}'{{ type }}': {% if type == "pattern" %}{{ value | js_regex }}{% else %}{{ value | json_value }}{% endif %},{% endfor %}},
|
|
244
232
|
{% endfor %}
|
|
245
233
|
}
|
|
246
234
|
});
|
|
@@ -258,7 +246,7 @@ Object.defineProperty({{ model.full_name_python_path() }}, "validationsMap", {
|
|
|
258
246
|
* @type {% raw %}{{{% endraw %}
|
|
259
247
|
|
|
260
248
|
{% for model in models %}
|
|
261
|
-
{{model.
|
|
249
|
+
{{model.python_type_name}}: {{model.python_type_name}}{% if not loop.last %},
|
|
262
250
|
{% endif %}{% endfor %}
|
|
263
251
|
|
|
264
252
|
{% raw %}}}{% endraw %}
|
|
@@ -266,6 +254,6 @@ Object.defineProperty({{ model.full_name_python_path() }}, "validationsMap", {
|
|
|
266
254
|
*/
|
|
267
255
|
module.exports = {
|
|
268
256
|
{%- for model in models %}
|
|
269
|
-
{{model.
|
|
257
|
+
{{model.python_type_name}},
|
|
270
258
|
{% endfor %}
|
|
271
259
|
};
|
|
@@ -31,6 +31,141 @@ from . import __version__
|
|
|
31
31
|
|
|
32
32
|
logger = logging.getLogger("main")
|
|
33
33
|
|
|
34
|
+
# Strings that were always pasted into the code unquoted and are kept that way (ignoring surrounding whitespace):
|
|
35
|
+
# a number in any notation the languages accept (0x10, 1_000, 1e-3, 10n...), or a plain dotted name such as
|
|
36
|
+
# True, null, Color.RED or -Infinity. Neither can call anything; any other string is quoted.
|
|
37
|
+
UNQUOTED_RE = re.compile(
|
|
38
|
+
r"[+-]?(\.?\d[\w.]*([eE][+-]\d\w*)?|[^\W\d]\w*(\.[^\W\d]\w*)*)"
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
# Characters that end a single-line string literal, and whether a backslash may escape them (line continuation)
|
|
42
|
+
LINE_BREAKS = {"python": ("\r\n", True), "js": ("\r\n", True), "go": ("\n", False)}
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def is_closed_docstring(s: str) -> bool:
|
|
46
|
+
"""
|
|
47
|
+
Whether s can go between triple quotes as-is: no unescaped \"\"\" inside it. The template puts a newline after
|
|
48
|
+
the text, so a trailing backslash can't escape the closing quotes.
|
|
49
|
+
"""
|
|
50
|
+
i = 0
|
|
51
|
+
while i < len(s):
|
|
52
|
+
if s[i] == "\\":
|
|
53
|
+
i += 2
|
|
54
|
+
elif s.startswith('"""', i):
|
|
55
|
+
return False
|
|
56
|
+
else:
|
|
57
|
+
i += 1
|
|
58
|
+
return True
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def is_closed_js_regex(s: str) -> bool:
|
|
62
|
+
"""Whether /s/ is one complete JS regex literal (like old_literal, plus [...] classes)."""
|
|
63
|
+
if not s or s[0] == "*":
|
|
64
|
+
return False
|
|
65
|
+
in_class = False
|
|
66
|
+
i = 0
|
|
67
|
+
while i < len(s):
|
|
68
|
+
c = s[i]
|
|
69
|
+
if c in "\r\n\u2028\u2029":
|
|
70
|
+
return False
|
|
71
|
+
if c == "\\":
|
|
72
|
+
if i + 1 >= len(s) or s[i + 1] in "\r\n\u2028\u2029":
|
|
73
|
+
return False
|
|
74
|
+
i += 2
|
|
75
|
+
continue
|
|
76
|
+
if c == "[":
|
|
77
|
+
in_class = True
|
|
78
|
+
elif c == "]":
|
|
79
|
+
in_class = False
|
|
80
|
+
elif c == "/" and not in_class:
|
|
81
|
+
return False
|
|
82
|
+
i += 1
|
|
83
|
+
# An unclosed [ class would swallow the closing / and whatever follows it on the line
|
|
84
|
+
return not in_class
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def json_literal(v) -> str:
|
|
88
|
+
# U+2028/U+2029 are valid in JS strings but jsbeautifier turns them into line breaks, so escape them
|
|
89
|
+
return (
|
|
90
|
+
json.dumps(v, ensure_ascii=False)
|
|
91
|
+
.replace("\u2028", "\\u2028")
|
|
92
|
+
.replace("\u2029", "\\u2029")
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def old_literal(s: str, quote: str, language: str) -> Optional[str]:
|
|
97
|
+
"""
|
|
98
|
+
quote + s + quote, as the templates used to emit it, if that is one complete string literal in the language:
|
|
99
|
+
every quote inside s is escaped, s does not end in an escaping backslash, and line breaks only appear as
|
|
100
|
+
line continuations where the language allows them. Escape sequences then mean exactly what they used to.
|
|
101
|
+
Raw U+2028/U+2029 are escaped (same value) because jsbeautifier would turn them into line breaks.
|
|
102
|
+
Returns None if the old form was not a complete literal.
|
|
103
|
+
"""
|
|
104
|
+
breaks, continuation = LINE_BREAKS[language]
|
|
105
|
+
out = []
|
|
106
|
+
i = 0
|
|
107
|
+
while i < len(s):
|
|
108
|
+
c = s[i]
|
|
109
|
+
if c == "\\":
|
|
110
|
+
if i + 1 >= len(s) or (s[i + 1] in breaks and not continuation):
|
|
111
|
+
return None
|
|
112
|
+
j = i + 3 if s.startswith("\r\n", i + 1) else i + 2
|
|
113
|
+
out.append(s[i:j])
|
|
114
|
+
i = j
|
|
115
|
+
continue
|
|
116
|
+
if s.startswith(quote, i) or c in breaks:
|
|
117
|
+
return None
|
|
118
|
+
out.append("\\u%04x" % ord(c) if c in "\u2028\u2029" else c)
|
|
119
|
+
i += 1
|
|
120
|
+
return quote + "".join(out) + quote
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def py_quote(v, quote: str) -> str:
|
|
124
|
+
"""A Python string literal for v: the old quote + v + quote when that was already a complete literal."""
|
|
125
|
+
s = str(v)
|
|
126
|
+
return old_literal(s, quote, "python") or repr(s)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def json_quote(v, quote: str, language: str = "js") -> str:
|
|
130
|
+
"""A JS/Go string literal for v: the old quote + v + quote when that was already a complete literal."""
|
|
131
|
+
s = str(v)
|
|
132
|
+
return old_literal(s, quote, language) or json_literal(s)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def unquoted(v) -> Optional[str]:
|
|
136
|
+
"""The text a string value used to be pasted in as, if it is a number or a plain name; otherwise None."""
|
|
137
|
+
t = v.strip()
|
|
138
|
+
return t if UNQUOTED_RE.fullmatch(t) else None
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def py_value(v) -> str:
|
|
142
|
+
"""Python source for a value that was emitted unquoted: as before, except strings that aren't numbers or names are quoted."""
|
|
143
|
+
if isinstance(v, str):
|
|
144
|
+
return unquoted(v) or repr(v)
|
|
145
|
+
return str(v)
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def json_value(v) -> str:
|
|
149
|
+
"""JS/Go source for a value that was emitted unquoted: numbers and names as before, everything else as JSON."""
|
|
150
|
+
if isinstance(v, str):
|
|
151
|
+
return unquoted(v) or json_literal(v)
|
|
152
|
+
return json_literal(v)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def py_docstring(s: str) -> str:
|
|
156
|
+
"""Docstring text, unchanged unless it would end the docstring early; then every '"' is escaped."""
|
|
157
|
+
return s if is_closed_docstring(s) else s.replace('"', '\\"')
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def js_regex(v) -> str:
|
|
161
|
+
s = str(v)
|
|
162
|
+
return (
|
|
163
|
+
"/" + s + "/"
|
|
164
|
+
if is_closed_js_regex(s)
|
|
165
|
+
else "new RegExp(" + json_literal(s) + ")"
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
|
|
34
169
|
J2P_TYPES = {
|
|
35
170
|
"string": str,
|
|
36
171
|
"integer": int,
|
|
@@ -101,6 +236,17 @@ class JsonSchema2Popo:
|
|
|
101
236
|
find, replace, s
|
|
102
237
|
)
|
|
103
238
|
self.jinja.globals["trn"] = self.maybe_translate_property_name
|
|
239
|
+
# Values from the schema are emitted as literals, never pasted into the generated source as code.
|
|
240
|
+
self.jinja.filters.update(
|
|
241
|
+
py_quote=py_quote,
|
|
242
|
+
py_value=py_value,
|
|
243
|
+
py_docstring=py_docstring,
|
|
244
|
+
json_literal=json_literal,
|
|
245
|
+
json_quote=json_quote,
|
|
246
|
+
json_value=json_value,
|
|
247
|
+
js_regex=js_regex,
|
|
248
|
+
)
|
|
249
|
+
self.jinja.filters["block_comment"] = lambda s: s.replace("*/", "*\\/")
|
|
104
250
|
self.jinja.filters["trn"] = self.maybe_translate_property_name
|
|
105
251
|
|
|
106
252
|
jinja_globals = self.module.jinja_globals()
|
|
@@ -118,9 +264,7 @@ class JsonSchema2Popo:
|
|
|
118
264
|
|
|
119
265
|
def __update_self(self):
|
|
120
266
|
extra_generation_options["translate_properties"] = self.translate_properties
|
|
121
|
-
extra_generation_options[
|
|
122
|
-
"translate_name_func"
|
|
123
|
-
] = self.maybe_translate_property_name
|
|
267
|
+
extra_generation_options["translate_name_func"] = self.translate_type_name
|
|
124
268
|
|
|
125
269
|
def load(self, json_schema_file):
|
|
126
270
|
self.process(json.load(json_schema_file))
|
|
@@ -407,12 +551,14 @@ class JsonSchema2Popo:
|
|
|
407
551
|
return model
|
|
408
552
|
|
|
409
553
|
def write_file(self, filename):
|
|
554
|
+
if not self.custom_template:
|
|
555
|
+
self.check_names()
|
|
410
556
|
template = self.custom_template or self.module.template()
|
|
411
557
|
self.jinja.get_template(template).stream(
|
|
412
558
|
models=self.definitions,
|
|
413
559
|
enum_used=self.enum_used,
|
|
414
560
|
list_used=self.list_used,
|
|
415
|
-
**self.module.extra_jinja_inputs()
|
|
561
|
+
**self.module.extra_jinja_inputs(),
|
|
416
562
|
).dump(filename)
|
|
417
563
|
if hasattr(filename, "close"):
|
|
418
564
|
filename.close()
|
|
@@ -424,6 +570,64 @@ class JsonSchema2Popo:
|
|
|
424
570
|
s1 = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", name)
|
|
425
571
|
return re.sub("([a-z0-9])([A-Z])", r"\1_\2", s1).lower()
|
|
426
572
|
|
|
573
|
+
def check_names(self):
|
|
574
|
+
"""Check every name the built-in templates emit as an identifier, for what is actually generated."""
|
|
575
|
+
seen = set()
|
|
576
|
+
|
|
577
|
+
def check_path(d: Definition):
|
|
578
|
+
# A type is emitted by its full path, e.g. Parent._child
|
|
579
|
+
for a in d.ancestors():
|
|
580
|
+
if a.name is not None:
|
|
581
|
+
self.check_identifier(a.name, "Type or property")
|
|
582
|
+
|
|
583
|
+
def visit(d: Optional[Definition]):
|
|
584
|
+
if d is None or id(d) in seen:
|
|
585
|
+
return
|
|
586
|
+
seen.add(id(d))
|
|
587
|
+
check_path(d)
|
|
588
|
+
if isinstance(d, ReferenceNode):
|
|
589
|
+
if d.value is not None:
|
|
590
|
+
check_path(d.value)
|
|
591
|
+
return
|
|
592
|
+
if getattr(d, "extends", None) is not None:
|
|
593
|
+
check_path(d.extends)
|
|
594
|
+
if isinstance(d, ListNode):
|
|
595
|
+
visit(d.item_type)
|
|
596
|
+
if isinstance(d, EnumNode):
|
|
597
|
+
for name in d.values:
|
|
598
|
+
self.check_identifier(
|
|
599
|
+
name,
|
|
600
|
+
"Enum member",
|
|
601
|
+
enum_member=True,
|
|
602
|
+
hint=" Enum member names are the enum values, or javaEnumNames if given.",
|
|
603
|
+
)
|
|
604
|
+
for p in getattr(d, "properties", None) or []:
|
|
605
|
+
self.check_identifier(p.name, "Type or property")
|
|
606
|
+
visit(p.definition)
|
|
607
|
+
for c in d.children:
|
|
608
|
+
visit(c)
|
|
609
|
+
|
|
610
|
+
for model in self.definitions:
|
|
611
|
+
visit(model)
|
|
612
|
+
|
|
613
|
+
def check_identifier(self, name, kind: str, enum_member=False, hint=""):
|
|
614
|
+
"""
|
|
615
|
+
Names from the schema are emitted as identifiers, so they must be identifiers in the target language.
|
|
616
|
+
Type and property names have '-' and '.' replaced with '_' first; enum member names are used as-is.
|
|
617
|
+
"""
|
|
618
|
+
candidate = str(name)
|
|
619
|
+
if not enum_member:
|
|
620
|
+
candidate = candidate.replace("-", "_").replace(".", "_")
|
|
621
|
+
if not self.module.is_valid_identifier(candidate, enum_member=enum_member):
|
|
622
|
+
raise ValueError(
|
|
623
|
+
f"{kind} name {name!r} cannot be used as an identifier in the generated "
|
|
624
|
+
f"{self.module.plugin_name()} code.{hint}"
|
|
625
|
+
)
|
|
626
|
+
|
|
627
|
+
def translate_type_name(self, name):
|
|
628
|
+
name = name.replace("-", "_").replace(".", "_")
|
|
629
|
+
return name
|
|
630
|
+
|
|
427
631
|
def after_generation(self, filename=None):
|
|
428
632
|
self.module.after_generation(filename=filename)
|
|
429
633
|
|
jsonschema2popo/python/python.py
CHANGED
|
@@ -4,7 +4,7 @@ import pathlib
|
|
|
4
4
|
from typing import Union, Dict, Callable, Any
|
|
5
5
|
|
|
6
6
|
from jsonschema2popo import version
|
|
7
|
-
from jsonschema2popo.classes import Definition, ListNode, CodeGenPlugin
|
|
7
|
+
from jsonschema2popo.classes import Definition, ListNode, CodeGenPlugin, is_identifier
|
|
8
8
|
from jsonschema2popo.jsonschema2popo import string_to_type
|
|
9
9
|
|
|
10
10
|
|
|
@@ -46,6 +46,9 @@ class Python(CodeGenPlugin):
|
|
|
46
46
|
"use_types": self.use_types,
|
|
47
47
|
}
|
|
48
48
|
|
|
49
|
+
def is_valid_identifier(self, name: str, enum_member: bool = False) -> bool:
|
|
50
|
+
return is_identifier(name)
|
|
51
|
+
|
|
49
52
|
def template(self) -> str:
|
|
50
53
|
return "python_class.tmpl"
|
|
51
54
|
|
|
@@ -25,7 +25,7 @@ from typing import List
|
|
|
25
25
|
class {{model.python_type_name}}{% if model.type == "enum" %}(enum.Enum){% endif %}{% if model.extends %}({{ model.extends.full_name_python_path()}}){% endif %}:
|
|
26
26
|
{% if model.comment %}
|
|
27
27
|
"""
|
|
28
|
-
{{ model.comment | indent(4) }}
|
|
28
|
+
{{ model.comment | py_docstring | indent(4) }}
|
|
29
29
|
"""
|
|
30
30
|
{% endif %}
|
|
31
31
|
{% for child in model.children %}
|
|
@@ -38,7 +38,7 @@ class {{model.python_type_name}}{% if model.type == "enum" %}(enum.Enum){% endif
|
|
|
38
38
|
|
|
39
39
|
{% if model.type == "enum" %}
|
|
40
40
|
{% for name, value in model.values.items() %}
|
|
41
|
-
{{name}} = {% if model.value_type.type == "string" %}
|
|
41
|
+
{{name}} = {% if model.value_type.type == "string" %}{{ value | py_quote('"') }}{% else %}{{ value | py_value }}{% endif %}
|
|
42
42
|
|
|
43
43
|
{% endfor %}
|
|
44
44
|
{% endif %}
|
|
@@ -51,12 +51,12 @@ class {{model.python_type_name}}{% if model.type == "enum" %}(enum.Enum){% endif
|
|
|
51
51
|
}
|
|
52
52
|
_formats_map = {
|
|
53
53
|
{% for prop in model.properties if prop.format %}
|
|
54
|
-
'{{trn(prop.name)}}':
|
|
54
|
+
'{{trn(prop.name)}}': {{ prop.format | py_quote("'") }},
|
|
55
55
|
{% endfor %}
|
|
56
56
|
}
|
|
57
57
|
_validations_map = {
|
|
58
58
|
{% for prop in model.properties if prop.validations %}
|
|
59
|
-
'{{ trn(prop.name) }}': { {% for type, value in prop.validations.items() %}'{{ type }}': {% if type == "pattern" %}
|
|
59
|
+
'{{ trn(prop.name) }}': { {% for type, value in prop.validations.items() %}'{{ type }}': {% if type == "pattern" %}{{ value | py_quote("'") }}{% else %}{{ value | py_value }}{% endif %},{% endfor %}},
|
|
60
60
|
{% endfor %}
|
|
61
61
|
}
|
|
62
62
|
{% endif %}
|
|
@@ -67,7 +67,7 @@ class {{model.python_type_name}}{% if model.type == "enum" %}(enum.Enum){% endif
|
|
|
67
67
|
, *args
|
|
68
68
|
{% endif %}
|
|
69
69
|
{% for prop in model.properties %}
|
|
70
|
-
, {{trn(prop.name)}}{% if use_types %}: {{ get_typing(prop, relativeTo=model) }}{% endif %}={% if prop.definition.string_type == "string" and prop.default is not none %}
|
|
70
|
+
, {{trn(prop.name)}}{% if use_types %}: {{ get_typing(prop, relativeTo=model) }}{% endif %}={% if prop.definition.string_type == "string" and prop.default is not none %}{{ prop.default | py_quote("'") }}{% else %}{{ prop.default | py_value }}{% endif %}
|
|
71
71
|
{% endfor %}
|
|
72
72
|
{% if model.extends %}
|
|
73
73
|
, **kwargs
|
|
@@ -77,7 +77,7 @@ class {{model.python_type_name}}{% if model.type == "enum" %}(enum.Enum){% endif
|
|
|
77
77
|
"""
|
|
78
78
|
{% for prop in model.properties %}
|
|
79
79
|
{% if prop.comment %}
|
|
80
|
-
:param {{ trn(prop.name) }}: {{ prop.comment | indent(12) }}
|
|
80
|
+
:param {{ trn(prop.name) }}: {{ prop.comment | py_docstring | indent(12) }}
|
|
81
81
|
{% endif %}
|
|
82
82
|
{% endfor %}
|
|
83
83
|
"""
|
|
@@ -105,7 +105,7 @@ class {{model.python_type_name}}{% if model.type == "enum" %}(enum.Enum){% endif
|
|
|
105
105
|
{{trn(prop.name)}} = property(_get_{{trn(prop.name)}}, _set_{{trn(prop.name)}})
|
|
106
106
|
{% if prop.comment %}
|
|
107
107
|
"""
|
|
108
|
-
{{ prop.comment | indent(4) }}
|
|
108
|
+
{{ prop.comment | py_docstring | indent(4) }}
|
|
109
109
|
"""
|
|
110
110
|
{% endif %}
|
|
111
111
|
|
|
@@ -1,13 +1,12 @@
|
|
|
1
|
-
Metadata-Version: 2.
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
2
|
Name: JSONSchema2PoPo2
|
|
3
|
-
Version: 3.0
|
|
3
|
+
Version: 3.1.0
|
|
4
4
|
Summary: Converts a JSON Schema to a Plain Old Python Object class
|
|
5
5
|
Home-page: https://github.com/mikedombo/JSONSchema2PoPo2
|
|
6
6
|
Author: Michael Dombrowski
|
|
7
7
|
Author-email: michael@mikedombrowski.com
|
|
8
8
|
License: MIT License
|
|
9
9
|
Keywords: python json-schema code-generator
|
|
10
|
-
Platform: UNKNOWN
|
|
11
10
|
Classifier: Development Status :: 5 - Production/Stable
|
|
12
11
|
Classifier: Intended Audience :: Developers
|
|
13
12
|
Classifier: License :: OSI Approved :: MIT License
|
|
@@ -22,12 +21,26 @@ Classifier: Programming Language :: Python :: 3.10
|
|
|
22
21
|
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
|
23
22
|
Requires-Python: >=3.4
|
|
24
23
|
Description-Content-Type: text/markdown
|
|
25
|
-
|
|
26
|
-
Requires-Dist:
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
24
|
+
License-File: LICENSE.txt
|
|
25
|
+
Requires-Dist: Jinja2>=2.11.3
|
|
26
|
+
Requires-Dist: networkx==2.4
|
|
27
|
+
Provides-Extra: format-js
|
|
28
|
+
Requires-Dist: jsbeautifier; extra == "format-js"
|
|
29
|
+
Provides-Extra: format-python
|
|
30
|
+
Requires-Dist: black; extra == "format-python"
|
|
31
|
+
Dynamic: author
|
|
32
|
+
Dynamic: author-email
|
|
33
|
+
Dynamic: classifier
|
|
34
|
+
Dynamic: description
|
|
35
|
+
Dynamic: description-content-type
|
|
36
|
+
Dynamic: home-page
|
|
37
|
+
Dynamic: keywords
|
|
38
|
+
Dynamic: license
|
|
39
|
+
Dynamic: license-file
|
|
40
|
+
Dynamic: provides-extra
|
|
41
|
+
Dynamic: requires-dist
|
|
42
|
+
Dynamic: requires-python
|
|
43
|
+
Dynamic: summary
|
|
31
44
|
|
|
32
45
|
# JSONSchema2PoPo2
|
|
33
46
|
|
|
@@ -210,5 +223,3 @@ This plugin is simply a single Python file along with a template file. The Pytho
|
|
|
210
223
|
`CodeGenPlugin` interface which allows it to add more arguments to the command line options and then make those new
|
|
211
224
|
values available to the template file. The plugin can also provide more functions to be called from the Jinja
|
|
212
225
|
template which makes developing a template far simpler.
|
|
213
|
-
|
|
214
|
-
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
jsonschema2popo/__init__.py,sha256=6buKm9RBkSl-Y_0ldcmWj4RZzxwpfBFearAd_kSjooM,67
|
|
2
|
+
jsonschema2popo/__main__.py,sha256=XdY6U0qjcHiEuhS5Zwx_936yxSo1f8EjjD8BFnNZNyQ,375
|
|
3
|
+
jsonschema2popo/classes.py,sha256=riNtNBuG5K45R2GpUfNvvABgMunBrq8zWVy9LrkXamg,8994
|
|
4
|
+
jsonschema2popo/jsonschema2popo.py,sha256=3iGZd07M1Pwox-7LpH0W51SZhgiSa1uatrAyXjgANQM,27701
|
|
5
|
+
jsonschema2popo/go/__init__.py,sha256=KE-vVwZ9gAjQgF4gKL61CeY1RFBlDKuYmomynf8Gjls,29
|
|
6
|
+
jsonschema2popo/go/go.py,sha256=q1l82t_tZpuS9J60RAVy9B0t1wO5QSq-SMo55pDv6eI,1387
|
|
7
|
+
jsonschema2popo/go/go_struct.tmpl,sha256=kN3GZ-cXevLjDjEdnhXA2Ywyw3B4r_QRZ8F7gNuvCNg,2740
|
|
8
|
+
jsonschema2popo/js/__init__.py,sha256=Z_0e678FTCNVUlXzW2M06qfU9gbqywzHJlLgSDh4n9I,29
|
|
9
|
+
jsonschema2popo/js/js.py,sha256=iF_e-tdzMp_E_RYc9SCChah6IHkC6ph1tNX2JiSzrfI,4014
|
|
10
|
+
jsonschema2popo/js/js_class.tmpl,sha256=wFzNIOBIQOPSy0-sc4J6lpFbTtFWdJp-01Nert0dgqg,8826
|
|
11
|
+
jsonschema2popo/python/__init__.py,sha256=-rpV828HDnQfqg5ceROWDi_Szuytk7hRqMn_eMbWdis,37
|
|
12
|
+
jsonschema2popo/python/python.py,sha256=BE_2fzDOipinI_gxF-mqGCpbhZRmYJqelBDZpM-ie9w,2981
|
|
13
|
+
jsonschema2popo/python/python_class.tmpl,sha256=tfetnJK4lJCn5636LHsPFqqfuf0hRJ4ChdaDYPc9G80,6473
|
|
14
|
+
jsonschema2popo2-3.1.0.dist-info/licenses/LICENSE.txt,sha256=Kft-5gV2Sd4dIuPalhq_jI2BR7Y8nu0dDPWXK2ZtGu8,1141
|
|
15
|
+
jsonschema2popo2-3.1.0.dist-info/METADATA,sha256=ydtL9SYRcL4CeiAbtYQX2uU85LcZMzdjVlEK1rO-3YU,8041
|
|
16
|
+
jsonschema2popo2-3.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
17
|
+
jsonschema2popo2-3.1.0.dist-info/entry_points.txt,sha256=TZVCJ9J58f9Usz3PFNsxlu5KHK8nSPZQ6ObC3oznOWs,74
|
|
18
|
+
jsonschema2popo2-3.1.0.dist-info/top_level.txt,sha256=q41oezqZYb2EwcNQJyD6XeA6q6ujaW1QJNOU6NZ5v1o,16
|
|
19
|
+
jsonschema2popo2-3.1.0.dist-info/RECORD,,
|
|
@@ -1,19 +0,0 @@
|
|
|
1
|
-
jsonschema2popo/__init__.py,sha256=xiReMbGtuTSPldCGAURzRWodOU19g4Ck-F86eR32BkM,67
|
|
2
|
-
jsonschema2popo/__main__.py,sha256=XdY6U0qjcHiEuhS5Zwx_936yxSo1f8EjjD8BFnNZNyQ,375
|
|
3
|
-
jsonschema2popo/classes.py,sha256=QTZC_m3h3ULJ2Zr-9nrZnRFC3C8HOq1OzrvHKRVZ120,8398
|
|
4
|
-
jsonschema2popo/jsonschema2popo.py,sha256=ak0eQbkZ6D56dx26AP8FA6T7GwOBpFunR0CPS8eazrU,20051
|
|
5
|
-
jsonschema2popo/go/__init__.py,sha256=KE-vVwZ9gAjQgF4gKL61CeY1RFBlDKuYmomynf8Gjls,29
|
|
6
|
-
jsonschema2popo/go/go.py,sha256=f7wDVuuLa-FRs3v_I133eQ77-TB6Cd5PZQfju-2RxII,1255
|
|
7
|
-
jsonschema2popo/go/go_struct.tmpl,sha256=75SFdQacjWk9Bb4yAP_PyewFeZTJbzyPkUkIa8JgzJg,2690
|
|
8
|
-
jsonschema2popo/js/__init__.py,sha256=Z_0e678FTCNVUlXzW2M06qfU9gbqywzHJlLgSDh4n9I,29
|
|
9
|
-
jsonschema2popo/js/js.py,sha256=shIRcoF90Sg5O0F1h3KL_yZOFvPOhJ5mWIdW23Os4tU,3620
|
|
10
|
-
jsonschema2popo/js/js_class.tmpl,sha256=RujFDMmaPxYsuWs0jdHSPlEAHCry4jDhamcXxAMDtZQ,8673
|
|
11
|
-
jsonschema2popo/python/__init__.py,sha256=-rpV828HDnQfqg5ceROWDi_Szuytk7hRqMn_eMbWdis,37
|
|
12
|
-
jsonschema2popo/python/python.py,sha256=4i1oz8F0cpccGdniCt8ZendWowD8lo2UVhsTkjKah6U,2849
|
|
13
|
-
jsonschema2popo/python/python_class.tmpl,sha256=4Q7Ks12nby9jrsxuPcGRjnTikWMfXTmcQj2-KZhofI8,6329
|
|
14
|
-
JSONSchema2PoPo2-3.0.2.dist-info/LICENSE.txt,sha256=Kft-5gV2Sd4dIuPalhq_jI2BR7Y8nu0dDPWXK2ZtGu8,1141
|
|
15
|
-
JSONSchema2PoPo2-3.0.2.dist-info/METADATA,sha256=Wumjy0x39FjV3cuiNkp4QFyQGxV38OD6aaNAdlbU900,7765
|
|
16
|
-
JSONSchema2PoPo2-3.0.2.dist-info/WHEEL,sha256=ewwEueio1C2XeHTvT17n8dZUJgOvyCWCt0WVNLClP9o,92
|
|
17
|
-
JSONSchema2PoPo2-3.0.2.dist-info/entry_points.txt,sha256=XFRlrg3br0wUcI9h2afnaFmnpZkPfqnEGLGe5609i0I,75
|
|
18
|
-
JSONSchema2PoPo2-3.0.2.dist-info/top_level.txt,sha256=q41oezqZYb2EwcNQJyD6XeA6q6ujaW1QJNOU6NZ5v1o,16
|
|
19
|
-
JSONSchema2PoPo2-3.0.2.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|