-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathgenerate_python_models.py
More file actions
71 lines (60 loc) · 1.92 KB
/
generate_python_models.py
File metadata and controls
71 lines (60 loc) · 1.92 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
#!/usr/bin/env python3
"""Generate Python models from the canonical ModelPack JSON Schema."""
from __future__ import annotations
import subprocess
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
SCHEMA_PATH = ROOT / "schema" / "config-schema.json"
OUTPUT_PATH = ROOT / "py" / "model_spec" / "v1" / "models.py"
def main() -> int:
try:
import datamodel_code_generator # noqa: F401
except ModuleNotFoundError:
print(
"error: datamodel-code-generator is not installed for this Python interpreter. "
"Install it with: python -m pip install datamodel-code-generator",
file=sys.stderr,
)
return 1
if not SCHEMA_PATH.is_file():
print(
f"error: JSON Schema file not found or not a file at expected path: {SCHEMA_PATH}",
file=sys.stderr,
)
return 1
OUTPUT_PATH.parent.mkdir(parents=True, exist_ok=True)
cmd = [
sys.executable,
"-m",
"datamodel_code_generator",
"--input",
str(SCHEMA_PATH),
"--output",
str(OUTPUT_PATH),
"--input-file-type",
"jsonschema",
"--output-model-type",
"pydantic_v2.BaseModel",
"--target-python-version",
"3.10",
"--enum-field-as-literal",
"all",
"--field-constraints",
"--disable-timestamp",
]
try:
subprocess.run(cmd, check=True)
except subprocess.CalledProcessError as exc:
cmd_str = " ".join(exc.cmd) if getattr(exc, "cmd", None) else " ".join(cmd)
print(
f"error: datamodel-code-generator failed with exit code {exc.returncode}.",
file=sys.stderr,
)
print(f"command: {cmd_str}", file=sys.stderr)
return exc.returncode or 1
else:
print(f"Generated: {OUTPUT_PATH}")
return 0
if __name__ == "__main__":
raise SystemExit(main())