codecraftai-restclient-base 1.2.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.
- ccai/restclient/base/__init__.py +0 -0
- ccai/restclient/base/aspectsrest.py +122 -0
- ccai/restclient/base/awssigv4.py +364 -0
- ccai/restclient/base/itemsresult.py +274 -0
- ccai/restclient/base/pagedlist.py +158 -0
- ccai/restclient/base/py.typed +0 -0
- ccai/restclient/base/restapigroup.py +434 -0
- ccai/restclient/base/restclientbase.py +666 -0
- ccai/restclient/base/restclientgenerator.py +1595 -0
- ccai/restclient/base/restclientutils.py +66 -0
- ccai/restclient/base/schemafield.py +11 -0
- ccai/restclient/base/schemaobject.py +12 -0
- ccai/restclient/base/taskhandle.py +267 -0
- codecraftai_restclient_base-1.2.0.dist-info/METADATA +88 -0
- codecraftai_restclient_base-1.2.0.dist-info/RECORD +17 -0
- codecraftai_restclient_base-1.2.0.dist-info/WHEEL +4 -0
- codecraftai_restclient_base-1.2.0.dist-info/licenses/LICENSE.md +204 -0
|
@@ -0,0 +1,1595 @@
|
|
|
1
|
+
"""
|
|
2
|
+
.. module:: restclientgenerator
|
|
3
|
+
:platform: Darwin, Linux, Unix, Windows
|
|
4
|
+
:synopsis: Generates REST client source from the GitHub OpenAPI description.
|
|
5
|
+
|
|
6
|
+
.. moduleauthor:: Myron Walker <myron.walker@gmail.com>
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from typing import Any, Dict, List, Optional, Tuple, Type
|
|
10
|
+
|
|
11
|
+
import argparse
|
|
12
|
+
import ast
|
|
13
|
+
import json
|
|
14
|
+
import keyword
|
|
15
|
+
import re
|
|
16
|
+
|
|
17
|
+
from dataclasses import dataclass
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
import yaml
|
|
21
|
+
|
|
22
|
+
from ccai.restclient.base.aspectsrest import AspectsRest
|
|
23
|
+
from ccai.restclient.base.pagedlist import PagedList
|
|
24
|
+
from ccai.restclient.base.restapigroup import RestApiGroup
|
|
25
|
+
from ccai.restclient.base.restclientbase import RestClientBase
|
|
26
|
+
from ccai.restclient.base.schemafield import Field
|
|
27
|
+
from ccai.restclient.base.schemaobject import SchemaObject
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
AUTO_GENERATED_BANNER = "# Auto-generated by RestClientGenerator. DO NOT EDIT.\n"
|
|
31
|
+
|
|
32
|
+
SUPPORTED_HTTP_METHODS = {"get", "post", "put", "delete", "patch", "head", "options"}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
_MARKDOWN_ESCAPE_RE = re.compile(r"\\([_*#\[\]()`.>~|-])")
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def literal_text(text: str) -> str:
|
|
39
|
+
"""
|
|
40
|
+
Makes free text from an OpenAPI description safe inside a generated string
|
|
41
|
+
literal or docstring.
|
|
42
|
+
|
|
43
|
+
Descriptions arrive as markdown, where a backslash escapes punctuation such
|
|
44
|
+
as ``\\_``. Python reads the same sequence as an invalid escape and warns at
|
|
45
|
+
import time, and a real backslash would change the literal's value. Markdown
|
|
46
|
+
escapes are unwrapped and any remaining backslash is doubled.
|
|
47
|
+
|
|
48
|
+
:param text: The description text.
|
|
49
|
+
|
|
50
|
+
:returns: Text that can be written verbatim inside a generated literal.
|
|
51
|
+
"""
|
|
52
|
+
rtnval = _MARKDOWN_ESCAPE_RE.sub(r"\1", text or "")
|
|
53
|
+
rtnval = rtnval.replace("\\", "\\\\")
|
|
54
|
+
return rtnval
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@dataclass
|
|
58
|
+
class ParameterSpec:
|
|
59
|
+
"""
|
|
60
|
+
Specification for a parameter from the OpenAPI description.
|
|
61
|
+
"""
|
|
62
|
+
name: str
|
|
63
|
+
location: str
|
|
64
|
+
required: bool
|
|
65
|
+
schema: Dict[str, Any]
|
|
66
|
+
description: str
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
@dataclass
|
|
70
|
+
class OperationSpec:
|
|
71
|
+
"""
|
|
72
|
+
Container holding details about an API operation.
|
|
73
|
+
"""
|
|
74
|
+
path: str
|
|
75
|
+
http_method: str
|
|
76
|
+
group: str
|
|
77
|
+
operation_id: str
|
|
78
|
+
method_name: str
|
|
79
|
+
summary: str
|
|
80
|
+
description: str
|
|
81
|
+
parameters: List[ParameterSpec]
|
|
82
|
+
request_body: Optional[Dict[str, Any]]
|
|
83
|
+
responses: Dict[str, Any]
|
|
84
|
+
external_docs: Optional[Dict[str, Any]] = None
|
|
85
|
+
response_schema_info: Optional[Dict[str, Any]] = None # Extracted 200 response schema info
|
|
86
|
+
archetype: Optional[str] = None
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
@dataclass
|
|
90
|
+
class TypeSpec:
|
|
91
|
+
"""
|
|
92
|
+
Specification for a generated type.
|
|
93
|
+
"""
|
|
94
|
+
name: str
|
|
95
|
+
schema: Dict[str, Any]
|
|
96
|
+
description: str = ""
|
|
97
|
+
source: str = "" # 'parameter', 'schema', 'request_body'
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class RestClientGenerator:
|
|
101
|
+
"""
|
|
102
|
+
Shapes the patterns for the REST API generation.
|
|
103
|
+
"""
|
|
104
|
+
|
|
105
|
+
REST_CLIENT_BASE_CLASS: Type[RestClientBase] = RestClientBase
|
|
106
|
+
GROUP_BASE_TYPE: Type[RestApiGroup] = RestApiGroup
|
|
107
|
+
SCHEMA_BASE_TYPE: Type[SchemaObject] = SchemaObject
|
|
108
|
+
SCHEMA_FIELD_TYPE: Type[Field] = Field
|
|
109
|
+
ASPECTS_TYPE: Type[AspectsRest] = AspectsRest
|
|
110
|
+
PAGEDLIST_TYPE: Type[PagedList] = PagedList
|
|
111
|
+
|
|
112
|
+
SCHEMA_MODULE_ROOT = "ccai.github.rest.clients.public.schemas"
|
|
113
|
+
GROUP_MODULE_ROOT = "ccai.github.rest.clients.public.groups"
|
|
114
|
+
CLIENT_MODULE_ROOT = "ccai.github.rest.clients.public"
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
DEFAULT_PAGINATION_DETECTION_HINTS = {
|
|
118
|
+
"detection_rules": {
|
|
119
|
+
"query_parameters": {
|
|
120
|
+
"parameters": ["page", "per_page"],
|
|
121
|
+
"enabled": True
|
|
122
|
+
}
|
|
123
|
+
},
|
|
124
|
+
"default_parameters": {
|
|
125
|
+
"page_param": "page",
|
|
126
|
+
"per_page_param": "per_page"
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
def __init__(self, openapi_spec_file: str, clients_root: str, client_class_name: str = "GithubRestClient"):
|
|
131
|
+
self._spec_path = Path(openapi_spec_file).resolve()
|
|
132
|
+
self._clients_root = Path(clients_root).resolve()
|
|
133
|
+
self._client_class_name = client_class_name
|
|
134
|
+
self._spec = self._load_openapi_spec(self._spec_path)
|
|
135
|
+
|
|
136
|
+
self._components = self._spec.get("components", {})
|
|
137
|
+
self._tag_catalog: Dict[str, str] = {}
|
|
138
|
+
self._groups: Dict[str, List[OperationSpec]] = {}
|
|
139
|
+
|
|
140
|
+
# Type registries for the new type-based approach
|
|
141
|
+
self._common_types: Dict[str, TypeSpec] = {} # Common parameter types
|
|
142
|
+
self._schema_types: Dict[str, TypeSpec] = {} # Schema types from components
|
|
143
|
+
self._request_types: Dict[str, TypeSpec] = {} # Request body types
|
|
144
|
+
|
|
145
|
+
# Schema usage tracking for file organization
|
|
146
|
+
self._schema_usage: Dict[str, Dict[str, Any]] = {} # schema_name -> {tags, creating_ops, using_ops}
|
|
147
|
+
|
|
148
|
+
# Schema import lookup table: type_name -> import statement
|
|
149
|
+
self._schema_imports: Dict[str, str] = {} # TypeName -> f"from {SCHEMA_MODULE_ROOT}.file import TypeName"
|
|
150
|
+
|
|
151
|
+
# Load pagination hints
|
|
152
|
+
self._pagination_hints = self.DEFAULT_PAGINATION_DETECTION_HINTS
|
|
153
|
+
|
|
154
|
+
# Load API hints
|
|
155
|
+
self._api_hints = self._load_api_hints()
|
|
156
|
+
|
|
157
|
+
self._build_type_registries()
|
|
158
|
+
self._process_spec()
|
|
159
|
+
self._analyze_schema_usage()
|
|
160
|
+
return
|
|
161
|
+
|
|
162
|
+
def generate(self):
|
|
163
|
+
"""
|
|
164
|
+
Generate all client, group, and schema modules.
|
|
165
|
+
"""
|
|
166
|
+
clients_root = self._clients_root
|
|
167
|
+
groups_dir = clients_root / "groups"
|
|
168
|
+
schemas_dir = clients_root / "schemas"
|
|
169
|
+
|
|
170
|
+
for directory in (groups_dir, schemas_dir):
|
|
171
|
+
directory.mkdir(parents=True, exist_ok=True)
|
|
172
|
+
|
|
173
|
+
# Generate schema modules first
|
|
174
|
+
self._generate_schema_modules(schemas_dir)
|
|
175
|
+
|
|
176
|
+
sorted_groups = sorted(self._groups.keys())
|
|
177
|
+
|
|
178
|
+
for group in sorted_groups:
|
|
179
|
+
ops = sorted(self._groups[group], key=lambda o: self._safe_snake(o.method_name))
|
|
180
|
+
self._generate_group_module(group, ops, groups_dir)
|
|
181
|
+
|
|
182
|
+
self._generate_client_module(sorted_groups, clients_root)
|
|
183
|
+
self._write_simple_init(groups_dir)
|
|
184
|
+
self._write_schemas_init(schemas_dir)
|
|
185
|
+
self._write_simple_init(clients_root)
|
|
186
|
+
return
|
|
187
|
+
|
|
188
|
+
def _analyze_schema_usage(self):
|
|
189
|
+
"""
|
|
190
|
+
Analyze which schemas are used by which operations and tags.
|
|
191
|
+
This information is used to organize schemas into appropriate files.
|
|
192
|
+
"""
|
|
193
|
+
for path_leaf, method_catalog in self._spec["paths"].items():
|
|
194
|
+
for call_method, op_desc in method_catalog.items():
|
|
195
|
+
if call_method not in SUPPORTED_HTTP_METHODS:
|
|
196
|
+
continue
|
|
197
|
+
|
|
198
|
+
operation_id = op_desc.get("operationId", "")
|
|
199
|
+
tags = op_desc.get("tags", [])
|
|
200
|
+
tag = tags[0] if tags else "default"
|
|
201
|
+
|
|
202
|
+
# Extract schema references from responses
|
|
203
|
+
responses = op_desc.get("responses", {})
|
|
204
|
+
response_200 = responses.get("200", {})
|
|
205
|
+
content = response_200.get("content", {})
|
|
206
|
+
json_content = content.get("application/json", {})
|
|
207
|
+
schema = json_content.get("schema", {})
|
|
208
|
+
|
|
209
|
+
# Extract schema references from request body
|
|
210
|
+
request_body = op_desc.get("requestBody", {})
|
|
211
|
+
|
|
212
|
+
# Recursively extract all schema references
|
|
213
|
+
refs = set()
|
|
214
|
+
self._extract_schema_refs(schema, refs)
|
|
215
|
+
self._extract_schema_refs(request_body, refs)
|
|
216
|
+
|
|
217
|
+
for ref_name in refs:
|
|
218
|
+
if ref_name not in self._schema_usage:
|
|
219
|
+
self._schema_usage[ref_name] = {
|
|
220
|
+
'tags': set(),
|
|
221
|
+
'creating_ops': [],
|
|
222
|
+
'using_ops': []
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
self._schema_usage[ref_name]['tags'].add(tag)
|
|
226
|
+
self._schema_usage[ref_name]['using_ops'].append(operation_id)
|
|
227
|
+
|
|
228
|
+
# Check if this is a creating operation (POST/PUT/PATCH)
|
|
229
|
+
if call_method.upper() in ['POST', 'PUT', 'PATCH']:
|
|
230
|
+
self._schema_usage[ref_name]['creating_ops'].append(operation_id)
|
|
231
|
+
return
|
|
232
|
+
|
|
233
|
+
def _build_schema_import_table(self):
|
|
234
|
+
"""
|
|
235
|
+
Build lookup table of import statements for all schema types.
|
|
236
|
+
Maps TypeName -> "from ccai.github.rest.clients.public.schemas.file import TypeName"
|
|
237
|
+
"""
|
|
238
|
+
for schema_name, type_spec in self._schema_types.items():
|
|
239
|
+
file_name = self._determine_schema_file(schema_name)
|
|
240
|
+
type_name = type_spec.name
|
|
241
|
+
import_stmt = f"from {self.SCHEMA_MODULE_ROOT}.{file_name} import {type_name}"
|
|
242
|
+
self._schema_imports[type_name] = import_stmt
|
|
243
|
+
return
|
|
244
|
+
|
|
245
|
+
def _build_type_registries(self):
|
|
246
|
+
"""
|
|
247
|
+
Build type registries from components.
|
|
248
|
+
"""
|
|
249
|
+
components = self._components
|
|
250
|
+
|
|
251
|
+
# Build common parameter types from components.parameters
|
|
252
|
+
comp_params = components.get("parameters", {})
|
|
253
|
+
for param_name, param_def in comp_params.items():
|
|
254
|
+
type_name = self._safe_pascal(param_name)
|
|
255
|
+
self._common_types[param_name] = TypeSpec(
|
|
256
|
+
name=type_name,
|
|
257
|
+
schema=param_def.get("schema", {}),
|
|
258
|
+
description=param_def.get("description", ""),
|
|
259
|
+
source="parameter"
|
|
260
|
+
)
|
|
261
|
+
|
|
262
|
+
# Build schema types from components.schemas
|
|
263
|
+
comp_schemas = components.get("schemas", {})
|
|
264
|
+
for schema_name, schema_def in comp_schemas.items():
|
|
265
|
+
type_name = self._safe_pascal(schema_name)
|
|
266
|
+
self._schema_types[schema_name] = TypeSpec(
|
|
267
|
+
name=type_name,
|
|
268
|
+
schema=schema_def,
|
|
269
|
+
description=schema_def.get("description", ""),
|
|
270
|
+
source="schema"
|
|
271
|
+
)
|
|
272
|
+
return
|
|
273
|
+
|
|
274
|
+
def _collect_parameters(self, path_level_params: List[dict], op_level_params: List[dict]) -> List[ParameterSpec]:
|
|
275
|
+
parameters: List[ParameterSpec] = []
|
|
276
|
+
for pentry in path_level_params + op_level_params:
|
|
277
|
+
param_def = self._dereference_parameter(pentry)
|
|
278
|
+
name = param_def.get("name", "unnamed")
|
|
279
|
+
location = param_def.get("in", "query")
|
|
280
|
+
required = bool(param_def.get("required", False))
|
|
281
|
+
schema = param_def.get("schema", {})
|
|
282
|
+
description = param_def.get("description", "")
|
|
283
|
+
parameters.append(
|
|
284
|
+
ParameterSpec(
|
|
285
|
+
name=name,
|
|
286
|
+
location=location,
|
|
287
|
+
required=required,
|
|
288
|
+
schema=schema,
|
|
289
|
+
description=description,
|
|
290
|
+
)
|
|
291
|
+
)
|
|
292
|
+
return parameters
|
|
293
|
+
|
|
294
|
+
def _collect_schema_types_from_properties(self, schema: Dict[str, Any], types_set: set):
|
|
295
|
+
"""
|
|
296
|
+
Collect schema types referenced by properties for class field definitions.
|
|
297
|
+
"""
|
|
298
|
+
if not schema:
|
|
299
|
+
return
|
|
300
|
+
|
|
301
|
+
properties = schema.get("properties", {})
|
|
302
|
+
for prop_schema in properties.values():
|
|
303
|
+
self._collect_schema_types_from_schema(prop_schema, types_set)
|
|
304
|
+
return
|
|
305
|
+
|
|
306
|
+
def _collect_schema_types_from_schema(self, schema: Dict[str, Any], types_set: set, refs_seen: Optional[set] = None):
|
|
307
|
+
"""
|
|
308
|
+
Recursively collect all schema type names referenced in a schema.
|
|
309
|
+
"""
|
|
310
|
+
if not schema:
|
|
311
|
+
return
|
|
312
|
+
|
|
313
|
+
if refs_seen is None:
|
|
314
|
+
refs_seen = set()
|
|
315
|
+
|
|
316
|
+
# Check for direct $ref
|
|
317
|
+
if "$ref" in schema:
|
|
318
|
+
ref = schema["$ref"]
|
|
319
|
+
if ref.startswith("#/components/schemas/"):
|
|
320
|
+
schema_name = ref.split("/")[-1]
|
|
321
|
+
if schema_name in refs_seen:
|
|
322
|
+
return
|
|
323
|
+
refs_seen.add(schema_name)
|
|
324
|
+
type_spec = self._schema_types.get(schema_name)
|
|
325
|
+
if type_spec:
|
|
326
|
+
if self._schema_can_generate_class(type_spec.schema):
|
|
327
|
+
types_set.add(type_spec.name)
|
|
328
|
+
else:
|
|
329
|
+
self._collect_schema_types_from_schema(type_spec.schema, types_set, refs_seen)
|
|
330
|
+
return
|
|
331
|
+
|
|
332
|
+
if "oneOf" in schema or "anyOf" in schema:
|
|
333
|
+
variants = schema.get("oneOf") or schema.get("anyOf") or []
|
|
334
|
+
for sub_schema in variants:
|
|
335
|
+
self._collect_schema_types_from_schema(sub_schema, types_set, refs_seen)
|
|
336
|
+
return
|
|
337
|
+
|
|
338
|
+
# Check for array items
|
|
339
|
+
if schema.get("type") == "array" and "items" in schema:
|
|
340
|
+
self._collect_schema_types_from_schema(schema["items"], types_set, refs_seen)
|
|
341
|
+
return
|
|
342
|
+
|
|
343
|
+
# Objects are represented as Dict[str, Any] in type annotations.
|
|
344
|
+
if schema.get("type") == "object":
|
|
345
|
+
return
|
|
346
|
+
|
|
347
|
+
return
|
|
348
|
+
|
|
349
|
+
def _dereference_parameter(self, param_entry: dict) -> dict:
|
|
350
|
+
if "$ref" in param_entry:
|
|
351
|
+
ref_path = param_entry["$ref"]
|
|
352
|
+
resolved = self._resolve_ref(ref_path)
|
|
353
|
+
if not isinstance(resolved, dict):
|
|
354
|
+
errmsg = f"Reference '{ref_path}' did not resolve to a parameter dictionary."
|
|
355
|
+
raise ValueError(errmsg)
|
|
356
|
+
return resolved
|
|
357
|
+
return param_entry
|
|
358
|
+
|
|
359
|
+
def _derive_group_and_method(self, operation_id: str, tags: List[str], path: str, http_method: str) -> Tuple[str, str]:
|
|
360
|
+
"""
|
|
361
|
+
Derive the group name and method name for an API operation.
|
|
362
|
+
|
|
363
|
+
Priority:
|
|
364
|
+
1. Check api-hints.json for method-name override
|
|
365
|
+
2. Use operationId (strip group prefix if present)
|
|
366
|
+
3. Fall back to http_method
|
|
367
|
+
"""
|
|
368
|
+
# Check for hints override
|
|
369
|
+
method_hints = self._get_api_method_hints(path, http_method)
|
|
370
|
+
if "operationId" in method_hints:
|
|
371
|
+
operation_id = method_hints["operationId"]
|
|
372
|
+
|
|
373
|
+
if "method-name" in method_hints:
|
|
374
|
+
method_name = method_hints["method-name"]
|
|
375
|
+
group_name = tags[0] if tags else "default"
|
|
376
|
+
group_name = self._safe_snake(group_name)
|
|
377
|
+
method_name = self._safe_snake(method_name)
|
|
378
|
+
return group_name, method_name
|
|
379
|
+
|
|
380
|
+
# Use operationId to derive group and method
|
|
381
|
+
group_name = tags[0] if tags else "default"
|
|
382
|
+
method_name = operation_id
|
|
383
|
+
|
|
384
|
+
if operation_id and "/" in operation_id:
|
|
385
|
+
parts = operation_id.split("/", 1)
|
|
386
|
+
group_name = parts[0]
|
|
387
|
+
method_name = parts[1]
|
|
388
|
+
elif not tags and operation_id:
|
|
389
|
+
group_name = operation_id
|
|
390
|
+
method_name = operation_id
|
|
391
|
+
elif not operation_id:
|
|
392
|
+
# Fallback to http_method if no operationId
|
|
393
|
+
method_name = http_method
|
|
394
|
+
|
|
395
|
+
group_name = self._safe_snake(group_name)
|
|
396
|
+
method_name = self._safe_snake(method_name)
|
|
397
|
+
return group_name, method_name
|
|
398
|
+
|
|
399
|
+
def _detect_api_archetype(self, path: str, http_method: str, operation_id: str, op_desc: Dict[str, Any],
|
|
400
|
+
parameters: List[ParameterSpec], response_schema_info: Optional[Dict[str, Any]]) -> Optional[str]:
|
|
401
|
+
"""
|
|
402
|
+
Detect the archetype for a specific API operation.
|
|
403
|
+
|
|
404
|
+
:param path: API path.
|
|
405
|
+
:param http_method: HTTP method name.
|
|
406
|
+
:param operation_id: Operation id from the spec.
|
|
407
|
+
:param op_desc: OpenAPI operation description.
|
|
408
|
+
:param parameters: List of parameters for the operation.
|
|
409
|
+
:param response_schema_info: Parsed response schema info.
|
|
410
|
+
|
|
411
|
+
:returns: Detected archetype or None.
|
|
412
|
+
"""
|
|
413
|
+
archetype = op_desc.get("archetype") or op_desc.get("x-archetype")
|
|
414
|
+
archetype = self._normalize_archetype(archetype)
|
|
415
|
+
if archetype:
|
|
416
|
+
return archetype
|
|
417
|
+
|
|
418
|
+
method_hints = self._get_api_method_hints(path, http_method)
|
|
419
|
+
archetype = self._normalize_archetype(method_hints.get("archetype"))
|
|
420
|
+
if archetype:
|
|
421
|
+
return archetype
|
|
422
|
+
|
|
423
|
+
archetype = self._detect_internal_archetype(path, http_method, operation_id, op_desc, parameters, response_schema_info)
|
|
424
|
+
return archetype
|
|
425
|
+
|
|
426
|
+
def _detect_internal_archetype(self, path: str, http_method: str, operation_id: str, op_desc: Dict[str, Any],
|
|
427
|
+
parameters: List[ParameterSpec], response_schema_info: Optional[Dict[str, Any]]) -> Optional[str]:
|
|
428
|
+
method = http_method.lower()
|
|
429
|
+
path_lower = path.lower()
|
|
430
|
+
summary = (op_desc.get("summary") or "").lower()
|
|
431
|
+
description = (op_desc.get("description") or "").lower()
|
|
432
|
+
opid = (operation_id or "").lower()
|
|
433
|
+
combined = " ".join([summary, description, opid])
|
|
434
|
+
|
|
435
|
+
if method in ("get", "head"):
|
|
436
|
+
if "properties" in path_lower or "settings" in path_lower:
|
|
437
|
+
return "get-properties"
|
|
438
|
+
if response_schema_info and response_schema_info.get("type") == "list":
|
|
439
|
+
if self._has_pagination_parameters(parameters):
|
|
440
|
+
return "paged-collection"
|
|
441
|
+
return "collection"
|
|
442
|
+
|
|
443
|
+
if method == "delete":
|
|
444
|
+
return "delete-item"
|
|
445
|
+
|
|
446
|
+
if method in ("put", "patch"):
|
|
447
|
+
if "properties" in path_lower or "settings" in path_lower:
|
|
448
|
+
return "set-properties"
|
|
449
|
+
if "update" in combined or "set" in combined:
|
|
450
|
+
return "update-item"
|
|
451
|
+
return "action"
|
|
452
|
+
|
|
453
|
+
if method == "post":
|
|
454
|
+
if any(keyword in combined for keyword in ("create", "add", "provision")):
|
|
455
|
+
return "create-item"
|
|
456
|
+
return "action"
|
|
457
|
+
|
|
458
|
+
return None
|
|
459
|
+
|
|
460
|
+
def _determine_return_type(self, op: OperationSpec) -> str:
|
|
461
|
+
"""
|
|
462
|
+
Determine the return type for the method.
|
|
463
|
+
"""
|
|
464
|
+
schema_info = op.response_schema_info
|
|
465
|
+
|
|
466
|
+
if not schema_info:
|
|
467
|
+
return "Any"
|
|
468
|
+
|
|
469
|
+
if schema_info.get("type") == "list":
|
|
470
|
+
item_schema = schema_info.get("item_schema", {})
|
|
471
|
+
item_type = self._schema_to_type(item_schema)
|
|
472
|
+
|
|
473
|
+
# Check if paginated
|
|
474
|
+
if self._is_paginated_operation(op):
|
|
475
|
+
pagedlist_type_name = self.PAGEDLIST_TYPE.__name__
|
|
476
|
+
return f"{pagedlist_type_name}[{item_type}]"
|
|
477
|
+
else:
|
|
478
|
+
return f"List[{item_type}]"
|
|
479
|
+
|
|
480
|
+
elif schema_info.get("type") == "single":
|
|
481
|
+
schema = schema_info.get("schema", {})
|
|
482
|
+
return self._schema_to_type(schema)
|
|
483
|
+
|
|
484
|
+
return "Any"
|
|
485
|
+
|
|
486
|
+
def _determine_schema_file(self, schema_name: str) -> str:
|
|
487
|
+
"""
|
|
488
|
+
Determine which file a schema should be placed in.
|
|
489
|
+
Priority:
|
|
490
|
+
1. Tag group the schema belongs to (if only one tag)
|
|
491
|
+
2. Tag group of the API that creates the object (POST/PUT/PATCH operations)
|
|
492
|
+
3. Use the classname in all lower case
|
|
493
|
+
"""
|
|
494
|
+
usage = self._schema_usage.get(schema_name, {})
|
|
495
|
+
tags = usage.get('tags', set())
|
|
496
|
+
creating_ops = usage.get('creating_ops', [])
|
|
497
|
+
|
|
498
|
+
# Priority 1: Single tag group
|
|
499
|
+
if len(tags) == 1:
|
|
500
|
+
return self._file_slug(list(tags)[0])
|
|
501
|
+
|
|
502
|
+
# Priority 2: Tag from first creating operation
|
|
503
|
+
if creating_ops:
|
|
504
|
+
first_creating_op = creating_ops[0]
|
|
505
|
+
# Extract tag from operation_id (format: "tag/method")
|
|
506
|
+
if '/' in first_creating_op:
|
|
507
|
+
tag = first_creating_op.split('/', 1)[0]
|
|
508
|
+
return self._file_slug(tag)
|
|
509
|
+
|
|
510
|
+
# Priority 3: Use schema classname in lowercase
|
|
511
|
+
type_spec = self._schema_types.get(schema_name)
|
|
512
|
+
if type_spec:
|
|
513
|
+
return type_spec.name.lower()
|
|
514
|
+
|
|
515
|
+
# Fallback
|
|
516
|
+
return schema_name.lower()
|
|
517
|
+
|
|
518
|
+
def _expected_status_codes(self, responses: Dict[str, Any]) -> List[int]:
|
|
519
|
+
expected: List[int] = []
|
|
520
|
+
for code_str in sorted(responses.keys()):
|
|
521
|
+
if code_str.isdigit():
|
|
522
|
+
code_int = int(code_str)
|
|
523
|
+
if 200 <= code_int < 300:
|
|
524
|
+
expected.append(code_int)
|
|
525
|
+
if not expected:
|
|
526
|
+
expected.append(200)
|
|
527
|
+
return expected
|
|
528
|
+
|
|
529
|
+
def _extract_response_schema_info(self, responses: Dict[str, Any]) -> Optional[Dict[str, Any]]:
|
|
530
|
+
"""
|
|
531
|
+
Extract schema information from the 200 response.
|
|
532
|
+
|
|
533
|
+
:returns: Dictionary with 'type' ('single' or 'list'), 'schema' (the schema dict),
|
|
534
|
+
and 'item_type' (for lists)
|
|
535
|
+
"""
|
|
536
|
+
# Look for 200 response
|
|
537
|
+
response_200 = responses.get("200")
|
|
538
|
+
if not response_200:
|
|
539
|
+
return None
|
|
540
|
+
|
|
541
|
+
content = response_200.get("content", {})
|
|
542
|
+
json_content = content.get("application/json")
|
|
543
|
+
if not json_content:
|
|
544
|
+
return None
|
|
545
|
+
|
|
546
|
+
schema = json_content.get("schema", {})
|
|
547
|
+
if not schema:
|
|
548
|
+
return None
|
|
549
|
+
|
|
550
|
+
# Determine if it's a list or single object
|
|
551
|
+
schema_type = schema.get("type")
|
|
552
|
+
|
|
553
|
+
if schema_type == "array":
|
|
554
|
+
items_schema = schema.get("items", {})
|
|
555
|
+
return {
|
|
556
|
+
"type": "list",
|
|
557
|
+
"schema": schema,
|
|
558
|
+
"item_schema": items_schema
|
|
559
|
+
}
|
|
560
|
+
else:
|
|
561
|
+
return {
|
|
562
|
+
"type": "single",
|
|
563
|
+
"schema": schema
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
def _extract_request_body_schema(self, request_body: Dict[str, Any]) -> Optional[Dict[str, Any]]:
|
|
567
|
+
"""
|
|
568
|
+
Extract schema from request body.
|
|
569
|
+
"""
|
|
570
|
+
content = request_body.get("content", {})
|
|
571
|
+
json_content = content.get("application/json")
|
|
572
|
+
if json_content:
|
|
573
|
+
return json_content.get("schema")
|
|
574
|
+
return None
|
|
575
|
+
|
|
576
|
+
def _extract_schema_refs(self, obj: Any, refs_set: set):
|
|
577
|
+
"""
|
|
578
|
+
Recursively extract schema references from an object.
|
|
579
|
+
"""
|
|
580
|
+
if isinstance(obj, dict):
|
|
581
|
+
if '$ref' in obj:
|
|
582
|
+
ref = obj['$ref']
|
|
583
|
+
if ref.startswith('#/components/schemas/'):
|
|
584
|
+
schema_name = ref.split('/')[-1]
|
|
585
|
+
refs_set.add(schema_name)
|
|
586
|
+
for value in obj.values():
|
|
587
|
+
self._extract_schema_refs(value, refs_set)
|
|
588
|
+
elif isinstance(obj, list):
|
|
589
|
+
for item in obj:
|
|
590
|
+
self._extract_schema_refs(item, refs_set)
|
|
591
|
+
return
|
|
592
|
+
|
|
593
|
+
def _field_default_literal(self, schema: Dict[str, Any], required: bool) -> str:
|
|
594
|
+
if required:
|
|
595
|
+
return ""
|
|
596
|
+
|
|
597
|
+
if "default" in schema:
|
|
598
|
+
dval = schema["default"]
|
|
599
|
+
if isinstance(dval, str):
|
|
600
|
+
return f'"{dval}"'
|
|
601
|
+
return str(dval)
|
|
602
|
+
|
|
603
|
+
return "None"
|
|
604
|
+
|
|
605
|
+
def _file_slug(self, name: str) -> str:
|
|
606
|
+
"""
|
|
607
|
+
Creates a filesystem-friendly slug without underscores.
|
|
608
|
+
"""
|
|
609
|
+
slug = self._safe_snake(name).replace("_", "")
|
|
610
|
+
if slug == "":
|
|
611
|
+
slug = "generated"
|
|
612
|
+
if slug[0].isdigit():
|
|
613
|
+
slug = f"op{slug}"
|
|
614
|
+
return slug
|
|
615
|
+
|
|
616
|
+
def _generate_client_module(self, sorted_groups: List[str], clients_root: Path):
|
|
617
|
+
client_filename = f"{self._client_class_name.lower()}.py"
|
|
618
|
+
client_file = clients_root / client_filename
|
|
619
|
+
|
|
620
|
+
# Generate the class body first so the imports can be limited to the names it references.
|
|
621
|
+
body_lines: List[str] = []
|
|
622
|
+
base_class_name = self.REST_CLIENT_BASE_CLASS.__name__
|
|
623
|
+
body_lines.append(f"class {self._client_class_name}({base_class_name}):")
|
|
624
|
+
body_lines.append(' """')
|
|
625
|
+
body_lines.append(" GitHub public REST API client generated from the OpenAPI specification.")
|
|
626
|
+
body_lines.append(" \"\"\"")
|
|
627
|
+
aspects_type_name = self.ASPECTS_TYPE.__name__
|
|
628
|
+
body_lines.append(f" def __init__(self, host: str, credential: BaseCredential, port: Optional[int] = None, scheme: Optional[str] = \"https\", aspects: {aspects_type_name} = DEFAULT_REST_ASPECTS):")
|
|
629
|
+
body_lines.append(" super().__init__(host, credential, port, scheme=scheme, aspects=aspects)")
|
|
630
|
+
|
|
631
|
+
for group in sorted_groups:
|
|
632
|
+
gclass = f"{self._safe_pascal(group)}ApiGroup"
|
|
633
|
+
attr_name = f"_grp_{self._safe_snake(group)}"
|
|
634
|
+
body_lines.append(f" self.{attr_name} = {gclass}(self)")
|
|
635
|
+
body_lines.append(" return")
|
|
636
|
+
body_lines.append("")
|
|
637
|
+
|
|
638
|
+
for group in sorted_groups:
|
|
639
|
+
gclass = f"{self._safe_pascal(group)}ApiGroup"
|
|
640
|
+
attr_name = f"_grp_{self._safe_snake(group)}"
|
|
641
|
+
prop_name = self._safe_snake(group)
|
|
642
|
+
body_lines.append(" @property")
|
|
643
|
+
body_lines.append(f" def {prop_name}(self) -> {gclass}:")
|
|
644
|
+
body_lines.append(f" return self.{attr_name}")
|
|
645
|
+
body_lines.append("")
|
|
646
|
+
|
|
647
|
+
typing_imports = ["from typing import Optional"]
|
|
648
|
+
module_imports = ["import weakref"]
|
|
649
|
+
native_from_imports: List[str] = []
|
|
650
|
+
third_party_imports: List[str] = []
|
|
651
|
+
local_imports = [
|
|
652
|
+
self._import_statement_for_type(self.ASPECTS_TYPE, ["DEFAULT_REST_ASPECTS"]),
|
|
653
|
+
self._import_statement_for_type(self.REST_CLIENT_BASE_CLASS),
|
|
654
|
+
"from ccai.credentials.basecredential import BaseCredential",
|
|
655
|
+
]
|
|
656
|
+
|
|
657
|
+
for group in sorted_groups:
|
|
658
|
+
gclass = f"{self._safe_pascal(group)}ApiGroup"
|
|
659
|
+
gmodule = f"{self.GROUP_MODULE_ROOT}.{self._file_slug(group)}"
|
|
660
|
+
local_imports.append(f"from {gmodule} import {gclass}")
|
|
661
|
+
|
|
662
|
+
body_text = "\n".join(body_lines)
|
|
663
|
+
|
|
664
|
+
lines: List[str] = [AUTO_GENERATED_BANNER]
|
|
665
|
+
lines.extend(self._format_import_sections([
|
|
666
|
+
typing_imports,
|
|
667
|
+
module_imports,
|
|
668
|
+
native_from_imports,
|
|
669
|
+
third_party_imports,
|
|
670
|
+
local_imports,
|
|
671
|
+
], body_text=body_text))
|
|
672
|
+
lines.append("")
|
|
673
|
+
lines.append("")
|
|
674
|
+
lines.extend(body_lines)
|
|
675
|
+
|
|
676
|
+
content = "\n".join(lines).rstrip() + "\n"
|
|
677
|
+
self._write_file(client_file, content)
|
|
678
|
+
return
|
|
679
|
+
|
|
680
|
+
def _generate_group_module(self, group: str, ops: List[OperationSpec], groups_dir: Path):
|
|
681
|
+
"""
|
|
682
|
+
Generate API group module with Pythonic method signatures.
|
|
683
|
+
"""
|
|
684
|
+
slug = self._file_slug(group)
|
|
685
|
+
class_name = f"{self._safe_pascal(group)}ApiGroup"
|
|
686
|
+
|
|
687
|
+
# Collect all schema types used in this group module
|
|
688
|
+
used_types = set()
|
|
689
|
+
for op in ops:
|
|
690
|
+
# Collect from response schemas
|
|
691
|
+
schema_info = op.response_schema_info
|
|
692
|
+
if schema_info:
|
|
693
|
+
if schema_info.get("type") == "list":
|
|
694
|
+
item_schema = schema_info.get("item_schema", {})
|
|
695
|
+
self._collect_schema_types_from_schema(item_schema, used_types)
|
|
696
|
+
elif schema_info.get("type") == "single":
|
|
697
|
+
schema = schema_info.get("schema", {})
|
|
698
|
+
self._collect_schema_types_from_schema(schema, used_types)
|
|
699
|
+
|
|
700
|
+
# Collect from request body
|
|
701
|
+
if op.request_body:
|
|
702
|
+
body_schema = self._extract_request_body_schema(op.request_body)
|
|
703
|
+
if body_schema:
|
|
704
|
+
self._collect_schema_types_from_schema(body_schema, used_types)
|
|
705
|
+
|
|
706
|
+
# Generate the class body first so the imports can be limited to the names it references.
|
|
707
|
+
body_lines: List[str] = []
|
|
708
|
+
group_base_name = self.GROUP_BASE_TYPE.__name__
|
|
709
|
+
body_lines.append(f"class {class_name}({group_base_name}):")
|
|
710
|
+
tag_desc = self._tag_catalog.get(group, "")
|
|
711
|
+
if tag_desc:
|
|
712
|
+
body_lines.append(" \"\"\"")
|
|
713
|
+
body_lines.append(f" {literal_text(tag_desc)}")
|
|
714
|
+
body_lines.append(" \"\"\"")
|
|
715
|
+
|
|
716
|
+
for op in ops:
|
|
717
|
+
method_lines = self._generate_method_signature_and_body(op, group)
|
|
718
|
+
body_lines.extend(method_lines)
|
|
719
|
+
|
|
720
|
+
body_text = "\n".join(body_lines)
|
|
721
|
+
|
|
722
|
+
# Generate imports
|
|
723
|
+
module_lines: List[str] = [AUTO_GENERATED_BANNER]
|
|
724
|
+
typing_imports = ["from typing import Any, Dict, List, Optional, Union"]
|
|
725
|
+
module_imports: List[str] = []
|
|
726
|
+
native_from_imports: List[str] = []
|
|
727
|
+
third_party_imports: List[str] = []
|
|
728
|
+
local_imports = [
|
|
729
|
+
self._import_statement_for_type(self.ASPECTS_TYPE, ["DEFAULT_REST_ASPECTS"]),
|
|
730
|
+
self._import_statement_for_type(self.GROUP_BASE_TYPE),
|
|
731
|
+
self._import_statement_for_type(self.PAGEDLIST_TYPE),
|
|
732
|
+
]
|
|
733
|
+
|
|
734
|
+
# Add specific schema imports
|
|
735
|
+
if used_types:
|
|
736
|
+
for type_name in sorted(used_types):
|
|
737
|
+
if type_name in self._schema_imports:
|
|
738
|
+
local_imports.append(self._schema_imports[type_name])
|
|
739
|
+
|
|
740
|
+
module_lines.extend(self._format_import_sections([
|
|
741
|
+
typing_imports,
|
|
742
|
+
module_imports,
|
|
743
|
+
native_from_imports,
|
|
744
|
+
third_party_imports,
|
|
745
|
+
local_imports,
|
|
746
|
+
], body_text=body_text))
|
|
747
|
+
module_lines.append("")
|
|
748
|
+
module_lines.append("")
|
|
749
|
+
module_lines.extend(body_lines)
|
|
750
|
+
|
|
751
|
+
content = "\n".join(module_lines).rstrip() + "\n"
|
|
752
|
+
out_path = groups_dir / f"{slug}.py"
|
|
753
|
+
self._write_file(out_path, content)
|
|
754
|
+
return
|
|
755
|
+
|
|
756
|
+
def _generate_method_body(self, op: OperationSpec, path_params: List[ParameterSpec],
|
|
757
|
+
query_params: List[ParameterSpec], header_params: List[ParameterSpec],
|
|
758
|
+
has_body: bool) -> List[str]:
|
|
759
|
+
"""
|
|
760
|
+
Generate the method body that makes the HTTP call.
|
|
761
|
+
"""
|
|
762
|
+
lines: List[str] = []
|
|
763
|
+
|
|
764
|
+
# Get client reference and check aspects
|
|
765
|
+
lines.append(" client = self.client")
|
|
766
|
+
lines.append(" if aspects is None:")
|
|
767
|
+
lines.append(" aspects = client.aspects")
|
|
768
|
+
lines.append("")
|
|
769
|
+
lines.append(" header_params = client.headers")
|
|
770
|
+
lines.append(" if headers is not None:")
|
|
771
|
+
lines.append(" header_params = headers")
|
|
772
|
+
lines.append("")
|
|
773
|
+
|
|
774
|
+
# Build path
|
|
775
|
+
if path_params:
|
|
776
|
+
lines.append(f" leaf_template = \"{op.path}\"")
|
|
777
|
+
lines.append(" path_params = {")
|
|
778
|
+
for param in path_params:
|
|
779
|
+
param_name = self._safe_snake(param.name)
|
|
780
|
+
lines.append(f" '{param.name}': {param_name},")
|
|
781
|
+
lines.append(" }")
|
|
782
|
+
lines.append(" call_leaf = leaf_template.format(**path_params)")
|
|
783
|
+
else:
|
|
784
|
+
lines.append(f" call_leaf = \"{op.path}\"")
|
|
785
|
+
lines.append("")
|
|
786
|
+
|
|
787
|
+
# Build query params
|
|
788
|
+
if query_params:
|
|
789
|
+
lines.append(" query_params = {}")
|
|
790
|
+
for param in query_params:
|
|
791
|
+
param_name = self._safe_snake(param.name)
|
|
792
|
+
lines.append(f" if {param_name} is not None:")
|
|
793
|
+
lines.append(f" query_params['{param.name}'] = {param_name}")
|
|
794
|
+
else:
|
|
795
|
+
lines.append(" query_params = None")
|
|
796
|
+
lines.append("")
|
|
797
|
+
|
|
798
|
+
# Build header params
|
|
799
|
+
if header_params:
|
|
800
|
+
lines.append(" if header_params is None:")
|
|
801
|
+
lines.append(" header_params = {}")
|
|
802
|
+
for param in header_params:
|
|
803
|
+
param_name = self._safe_snake(param.name)
|
|
804
|
+
lines.append(f" if {param_name} is not None:")
|
|
805
|
+
lines.append(f" header_params['{param.name}'] = {param_name}")
|
|
806
|
+
lines.append("")
|
|
807
|
+
|
|
808
|
+
# Make the call
|
|
809
|
+
default_exp_status = self._expected_status_codes(op.responses)
|
|
810
|
+
lines.append(f" if exp_status is None:")
|
|
811
|
+
lines.append(f" exp_status = {default_exp_status}")
|
|
812
|
+
lines.append("")
|
|
813
|
+
lines.append(" resp = client.perform_call(")
|
|
814
|
+
lines.append(" leaf=call_leaf,")
|
|
815
|
+
lines.append(f" method=\"{op.http_method}\",")
|
|
816
|
+
lines.append(" params=query_params if query_params else None,")
|
|
817
|
+
if has_body:
|
|
818
|
+
lines.append(" body=body,")
|
|
819
|
+
else:
|
|
820
|
+
lines.append(" body=None,")
|
|
821
|
+
lines.append(" exp_status=exp_status,")
|
|
822
|
+
lines.append(" headers=header_params if header_params else None,")
|
|
823
|
+
lines.append(" context_msg=None,")
|
|
824
|
+
lines.append(" aspects=aspects,")
|
|
825
|
+
lines.append(" )")
|
|
826
|
+
|
|
827
|
+
# Parse and return response
|
|
828
|
+
lines.extend(self._generate_response_parsing(op))
|
|
829
|
+
|
|
830
|
+
return lines
|
|
831
|
+
|
|
832
|
+
def _generate_method_signature_and_body(self, op: OperationSpec, group: str) -> List[str]:
|
|
833
|
+
"""
|
|
834
|
+
Generate a single API method with Pythonic signature.
|
|
835
|
+
|
|
836
|
+
Signature order:
|
|
837
|
+
1. Required path parameters (positional)
|
|
838
|
+
2. Request body with schema type (positional, if present)
|
|
839
|
+
3. Mandatory query/header parameters (positional)
|
|
840
|
+
4. * (keyword-only marker)
|
|
841
|
+
5. Optional query/header parameters (kwargs)
|
|
842
|
+
6. aspects parameter (framework, last)
|
|
843
|
+
"""
|
|
844
|
+
lines: List[str] = []
|
|
845
|
+
method_name = self._safe_snake(op.method_name)
|
|
846
|
+
|
|
847
|
+
# Build signature parts
|
|
848
|
+
sig_params: List[str] = ["self"]
|
|
849
|
+
|
|
850
|
+
# Collect parameters by type
|
|
851
|
+
path_params = [p for p in op.parameters if p.location == "path"]
|
|
852
|
+
query_params = [p for p in op.parameters if p.location == "query"]
|
|
853
|
+
header_params = [p for p in op.parameters if p.location == "header"]
|
|
854
|
+
|
|
855
|
+
# 1. Required path parameters (always first)
|
|
856
|
+
for param in path_params:
|
|
857
|
+
param_name = self._safe_snake(param.name)
|
|
858
|
+
param_type = self._schema_to_type(param.schema)
|
|
859
|
+
sig_params.append(f"{param_name}: {param_type}")
|
|
860
|
+
|
|
861
|
+
# 2. Request body with actual schema type
|
|
862
|
+
body_type_str = None
|
|
863
|
+
if op.request_body:
|
|
864
|
+
body_schema = self._extract_request_body_schema(op.request_body)
|
|
865
|
+
if body_schema:
|
|
866
|
+
body_type_str = self._schema_to_type(body_schema)
|
|
867
|
+
sig_params.append(f"body: {body_type_str}")
|
|
868
|
+
|
|
869
|
+
# 3. Mandatory (required) query/header parameters
|
|
870
|
+
mandatory_qh_params = [p for p in query_params + header_params if p.required]
|
|
871
|
+
for param in mandatory_qh_params:
|
|
872
|
+
param_name = self._safe_snake(param.name)
|
|
873
|
+
param_type = self._schema_to_type(param.schema)
|
|
874
|
+
sig_params.append(f"{param_name}: {param_type}")
|
|
875
|
+
|
|
876
|
+
# 4. Mark start of keyword-only parameters
|
|
877
|
+
sig_params.append("*")
|
|
878
|
+
|
|
879
|
+
# 5. Optional query/header parameters
|
|
880
|
+
optional_qh_params = [p for p in query_params + header_params if not p.required]
|
|
881
|
+
for param in optional_qh_params:
|
|
882
|
+
param_name = self._safe_snake(param.name)
|
|
883
|
+
param_type = self._schema_to_type(param.schema)
|
|
884
|
+
default = self._field_default_literal(param.schema, False) or "None"
|
|
885
|
+
sig_params.append(f"{param_name}: Optional[{param_type}] = {default}")
|
|
886
|
+
|
|
887
|
+
# 6. Framework parameters (optional)
|
|
888
|
+
sig_params.append("exp_status: Optional[List[int]] = None")
|
|
889
|
+
sig_params.append("headers: Optional[Dict[str, str]] = None")
|
|
890
|
+
aspects_type_name = self.ASPECTS_TYPE.__name__
|
|
891
|
+
sig_params.append(f"aspects: Optional[{aspects_type_name}] = None")
|
|
892
|
+
|
|
893
|
+
# Determine return type
|
|
894
|
+
return_type = self._determine_return_type(op)
|
|
895
|
+
|
|
896
|
+
# Generate method signature
|
|
897
|
+
lines.append("")
|
|
898
|
+
sig_line = f" def {method_name}({', '.join(sig_params)}) -> {return_type}:"
|
|
899
|
+
lines.append(sig_line)
|
|
900
|
+
lines.append(" \"\"\"")
|
|
901
|
+
if op.summary:
|
|
902
|
+
lines.append(f" {literal_text(op.summary)}")
|
|
903
|
+
if op.description and op.description != op.summary:
|
|
904
|
+
lines.append(f" ")
|
|
905
|
+
lines.append(f" {literal_text(op.description)}")
|
|
906
|
+
lines.append(" \"\"\"")
|
|
907
|
+
|
|
908
|
+
# Generate method body
|
|
909
|
+
lines.extend(self._generate_method_body(op, path_params, query_params, header_params, body_type_str is not None))
|
|
910
|
+
|
|
911
|
+
return lines
|
|
912
|
+
|
|
913
|
+
def _generate_response_parsing(self, op: OperationSpec) -> List[str]:
|
|
914
|
+
"""
|
|
915
|
+
Generate code to parse the response and return the appropriate type.
|
|
916
|
+
"""
|
|
917
|
+
lines: List[str] = []
|
|
918
|
+
schema_info = op.response_schema_info
|
|
919
|
+
|
|
920
|
+
# A success status can legitimately carry no content (204/205, or an empty
|
|
921
|
+
# 202 "Accepted"). Guard resp.json() so those return None instead of raising
|
|
922
|
+
# on an empty body; any other status still parses, so an unexpected-empty 200
|
|
923
|
+
# surfaces as an error rather than being silently masked.
|
|
924
|
+
no_content_guard = "resp.status_code in (204, 205) or (resp.status_code == 202 and len(resp.content) == 0)"
|
|
925
|
+
|
|
926
|
+
if not schema_info:
|
|
927
|
+
lines.append(f" if {no_content_guard}:")
|
|
928
|
+
lines.append(" rtnval = None")
|
|
929
|
+
lines.append(" else:")
|
|
930
|
+
lines.append(" rtnval = resp.json()")
|
|
931
|
+
lines.append(" return rtnval")
|
|
932
|
+
return lines
|
|
933
|
+
|
|
934
|
+
if schema_info.get("type") == "list":
|
|
935
|
+
item_schema = schema_info.get("item_schema", {})
|
|
936
|
+
item_type = self._schema_to_type(item_schema)
|
|
937
|
+
|
|
938
|
+
lines.append(" raw_data = resp.json()")
|
|
939
|
+
lines.append(f" items = [self._parse_item(item, {item_type}) for item in raw_data]")
|
|
940
|
+
|
|
941
|
+
if self._is_paginated_operation(op):
|
|
942
|
+
pagedlist_type_name = self.PAGEDLIST_TYPE.__name__
|
|
943
|
+
lines.append(f" rtnval = {pagedlist_type_name}[{item_type}](items, dict(resp.headers), raw_data)")
|
|
944
|
+
lines.append(" return rtnval")
|
|
945
|
+
else:
|
|
946
|
+
lines.append(" return items")
|
|
947
|
+
|
|
948
|
+
elif schema_info.get("type") == "single":
|
|
949
|
+
schema = schema_info.get("schema", {})
|
|
950
|
+
data_type = self._schema_to_type(schema)
|
|
951
|
+
|
|
952
|
+
# Check if this is a custom SchemaObject type (has $ref) or primitive
|
|
953
|
+
if "$ref" in schema:
|
|
954
|
+
# Custom type with from_dict method
|
|
955
|
+
lines.append(f" if {no_content_guard}:")
|
|
956
|
+
lines.append(" rtnobj = None")
|
|
957
|
+
lines.append(" else:")
|
|
958
|
+
lines.append(" raw_data = resp.json()")
|
|
959
|
+
lines.append(f" rtnobj = {data_type}.from_dict(raw_data)")
|
|
960
|
+
lines.append(" return rtnobj")
|
|
961
|
+
else:
|
|
962
|
+
# Primitive type or Dict[str, Any] - return directly or use _parse_item
|
|
963
|
+
lines.append(f" if {no_content_guard}:")
|
|
964
|
+
lines.append(" rtnval = None")
|
|
965
|
+
lines.append(" else:")
|
|
966
|
+
lines.append(" raw_data = resp.json()")
|
|
967
|
+
lines.append(f" rtnval = self._parse_item(raw_data, {data_type})")
|
|
968
|
+
lines.append(" return rtnval")
|
|
969
|
+
|
|
970
|
+
return lines
|
|
971
|
+
|
|
972
|
+
def _generate_schema_modules(self, schemas_dir: Path):
|
|
973
|
+
"""
|
|
974
|
+
Generate schema modules organized by tag/operation.
|
|
975
|
+
"""
|
|
976
|
+
# Group schemas by their target file
|
|
977
|
+
schemas_by_file: Dict[str, List[Tuple[str, TypeSpec]]] = {}
|
|
978
|
+
|
|
979
|
+
self._schema_imports.clear()
|
|
980
|
+
|
|
981
|
+
for schema_name, type_spec in self._schema_types.items():
|
|
982
|
+
file_name = self._determine_schema_file(schema_name)
|
|
983
|
+
if file_name not in schemas_by_file:
|
|
984
|
+
schemas_by_file[file_name] = []
|
|
985
|
+
schemas_by_file[file_name].append((schema_name, type_spec))
|
|
986
|
+
import_stmt = f"from {self.SCHEMA_MODULE_ROOT}.{file_name} import {type_spec.name}"
|
|
987
|
+
self._schema_imports[type_spec.name] = import_stmt
|
|
988
|
+
|
|
989
|
+
# Generate each schema file
|
|
990
|
+
for file_name, schemas in sorted(schemas_by_file.items()):
|
|
991
|
+
emit_schemas: List[Tuple[str, TypeSpec]] = []
|
|
992
|
+
class_lines_by_type: Dict[str, List[str]] = {}
|
|
993
|
+
|
|
994
|
+
for schema_name, type_spec in schemas:
|
|
995
|
+
class_lines = self._generate_type_class(type_spec)
|
|
996
|
+
if class_lines:
|
|
997
|
+
emit_schemas.append((schema_name, type_spec))
|
|
998
|
+
class_lines_by_type[type_spec.name] = class_lines
|
|
999
|
+
|
|
1000
|
+
out_path = schemas_dir / f"{file_name}.py"
|
|
1001
|
+
if not emit_schemas:
|
|
1002
|
+
if out_path.exists():
|
|
1003
|
+
out_path.unlink()
|
|
1004
|
+
continue
|
|
1005
|
+
|
|
1006
|
+
# Generate schema classes for this file first so the imports can be limited to the names they reference.
|
|
1007
|
+
body_lines: List[str] = []
|
|
1008
|
+
ordered_schemas = self._order_schema_definitions(emit_schemas)
|
|
1009
|
+
for schema_name, type_spec in ordered_schemas:
|
|
1010
|
+
class_lines = class_lines_by_type.get(type_spec.name, [])
|
|
1011
|
+
if not class_lines:
|
|
1012
|
+
continue
|
|
1013
|
+
body_lines.extend(class_lines)
|
|
1014
|
+
body_lines.append("")
|
|
1015
|
+
body_lines.append("")
|
|
1016
|
+
|
|
1017
|
+
body_text = "\n".join(body_lines)
|
|
1018
|
+
|
|
1019
|
+
module_lines: List[str] = [AUTO_GENERATED_BANNER]
|
|
1020
|
+
module_lines.append("from __future__ import annotations")
|
|
1021
|
+
module_lines.append("")
|
|
1022
|
+
typing_imports = ["from typing import Any, Dict, List, Optional, Union"]
|
|
1023
|
+
module_imports: List[str] = []
|
|
1024
|
+
native_from_imports: List[str] = []
|
|
1025
|
+
third_party_imports: List[str] = []
|
|
1026
|
+
local_imports = [
|
|
1027
|
+
self._import_statement_for_type(self.SCHEMA_BASE_TYPE),
|
|
1028
|
+
self._import_statement_for_type(self.SCHEMA_FIELD_TYPE),
|
|
1029
|
+
]
|
|
1030
|
+
module_lines.extend(self._format_import_sections([
|
|
1031
|
+
typing_imports,
|
|
1032
|
+
module_imports,
|
|
1033
|
+
native_from_imports,
|
|
1034
|
+
third_party_imports,
|
|
1035
|
+
local_imports,
|
|
1036
|
+
], body_text=body_text))
|
|
1037
|
+
module_lines.append("")
|
|
1038
|
+
module_lines.append("")
|
|
1039
|
+
module_lines.extend(body_lines)
|
|
1040
|
+
|
|
1041
|
+
content = "\n".join(module_lines).rstrip() + "\n"
|
|
1042
|
+
self._write_file(out_path, content)
|
|
1043
|
+
return
|
|
1044
|
+
|
|
1045
|
+
def _generate_type_class(self, type_spec: TypeSpec) -> List[str]:
|
|
1046
|
+
"""
|
|
1047
|
+
Generate a class that inherits from SchemaObject using Field descriptors.
|
|
1048
|
+
"""
|
|
1049
|
+
lines: List[str] = []
|
|
1050
|
+
schema = type_spec.schema
|
|
1051
|
+
|
|
1052
|
+
# Handle simple types (parameters) - skip generation
|
|
1053
|
+
if not self._schema_can_generate_class(schema):
|
|
1054
|
+
return lines
|
|
1055
|
+
|
|
1056
|
+
properties = schema.get("properties", {})
|
|
1057
|
+
required_fields = schema.get("required", [])
|
|
1058
|
+
|
|
1059
|
+
# Generate class definition
|
|
1060
|
+
schema_base_name = self.SCHEMA_BASE_TYPE.__name__
|
|
1061
|
+
lines.append(f"class {type_spec.name}({schema_base_name}):")
|
|
1062
|
+
|
|
1063
|
+
# Docstring
|
|
1064
|
+
if type_spec.description:
|
|
1065
|
+
lines.append(' """')
|
|
1066
|
+
lines.append(f" {literal_text(type_spec.description)}")
|
|
1067
|
+
lines.append(' """')
|
|
1068
|
+
|
|
1069
|
+
# Generate Field descriptors for each property
|
|
1070
|
+
for field_name, prop_schema in properties.items():
|
|
1071
|
+
attr_name = self._safe_snake(field_name)
|
|
1072
|
+
field_type_str = self._schema_to_type(prop_schema, use_forward_refs=True)
|
|
1073
|
+
is_required = field_name in required_fields
|
|
1074
|
+
description = prop_schema.get("description", "")
|
|
1075
|
+
|
|
1076
|
+
# Escape description for string literal
|
|
1077
|
+
if description:
|
|
1078
|
+
description = literal_text(description).replace('"', '\\"').replace('\n', ' ').replace('\r', '')
|
|
1079
|
+
|
|
1080
|
+
# Build Field() call
|
|
1081
|
+
field_parts = [field_type_str]
|
|
1082
|
+
if is_required:
|
|
1083
|
+
field_parts.append("required=True")
|
|
1084
|
+
if description:
|
|
1085
|
+
field_parts.append(f'description="{description}"')
|
|
1086
|
+
|
|
1087
|
+
field_def = f" {attr_name} = Field({', '.join(field_parts)})"
|
|
1088
|
+
lines.append(field_def)
|
|
1089
|
+
|
|
1090
|
+
return lines
|
|
1091
|
+
|
|
1092
|
+
def _get_api_method_hints(self, path: str, http_method: str) -> Dict[str, Any]:
|
|
1093
|
+
"""
|
|
1094
|
+
Get API hints for a specific path and method.
|
|
1095
|
+
|
|
1096
|
+
:param path: The API path.
|
|
1097
|
+
:param http_method: The HTTP method.
|
|
1098
|
+
|
|
1099
|
+
:returns: Dictionary of hints for the API method.
|
|
1100
|
+
"""
|
|
1101
|
+
path_hints = self._api_hints.get("paths", {}).get(path, {})
|
|
1102
|
+
method_hints = path_hints.get(http_method.lower(), {}) or {}
|
|
1103
|
+
return method_hints
|
|
1104
|
+
|
|
1105
|
+
def _has_pagination_parameters(self, parameters: List[ParameterSpec]) -> bool:
|
|
1106
|
+
param_names = [p.name for p in parameters if p.location == "query"]
|
|
1107
|
+
page_params = self._pagination_hints.get("detection_rules", {}).get(
|
|
1108
|
+
"query_parameters", {}).get("parameters", ["page", "per_page"])
|
|
1109
|
+
return any(pp in param_names for pp in page_params)
|
|
1110
|
+
|
|
1111
|
+
def _import_statement_for_type(self, type_obj: Type, extra_names: Optional[List[str]] = None) -> str:
|
|
1112
|
+
"""
|
|
1113
|
+
Build a from-import statement for a given type.
|
|
1114
|
+
"""
|
|
1115
|
+
module_name = type_obj.__module__
|
|
1116
|
+
type_name = type_obj.__name__
|
|
1117
|
+
if extra_names:
|
|
1118
|
+
names_list = [type_name] + extra_names
|
|
1119
|
+
names = ", ".join(sorted(names_list))
|
|
1120
|
+
else:
|
|
1121
|
+
names = type_name
|
|
1122
|
+
return f"from {module_name} import {names}"
|
|
1123
|
+
|
|
1124
|
+
def _is_paginated_operation(self, op: OperationSpec) -> bool:
|
|
1125
|
+
"""
|
|
1126
|
+
Determine if an operation returns paginated results.
|
|
1127
|
+
|
|
1128
|
+
:returns: True if the operation is paginated
|
|
1129
|
+
"""
|
|
1130
|
+
if op.archetype == "paged-collection":
|
|
1131
|
+
return True
|
|
1132
|
+
if op.archetype == "collection":
|
|
1133
|
+
return False
|
|
1134
|
+
|
|
1135
|
+
# Check if it's a list response
|
|
1136
|
+
if op.response_schema_info and op.response_schema_info.get("type") != "list":
|
|
1137
|
+
return False
|
|
1138
|
+
|
|
1139
|
+
# Check if it has page/per_page parameters
|
|
1140
|
+
param_names = [p.name for p in op.parameters]
|
|
1141
|
+
page_params = self._pagination_hints.get("detection_rules", {}).get(
|
|
1142
|
+
"query_parameters", {}).get("parameters", ["page", "per_page"])
|
|
1143
|
+
|
|
1144
|
+
has_page_params = any(pp in param_names for pp in page_params)
|
|
1145
|
+
|
|
1146
|
+
return has_page_params
|
|
1147
|
+
|
|
1148
|
+
def _load_api_hints(self) -> Dict[str, Any]:
|
|
1149
|
+
"""
|
|
1150
|
+
Load API hints configuration. This is a dictionary keyed by API path
|
|
1151
|
+
that provides hints for code generation (e.g. method-name or operationId overrides).
|
|
1152
|
+
"""
|
|
1153
|
+
hints: Dict[str, Any] = {"paths": {}}
|
|
1154
|
+
|
|
1155
|
+
json_file = self._spec_path.parent / "api-hints.json"
|
|
1156
|
+
if json_file.exists():
|
|
1157
|
+
with open(json_file, "r", encoding="utf-8") as hf:
|
|
1158
|
+
loaded = json.load(hf)
|
|
1159
|
+
normalized = self._normalize_api_hints(loaded)
|
|
1160
|
+
self._merge_api_hints(hints, normalized)
|
|
1161
|
+
|
|
1162
|
+
yaml_file = self._spec_path.parent / "api-hints.yaml"
|
|
1163
|
+
if not yaml_file.exists():
|
|
1164
|
+
yaml_file = self._spec_path.parent / "api-hints.yml"
|
|
1165
|
+
|
|
1166
|
+
if yaml_file.exists():
|
|
1167
|
+
if yaml is None:
|
|
1168
|
+
errmsg = "Yaml hints file found but PyYAML is not installed. Install PyYAML to use api-hints.yaml."
|
|
1169
|
+
raise RuntimeError(errmsg)
|
|
1170
|
+
with open(yaml_file, "r", encoding="utf-8") as hf:
|
|
1171
|
+
loaded = yaml.safe_load(hf)
|
|
1172
|
+
normalized = self._normalize_api_hints(loaded)
|
|
1173
|
+
self._merge_api_hints(hints, normalized)
|
|
1174
|
+
|
|
1175
|
+
return hints
|
|
1176
|
+
|
|
1177
|
+
def _load_openapi_spec(self, spec_path: Path) -> Dict[str, Any]:
|
|
1178
|
+
"""
|
|
1179
|
+
Load an OpenAPI specification file from JSON or YAML.
|
|
1180
|
+
"""
|
|
1181
|
+
suffix = spec_path.suffix.lower()
|
|
1182
|
+
if suffix in (".yaml", ".yml"):
|
|
1183
|
+
if yaml is None:
|
|
1184
|
+
errmsg = "Yaml OpenAPI spec file provided but PyYAML is not installed."
|
|
1185
|
+
raise RuntimeError(errmsg)
|
|
1186
|
+
with open(spec_path, "r", encoding="utf-8") as sf:
|
|
1187
|
+
return yaml.safe_load(sf)
|
|
1188
|
+
if suffix == ".json":
|
|
1189
|
+
with open(spec_path, "r", encoding="utf-8") as sf:
|
|
1190
|
+
return json.load(sf)
|
|
1191
|
+
|
|
1192
|
+
with open(spec_path, "r", encoding="utf-8") as sf:
|
|
1193
|
+
raw_content = sf.read()
|
|
1194
|
+
|
|
1195
|
+
try:
|
|
1196
|
+
return json.loads(raw_content)
|
|
1197
|
+
except json.JSONDecodeError:
|
|
1198
|
+
if yaml is None:
|
|
1199
|
+
errmsg = "Unable to parse OpenAPI spec as JSON and PyYAML is not installed."
|
|
1200
|
+
raise RuntimeError(errmsg)
|
|
1201
|
+
return yaml.safe_load(raw_content)
|
|
1202
|
+
|
|
1203
|
+
def _merge_api_hints(self, base: Dict[str, Any], incoming: Dict[str, Any]):
|
|
1204
|
+
"""
|
|
1205
|
+
Merge API hints dictionaries with incoming values overriding base values.
|
|
1206
|
+
|
|
1207
|
+
:param base: Base hints dictionary.
|
|
1208
|
+
:param incoming: Incoming hints dictionary.
|
|
1209
|
+
"""
|
|
1210
|
+
base_paths = base.setdefault("paths", {})
|
|
1211
|
+
incoming_paths = incoming.get("paths", {})
|
|
1212
|
+
for path, methods in incoming_paths.items():
|
|
1213
|
+
if path not in base_paths:
|
|
1214
|
+
base_paths[path] = methods
|
|
1215
|
+
continue
|
|
1216
|
+
for method, method_hints in methods.items():
|
|
1217
|
+
if method not in base_paths[path]:
|
|
1218
|
+
base_paths[path][method] = method_hints
|
|
1219
|
+
elif isinstance(base_paths[path][method], dict) and isinstance(method_hints, dict):
|
|
1220
|
+
base_paths[path][method].update(method_hints)
|
|
1221
|
+
else:
|
|
1222
|
+
base_paths[path][method] = method_hints
|
|
1223
|
+
return
|
|
1224
|
+
|
|
1225
|
+
def _normalize_api_hints(self, hints: Optional[Dict[str, Any]]) -> Dict[str, Any]:
|
|
1226
|
+
"""
|
|
1227
|
+
Normalize hints to a dictionary with a top-level 'paths' key.
|
|
1228
|
+
|
|
1229
|
+
:param hints: Raw hints dictionary loaded from json/yaml.
|
|
1230
|
+
|
|
1231
|
+
:returns: Normalized hints dictionary.
|
|
1232
|
+
"""
|
|
1233
|
+
normalized: Dict[str, Any] = {"paths": {}}
|
|
1234
|
+
if not hints:
|
|
1235
|
+
return normalized
|
|
1236
|
+
|
|
1237
|
+
if "paths" in hints:
|
|
1238
|
+
paths = hints.get("paths", {})
|
|
1239
|
+
else:
|
|
1240
|
+
paths = hints
|
|
1241
|
+
|
|
1242
|
+
for path, methods in paths.items():
|
|
1243
|
+
if not isinstance(methods, dict):
|
|
1244
|
+
continue
|
|
1245
|
+
method_map: Dict[str, Any] = {}
|
|
1246
|
+
for method, method_hints in methods.items():
|
|
1247
|
+
method_key = method.lower()
|
|
1248
|
+
method_map[method_key] = method_hints
|
|
1249
|
+
normalized["paths"][path] = method_map
|
|
1250
|
+
|
|
1251
|
+
return normalized
|
|
1252
|
+
|
|
1253
|
+
def _normalize_archetype(self, archetype: Optional[str]) -> Optional[str]:
|
|
1254
|
+
if not archetype:
|
|
1255
|
+
return None
|
|
1256
|
+
archetype = str(archetype).strip().lower()
|
|
1257
|
+
return archetype
|
|
1258
|
+
|
|
1259
|
+
def _order_schema_definitions(self, schemas: List[Tuple[str, TypeSpec]]) -> List[Tuple[str, TypeSpec]]:
|
|
1260
|
+
"""
|
|
1261
|
+
Order schema definitions so dependent types in the same module are defined first.
|
|
1262
|
+
"""
|
|
1263
|
+
schema_by_name: Dict[str, Tuple[str, TypeSpec]] = {}
|
|
1264
|
+
dependencies_by_name: Dict[str, set] = {}
|
|
1265
|
+
|
|
1266
|
+
for schema_name, type_spec in schemas:
|
|
1267
|
+
schema_by_name[type_spec.name] = (schema_name, type_spec)
|
|
1268
|
+
|
|
1269
|
+
for schema_name, type_spec in schemas:
|
|
1270
|
+
dependencies: set = set()
|
|
1271
|
+
self._collect_schema_types_from_properties(type_spec.schema, dependencies)
|
|
1272
|
+
dependencies.discard(type_spec.name)
|
|
1273
|
+
dependencies.intersection_update(schema_by_name.keys())
|
|
1274
|
+
dependencies_by_name[type_spec.name] = dependencies
|
|
1275
|
+
|
|
1276
|
+
ordered: List[Tuple[str, TypeSpec]] = []
|
|
1277
|
+
pending = sorted(schema_by_name.keys())
|
|
1278
|
+
|
|
1279
|
+
while pending:
|
|
1280
|
+
ready = [name for name in pending if not dependencies_by_name[name]]
|
|
1281
|
+
if not ready:
|
|
1282
|
+
break
|
|
1283
|
+
|
|
1284
|
+
for name in ready:
|
|
1285
|
+
pending.remove(name)
|
|
1286
|
+
ordered.append(schema_by_name[name])
|
|
1287
|
+
for remaining in pending:
|
|
1288
|
+
dependencies_by_name[remaining].discard(name)
|
|
1289
|
+
|
|
1290
|
+
for name in pending:
|
|
1291
|
+
ordered.append(schema_by_name[name])
|
|
1292
|
+
|
|
1293
|
+
return ordered
|
|
1294
|
+
|
|
1295
|
+
def _process_spec(self):
|
|
1296
|
+
spec = self._spec
|
|
1297
|
+
|
|
1298
|
+
for item in spec.get("tags", []):
|
|
1299
|
+
name = item["name"]
|
|
1300
|
+
desc = item.get("description", "")
|
|
1301
|
+
self._tag_catalog[self._safe_snake(name)] = desc
|
|
1302
|
+
|
|
1303
|
+
path_catalog: Dict[str, dict] = spec["paths"]
|
|
1304
|
+
for path_leaf, method_catalog in path_catalog.items():
|
|
1305
|
+
path_level_params = method_catalog.get("parameters", [])
|
|
1306
|
+
for call_method, op_desc in method_catalog.items():
|
|
1307
|
+
if call_method not in SUPPORTED_HTTP_METHODS:
|
|
1308
|
+
continue
|
|
1309
|
+
|
|
1310
|
+
operation_id = op_desc.get("operationId", "")
|
|
1311
|
+
method_hints = self._get_api_method_hints(path_leaf, call_method)
|
|
1312
|
+
if "operationId" in method_hints:
|
|
1313
|
+
operation_id = method_hints["operationId"]
|
|
1314
|
+
tags = op_desc.get("tags", [])
|
|
1315
|
+
summary = op_desc.get("summary", "")
|
|
1316
|
+
description = op_desc.get("description", "")
|
|
1317
|
+
external_docs = op_desc.get("externalDocs")
|
|
1318
|
+
responses = op_desc.get("responses", {})
|
|
1319
|
+
request_body = op_desc.get("requestBody")
|
|
1320
|
+
|
|
1321
|
+
group_name, method_name = self._derive_group_and_method(operation_id, tags, path_leaf, call_method)
|
|
1322
|
+
|
|
1323
|
+
parameters = self._collect_parameters(
|
|
1324
|
+
path_level_params, op_desc.get("parameters", [])
|
|
1325
|
+
)
|
|
1326
|
+
|
|
1327
|
+
# Extract response schema information
|
|
1328
|
+
response_schema_info = self._extract_response_schema_info(responses)
|
|
1329
|
+
|
|
1330
|
+
archetype = self._detect_api_archetype(
|
|
1331
|
+
path_leaf, call_method, operation_id, op_desc, parameters, response_schema_info
|
|
1332
|
+
)
|
|
1333
|
+
|
|
1334
|
+
op = OperationSpec(
|
|
1335
|
+
path=path_leaf,
|
|
1336
|
+
http_method=call_method.upper(),
|
|
1337
|
+
group=group_name,
|
|
1338
|
+
operation_id=operation_id,
|
|
1339
|
+
method_name=method_name,
|
|
1340
|
+
summary=summary,
|
|
1341
|
+
description=description,
|
|
1342
|
+
parameters=parameters,
|
|
1343
|
+
request_body=request_body,
|
|
1344
|
+
responses=responses,
|
|
1345
|
+
external_docs=external_docs,
|
|
1346
|
+
response_schema_info=response_schema_info,
|
|
1347
|
+
archetype=archetype,
|
|
1348
|
+
)
|
|
1349
|
+
self._groups.setdefault(group_name, []).append(op)
|
|
1350
|
+
return
|
|
1351
|
+
|
|
1352
|
+
def _resolve_ref(self, ref_path: str):
|
|
1353
|
+
if not ref_path.startswith("#/"):
|
|
1354
|
+
errmsg = f"Unsupported reference format '{ref_path}'."
|
|
1355
|
+
raise ValueError(errmsg)
|
|
1356
|
+
|
|
1357
|
+
segments = ref_path.lstrip("#/").split("/")
|
|
1358
|
+
obj: Any = self._spec
|
|
1359
|
+
for segment in segments:
|
|
1360
|
+
obj = obj[segment]
|
|
1361
|
+
return obj
|
|
1362
|
+
|
|
1363
|
+
def _safe_snake(self, name: str) -> str:
|
|
1364
|
+
snake = re.sub(r"[^0-9a-zA-Z]+", "_", name).strip("_").lower()
|
|
1365
|
+
if snake == "" or snake[0].isdigit() or keyword.iskeyword(snake):
|
|
1366
|
+
snake = f"op_{snake}"
|
|
1367
|
+
return snake
|
|
1368
|
+
|
|
1369
|
+
def _safe_pascal(self, name: str) -> str:
|
|
1370
|
+
parts = re.split(r"[^0-9a-zA-Z]+", name)
|
|
1371
|
+
pascal = "".join([p.capitalize() for p in parts if p])
|
|
1372
|
+
if pascal == "":
|
|
1373
|
+
pascal = "Generated"
|
|
1374
|
+
if pascal[0].isdigit():
|
|
1375
|
+
pascal = f"Op{pascal}"
|
|
1376
|
+
return pascal
|
|
1377
|
+
|
|
1378
|
+
def _schema_can_generate_class(self, schema: Dict[str, Any]) -> bool:
|
|
1379
|
+
"""
|
|
1380
|
+
Determine if a schema can generate a SchemaObject class.
|
|
1381
|
+
"""
|
|
1382
|
+
if "properties" not in schema:
|
|
1383
|
+
return False
|
|
1384
|
+
|
|
1385
|
+
properties = schema.get("properties", {})
|
|
1386
|
+
if not properties:
|
|
1387
|
+
return False
|
|
1388
|
+
|
|
1389
|
+
attr_names = [self._safe_snake(fname) for fname in properties.keys()]
|
|
1390
|
+
if len(attr_names) != len(set(attr_names)):
|
|
1391
|
+
return False
|
|
1392
|
+
|
|
1393
|
+
return True
|
|
1394
|
+
|
|
1395
|
+
def _schema_to_type(self, schema: Dict[str, Any], nullable: bool = False, refs_seen: Optional[set] = None, use_forward_refs: bool = False) -> str:
|
|
1396
|
+
"""
|
|
1397
|
+
Convert an OpenAPI schema to a Python type annotation.
|
|
1398
|
+
"""
|
|
1399
|
+
if refs_seen is None:
|
|
1400
|
+
refs_seen = set()
|
|
1401
|
+
|
|
1402
|
+
if "$ref" in schema:
|
|
1403
|
+
ref_path = schema["$ref"]
|
|
1404
|
+
# Extract the type name from the reference
|
|
1405
|
+
schema_name = ref_path.split("/")[-1]
|
|
1406
|
+
type_name = self._safe_pascal(schema_name)
|
|
1407
|
+
|
|
1408
|
+
if schema_name in refs_seen:
|
|
1409
|
+
return "Any"
|
|
1410
|
+
|
|
1411
|
+
refs_seen.add(schema_name)
|
|
1412
|
+
|
|
1413
|
+
type_spec = self._schema_types.get(schema_name)
|
|
1414
|
+
if type_spec:
|
|
1415
|
+
if self._schema_can_generate_class(type_spec.schema):
|
|
1416
|
+
type_expr = f"\"{type_name}\"" if use_forward_refs else type_name
|
|
1417
|
+
if nullable or schema.get("nullable", False):
|
|
1418
|
+
return f"Optional[{type_expr}]"
|
|
1419
|
+
return type_expr
|
|
1420
|
+
return self._schema_to_type(type_spec.schema, nullable, refs_seen, use_forward_refs)
|
|
1421
|
+
|
|
1422
|
+
if nullable or schema.get("nullable", False):
|
|
1423
|
+
return "Optional[Any]"
|
|
1424
|
+
return "Any"
|
|
1425
|
+
|
|
1426
|
+
# Check for nullable at the schema level
|
|
1427
|
+
is_nullable = nullable or schema.get("nullable", False)
|
|
1428
|
+
|
|
1429
|
+
# Handle oneOf/anyOf (use Union)
|
|
1430
|
+
if "oneOf" in schema or "anyOf" in schema:
|
|
1431
|
+
variants = schema.get("oneOf") or schema.get("anyOf") or []
|
|
1432
|
+
types = [self._schema_to_type(v, False, refs_seen, use_forward_refs) for v in variants]
|
|
1433
|
+
union_type = f"Union[{', '.join(types)}]"
|
|
1434
|
+
if is_nullable:
|
|
1435
|
+
return f"Optional[{union_type}]"
|
|
1436
|
+
return union_type
|
|
1437
|
+
|
|
1438
|
+
schema_type = schema.get("type", "any")
|
|
1439
|
+
|
|
1440
|
+
if schema_type == "integer":
|
|
1441
|
+
base_type = "int"
|
|
1442
|
+
elif schema_type == "number":
|
|
1443
|
+
base_type = "float"
|
|
1444
|
+
elif schema_type == "boolean":
|
|
1445
|
+
base_type = "bool"
|
|
1446
|
+
elif schema_type == "array":
|
|
1447
|
+
item_schema = schema.get("items", {})
|
|
1448
|
+
item_type = self._schema_to_type(item_schema, refs_seen=refs_seen, use_forward_refs=use_forward_refs)
|
|
1449
|
+
base_type = f"List[{item_type}]"
|
|
1450
|
+
elif schema_type == "object":
|
|
1451
|
+
base_type = "Dict[str, Any]"
|
|
1452
|
+
else:
|
|
1453
|
+
base_type = "str"
|
|
1454
|
+
|
|
1455
|
+
if is_nullable:
|
|
1456
|
+
return f"Optional[{base_type}]"
|
|
1457
|
+
return base_type
|
|
1458
|
+
|
|
1459
|
+
def _write_file(self, path: Path, content: str):
|
|
1460
|
+
path.write_text(content, encoding="utf-8")
|
|
1461
|
+
return
|
|
1462
|
+
|
|
1463
|
+
def _format_import_sections(self, sections: List[List[str]], body_text: Optional[str] = None) -> List[str]:
|
|
1464
|
+
"""
|
|
1465
|
+
Format import sections in order and sort each section alphabetically.
|
|
1466
|
+
|
|
1467
|
+
:param sections: The import sections, each a list of import statements.
|
|
1468
|
+
:param body_text: The text of the module body the imports are for. When provided, names that the body
|
|
1469
|
+
does not reference are dropped so the generated module has no unused imports.
|
|
1470
|
+
|
|
1471
|
+
:returns: The formatted import lines.
|
|
1472
|
+
"""
|
|
1473
|
+
referenced_names = None
|
|
1474
|
+
if body_text is not None:
|
|
1475
|
+
referenced_names = self._referenced_names(body_text)
|
|
1476
|
+
|
|
1477
|
+
lines: List[str] = []
|
|
1478
|
+
for section in sections:
|
|
1479
|
+
if referenced_names is not None:
|
|
1480
|
+
section = self._prune_import_statements(section, referenced_names)
|
|
1481
|
+
if not section:
|
|
1482
|
+
continue
|
|
1483
|
+
lines.extend(sorted(section))
|
|
1484
|
+
lines.append("")
|
|
1485
|
+
if lines:
|
|
1486
|
+
lines.pop()
|
|
1487
|
+
return lines
|
|
1488
|
+
|
|
1489
|
+
def _prune_import_statements(self, statements: List[str], referenced_names: set) -> List[str]:
|
|
1490
|
+
"""
|
|
1491
|
+
Removes the imported names that are not in 'referenced_names' from a list of import statements. A
|
|
1492
|
+
statement that no longer imports any name is dropped.
|
|
1493
|
+
|
|
1494
|
+
:param statements: Import statements of the form 'import x' or 'from x import a, b'.
|
|
1495
|
+
:param referenced_names: The names referenced by the module body.
|
|
1496
|
+
|
|
1497
|
+
:returns: The pruned import statements.
|
|
1498
|
+
"""
|
|
1499
|
+
pruned: List[str] = []
|
|
1500
|
+
for statement in statements:
|
|
1501
|
+
if statement.startswith("from "):
|
|
1502
|
+
module_part, _, names_part = statement.partition(" import ")
|
|
1503
|
+
kept_names = []
|
|
1504
|
+
for name in names_part.split(","):
|
|
1505
|
+
name = name.strip()
|
|
1506
|
+
bound_name = name.split(" as ")[-1].strip()
|
|
1507
|
+
if bound_name in referenced_names:
|
|
1508
|
+
kept_names.append(name)
|
|
1509
|
+
if len(kept_names) > 0:
|
|
1510
|
+
pruned.append(f"{module_part} import {', '.join(kept_names)}")
|
|
1511
|
+
else:
|
|
1512
|
+
module_name = statement[len("import "):].strip()
|
|
1513
|
+
bound_name = module_name.split(" as ")[-1].strip().split(".")[0]
|
|
1514
|
+
if bound_name in referenced_names:
|
|
1515
|
+
pruned.append(statement)
|
|
1516
|
+
return pruned
|
|
1517
|
+
|
|
1518
|
+
def _referenced_names(self, body_text: str) -> set:
|
|
1519
|
+
"""
|
|
1520
|
+
Collects the names referenced by generated module code, including names used inside string
|
|
1521
|
+
annotations (forward references).
|
|
1522
|
+
|
|
1523
|
+
:param body_text: The generated module body.
|
|
1524
|
+
|
|
1525
|
+
:returns: The set of referenced names.
|
|
1526
|
+
"""
|
|
1527
|
+
referenced_names = set()
|
|
1528
|
+
tree = ast.parse(body_text)
|
|
1529
|
+
|
|
1530
|
+
annotations = []
|
|
1531
|
+
for node in ast.walk(tree):
|
|
1532
|
+
if isinstance(node, ast.Name):
|
|
1533
|
+
referenced_names.add(node.id)
|
|
1534
|
+
elif isinstance(node, ast.arg) and node.annotation is not None:
|
|
1535
|
+
annotations.append(node.annotation)
|
|
1536
|
+
elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.returns is not None:
|
|
1537
|
+
annotations.append(node.returns)
|
|
1538
|
+
elif isinstance(node, ast.AnnAssign):
|
|
1539
|
+
annotations.append(node.annotation)
|
|
1540
|
+
|
|
1541
|
+
for annotation in annotations:
|
|
1542
|
+
for node in ast.walk(annotation):
|
|
1543
|
+
if isinstance(node, ast.Constant) and isinstance(node.value, str):
|
|
1544
|
+
try:
|
|
1545
|
+
annotation_tree = ast.parse(node.value, mode="eval")
|
|
1546
|
+
except SyntaxError:
|
|
1547
|
+
continue
|
|
1548
|
+
for sub_node in ast.walk(annotation_tree):
|
|
1549
|
+
if isinstance(sub_node, ast.Name):
|
|
1550
|
+
referenced_names.add(sub_node.id)
|
|
1551
|
+
|
|
1552
|
+
return referenced_names
|
|
1553
|
+
|
|
1554
|
+
def _write_schemas_init(self, schemas_dir: Path):
|
|
1555
|
+
"""
|
|
1556
|
+
Generate an empty __init__.py for schemas to avoid eager schema imports.
|
|
1557
|
+
"""
|
|
1558
|
+
init_file = schemas_dir / "__init__.py"
|
|
1559
|
+
self._write_file(init_file, "")
|
|
1560
|
+
return
|
|
1561
|
+
|
|
1562
|
+
def _write_simple_init(self, target_dir: Path):
|
|
1563
|
+
init_file = target_dir / "__init__.py"
|
|
1564
|
+
if init_file.exists():
|
|
1565
|
+
return
|
|
1566
|
+
init_file.write_text("", encoding="utf-8")
|
|
1567
|
+
return
|
|
1568
|
+
|
|
1569
|
+
|
|
1570
|
+
def rest_client_generator_main():
|
|
1571
|
+
"""
|
|
1572
|
+
Entry point used to generate REST client code from the OpenAPI specification.
|
|
1573
|
+
"""
|
|
1574
|
+
parser = argparse.ArgumentParser(description="Generate REST client code from an OpenAPI specification.")
|
|
1575
|
+
parser.add_argument("--client-root", required=True, help="Root directory where the generated client package (public) resides.")
|
|
1576
|
+
parser.add_argument("--client-classname", default="GithubRestClient", help="Class name to use for the generated root client.")
|
|
1577
|
+
parser.add_argument("--specfile", required=True, help="Path to the OpenAPI specification JSON or YAML file.")
|
|
1578
|
+
|
|
1579
|
+
args = parser.parse_args()
|
|
1580
|
+
|
|
1581
|
+
# Use this package's own RestClientGenerator. The previous import of
|
|
1582
|
+
# ccai.github.rest.generation.githubrestclientgenerator resolved nowhere (the
|
|
1583
|
+
# base package must not depend on a specific client package); the local
|
|
1584
|
+
# generator has the same constructor and is the correct foundation entry point.
|
|
1585
|
+
generator = RestClientGenerator(
|
|
1586
|
+
openapi_spec_file=args.specfile,
|
|
1587
|
+
clients_root=args.client_root,
|
|
1588
|
+
client_class_name=args.client_classname
|
|
1589
|
+
)
|
|
1590
|
+
generator.generate()
|
|
1591
|
+
return
|
|
1592
|
+
|
|
1593
|
+
|
|
1594
|
+
if __name__ == "__main__":
|
|
1595
|
+
rest_client_generator_main()
|