Skip to content

Commit 8878c50

Browse files
committed
Better semantic file separation for models & http-client for client SDK
1 parent a16c7bb commit 8878c50

6 files changed

Lines changed: 211 additions & 25 deletions

File tree

‎.gitignore‎

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,3 +37,66 @@ temp-*
3737
temp-py/
3838
.git.bak
3939
test_wasi.js
40+
41+
# ---------------------------------------------------
42+
# Additional comprehensive exclusions for careless git add .
43+
# ---------------------------------------------------
44+
45+
# Byte-compiled / optimized / DLL files
46+
*.py[cod]
47+
*$py.class
48+
*.pyd
49+
50+
# C extensions
51+
*.so
52+
53+
# Distribution / packaging
54+
.Python
55+
env/
56+
venv/
57+
ENV/
58+
env.bak/
59+
venv.bak/
60+
.env
61+
.venv
62+
63+
# Unit test / coverage reports
64+
htmlcov/
65+
.tox/
66+
.nox/
67+
.coverage
68+
.coverage.*
69+
.cache
70+
nosetests.xml
71+
coverage.xml
72+
*.cover
73+
*.sfdx
74+
.hypothesis/
75+
.pytest_cache/
76+
77+
# Jupyter Notebook
78+
.ipynb_checkpoints
79+
80+
# Environments
81+
.env
82+
.venv
83+
env/
84+
venv/
85+
ENV/
86+
env.bak/
87+
venv.bak/
88+
89+
# mypy
90+
.mypy_cache/
91+
.dmypy.json
92+
dmypy.json
93+
.pyre/
94+
95+
# OS generated files
96+
.DS_Store
97+
.DS_Store?
98+
._*
99+
.Spotlight-V100
100+
.Trashes
101+
ehthumbs.db
102+
Thumbs.db

‎src/openapi_client/classes/emit.py‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,49 @@ def emit_classes(schemas: Dict[str, SchemaOrReference]) -> List[cst.ClassDef]:
7373
return class_defs
7474

7575

76+
def emit_models_module(schemas: Dict[str, SchemaOrReference]) -> str:
77+
"""Emit a complete Python module containing Pydantic models."""
78+
body: List[cst.BaseStatement | cst.EmptyLine] = []
79+
80+
body.append(
81+
cst.SimpleStatementLine(
82+
[
83+
cst.ImportFrom(
84+
module=cst.Name("typing"),
85+
names=[
86+
cst.ImportAlias(name=cst.Name("Any")),
87+
cst.ImportAlias(name=cst.Name("Dict")),
88+
cst.ImportAlias(name=cst.Name("Optional")),
89+
cst.ImportAlias(name=cst.Name("List")),
90+
],
91+
)
92+
]
93+
)
94+
)
95+
body.append(
96+
cst.SimpleStatementLine(
97+
[
98+
cst.ImportFrom(
99+
module=cst.Name("pydantic"),
100+
names=[
101+
cst.ImportAlias(name=cst.Name("BaseModel")),
102+
cst.ImportAlias(name=cst.Name("Field")),
103+
],
104+
)
105+
]
106+
)
107+
)
108+
body.append(cst.EmptyLine())
109+
110+
class_defs = emit_classes(schemas)
111+
for class_def in class_defs:
112+
body.append(class_def)
113+
body.append(cst.EmptyLine())
114+
115+
module = cst.Module(body=body) # type: ignore
116+
return module.code
117+
118+
76119
# OpenAPI 3.2.0 keywords: openapi, $self, jsonSchemaDialect, servers, webhooks, components, security, tags, externalDocs, termsOfService, contact, license, version, name, url, email, identifier, variables, responses, requestBodies, headers, securitySchemes, links, callbacks, pathItems, mediaTypes
77120

78121

‎src/openapi_client/cli.py‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -224,18 +224,34 @@ def process_from_openapi(
224224

225225
for spec in specs:
226226
if subcommand == "to_sdk":
227+
from openapi_client.classes.emit import emit_models_module
228+
227229
generator = ClientGenerator(spec)
228230
(out_dir / "client.py").write_text(
229231
generator.generate_code(), encoding="utf-8"
230232
)
233+
234+
if spec.components and getattr(spec.components, "schemas", None):
235+
(out_dir / "models.py").write_text(
236+
emit_models_module(spec.components.schemas), encoding="utf-8"
237+
)
238+
231239
(out_dir / "test_client.py").write_text(
232240
emit_tests(spec).code, encoding="utf-8"
233241
)
234242
elif subcommand == "to_sdk_cli":
243+
from openapi_client.classes.emit import emit_models_module
244+
235245
generator = ClientGenerator(spec)
236246
(out_dir / "client.py").write_text(
237247
generator.generate_code(), encoding="utf-8"
238248
)
249+
250+
if spec.components and getattr(spec.components, "schemas", None):
251+
(out_dir / "models.py").write_text(
252+
emit_models_module(spec.components.schemas), encoding="utf-8"
253+
)
254+
239255
from openapi_client.cli_sdk_cdd.emit import emit_cli_sdk
240256

241257
(out_dir / "cli_main.py").write_text(emit_cli_sdk(spec), encoding="utf-8")
@@ -279,6 +295,7 @@ def sync_to_openapi(input_path: str, output_path: str) -> None:
279295
) # type: ignore
280296

281297
client_py = in_path / "client.py"
298+
models_py = in_path / "models.py"
282299
mock_py = in_path / "mock_server.py"
283300
test_py = in_path / "test_client.py"
284301
cli_py = in_path / "cli_main.py"
@@ -291,6 +308,11 @@ def sync_to_openapi(input_path: str, output_path: str) -> None:
291308
extract_classes_from_ast(mod, spec)
292309
extract_functions_from_ast(mod, spec)
293310

311+
if models_py.exists():
312+
from openapi_client.classes.parse import extract_classes_from_ast
313+
mod = cst.parse_module(models_py.read_text(encoding="utf-8"))
314+
extract_classes_from_ast(mod, spec)
315+
294316
if mock_py.exists():
295317
mod = cst.parse_module(mock_py.read_text(encoding="utf-8"))
296318
extract_mocks_from_ast(mod, spec)
@@ -333,6 +355,7 @@ def sync_dir(project_dir: str) -> None:
333355
d = Path(project_dir)
334356

335357
client_py = d / "client.py"
358+
models_py = d / "models.py"
336359
mock_py = d / "mock_server.py"
337360
test_py = d / "test_client.py"
338361
cli_py = d / "cli_main.py"
@@ -355,6 +378,11 @@ def sync_dir(project_dir: str) -> None:
355378
extract_classes_from_ast(mod, spec)
356379
extract_functions_from_ast(mod, spec)
357380

381+
if models_py.exists():
382+
from openapi_client.classes.parse import extract_classes_from_ast
383+
mod = cst.parse_module(models_py.read_text(encoding="utf-8"))
384+
extract_classes_from_ast(mod, spec)
385+
358386
if mock_py.exists():
359387
mod = cst.parse_module(mock_py.read_text(encoding="utf-8"))
360388
extract_mocks_from_ast(mod, spec)
@@ -378,6 +406,11 @@ def sync_dir(project_dir: str) -> None:
378406

379407
generator = ClientGenerator(spec)
380408
client_py.write_text(generator.generate_code(), encoding="utf-8")
409+
410+
if spec.components and getattr(spec.components, "schemas", None):
411+
from openapi_client.classes.emit import emit_models_module
412+
models_py.write_text(emit_models_module(spec.components.schemas), encoding="utf-8")
413+
381414
test_py.write_text(emit_tests(spec).code, encoding="utf-8")
382415
mock_py.write_text(emit_mock_server(spec).code, encoding="utf-8")
383416
if cli_py.exists():

‎src/openapi_client/routes/emit.py‎

Lines changed: 12 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44

55
import libcst as cst
66
from openapi_client.models import OpenAPI
7-
from openapi_client.classes.emit import emit_classes
87
from openapi_client.functions.emit import emit_functions
98

109
from typing import List
@@ -54,27 +53,21 @@ def generate(self) -> cst.Module:
5453
]
5554
)
5655
)
57-
body.append(
58-
cst.SimpleStatementLine(
59-
[
60-
cst.ImportFrom(
61-
module=cst.Name("pydantic"),
62-
names=[
63-
cst.ImportAlias(name=cst.Name("BaseModel")),
64-
cst.ImportAlias(name=cst.Name("Field")),
65-
],
66-
)
67-
]
68-
)
69-
)
7056
body.append(cst.EmptyLine())
7157

72-
# Emit classes (Pydantic Models)
58+
# Import Pydantic models from models.py
7359
if self.spec.components and self.spec.components.schemas:
74-
class_defs = emit_classes(self.spec.components.schemas)
75-
for class_def in class_defs:
76-
body.append(class_def)
77-
body.append(cst.EmptyLine())
60+
body.append(
61+
cst.SimpleStatementLine(
62+
[
63+
cst.ImportFrom(
64+
module=cst.Name("models"),
65+
names=cst.ImportStar(),
66+
)
67+
]
68+
)
69+
)
70+
body.append(cst.EmptyLine())
7871

7972
# Emit functions inside the Client class
8073
methods = emit_functions(self.spec)

‎tests/test_cli.py‎

Lines changed: 55 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,16 @@ def test_cli_main_from_openapi(tmp_path, monkeypatch):
4141
"openapi": "3.2.0",
4242
"info": {"title": "Test API", "version": "1.0"},
4343
"paths": {},
44+
"components": {
45+
"schemas": {
46+
"Pet": {
47+
"type": "object",
48+
"properties": {
49+
"name": {"type": "string"}
50+
}
51+
}
52+
}
53+
}
4454
}
4555
spec_path = tmp_path / "openapi.json"
4656
spec_path.write_text(json.dumps(spec))
@@ -60,6 +70,25 @@ def test_cli_main_from_openapi(tmp_path, monkeypatch):
6070
)
6171
main()
6272
assert (out_dir / "client.py").exists()
73+
assert (out_dir / "models.py").exists()
74+
75+
out_dir_cli = tmp_path / "out_cli"
76+
monkeypatch.setattr(
77+
"sys.argv",
78+
[
79+
"cdd-python",
80+
"from_openapi",
81+
"to_sdk_cli",
82+
"-i",
83+
str(spec_path),
84+
"-o",
85+
str(out_dir_cli),
86+
],
87+
)
88+
main()
89+
assert (out_dir_cli / "client.py").exists()
90+
assert (out_dir_cli / "cli_main.py").exists()
91+
assert (out_dir_cli / "models.py").exists()
6392

6493

6594
def test_cli_main_to_openapi(tmp_path, monkeypatch):
@@ -76,22 +105,44 @@ def test_cli_main_to_openapi(tmp_path, monkeypatch):
76105
assert out_spec.exists()
77106

78107

108+
def test_cli_sync_to_openapi_with_models(tmp_path):
109+
py_code = "class Client:\n pass\n"
110+
py_path = tmp_path / "client.py"
111+
py_path.write_text(py_code)
112+
113+
models_code = "from pydantic import BaseModel\nclass Pet(BaseModel):\n name: str\n"
114+
models_path = tmp_path / "models.py"
115+
models_path.write_text(models_code)
116+
117+
out_spec = tmp_path / "openapi.json"
118+
sync_to_openapi(str(tmp_path), str(out_spec))
119+
120+
assert out_spec.exists()
121+
data = json.loads(out_spec.read_text())
122+
assert data["openapi"] == "3.2.0"
123+
assert "Pet" in data["components"]["schemas"]
124+
125+
79126
def test_cli_sync_dir(tmp_path):
80127
project_dir = tmp_path / "project"
81128
project_dir.mkdir()
82129

83130
# client.py
84131
client_py = project_dir / "client.py"
85132
client_py.write_text("""
86-
from pydantic import BaseModel
87-
class Pet(BaseModel):
88-
name: str
89-
90133
class Client:
91134
def get_pets(self):
92135
pass
93136
""")
94137

138+
# models.py
139+
models_py = project_dir / "models.py"
140+
models_py.write_text("""
141+
from pydantic import BaseModel
142+
class Pet(BaseModel):
143+
name: str
144+
""")
145+
95146
# mock_server.py
96147
mock_py = project_dir / "mock_server.py"
97148
mock_py.write_text("""

‎tests/test_client.py‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -107,9 +107,12 @@ def test_generate_code():
107107
code = generator.generate_code()
108108
assert "class Client" in code
109109
assert "def get_pets" in code
110-
assert "class Pet(BaseModel):" in code
111-
assert "class Empty(BaseModel):" in code
112110
assert "limit: int" in code
111+
112+
from openapi_client.classes.emit import emit_models_module
113+
models_code = emit_models_module(spec.components.schemas)
114+
assert "class Pet(BaseModel):" in models_code
115+
assert "class Empty(BaseModel):" in models_code
113116

114117

115118
def test_extract_code():

0 commit comments

Comments
 (0)