-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclass-to-swagger.py
303 lines (249 loc) · 9.32 KB
/
class-to-swagger.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
#!/usr/bin/env python3
import sys
import re
import pprint
import json
from functools import singledispatch
SWAGGER_INDENT = 4
pp = pprint.PrettyPrinter(indent=4)
class PropertyType():
def __init__(self, required):
self.required = required
class SimplePropertyType(PropertyType):
def __init__(self, typeString: str, required: bool = False):
self.type = typeString.lower()
super().__init__(required)
def __str__(self):
return self.__repr__()
def __repr__(self):
return pp.pformat(self.to_swagger_dict())
def to_swagger_dict(self):
return {
'type': self.type
}
class NumberPropertyType(PropertyType):
def __init__(self, typeString: str, required: bool = False):
_class_type_map = {
'int': {
'type': 'integer',
'format': 'int32'
},
'long': {
'type': 'integer',
'format': 'int64'
},
'float': {
'type': 'number',
'format': 'float'
},
'double': {
'type': 'number',
'format': 'double'
}
}
lower_case_type = typeString.lower()
type_and_format = _class_type_map.get(lower_case_type, {'type': 'number'})
self.type = type_and_format.get('type', None)
self.format = type_and_format.get('format') # This returns None if a typeString is not recognized in above map
super().__init__(required)
def __str__(self):
return self.__repr__()
def __repr__(self):
return pp.pformat(self.to_swagger_dict())
def to_swagger_dict(self):
res = {}
res['type'] = self.type
if self.format is not None:
res['format'] = self.format
return res
class ArrayPropertyType(PropertyType):
def __init__(self, items: PropertyType, required: bool = False):
self.type = "array"
self.items = items
super().__init__(required)
def __str__(self):
return self.__repr__()
def __repr__(self):
return pp.pformat(self.to_swagger_dict())
def to_swagger_dict(self):
return {
'type': self.type,
'items': self.items
}
class ReferencePropertyType(PropertyType):
def __init__(self, className: str, required: bool = False):
self.className = className
super().__init__(required)
def __str__(self):
return self.__repr__()
def __repr__(self):
return pp.pformat(self.to_swagger_dict())
def to_swagger_dict(self):
return {
'$ref': '#/definitions/{}'.format(self.className)
}
class SwaggerProperty:
def __init__(self, pname: str, ptype: PropertyType, required: bool = False):
self.property_name = pname
self.propertyType = ptype
self.required = required
def __str__(self):
return self.__repr__()
def __repr__(self):
return pp.pformat(self.to_swagger_dict())
def to_swagger_dict(self):
rep = self.propertyType
return rep
class SwaggerDoc:
def __init__(self, className):
self.type = "object"
self.name = className
self.properties = []
self.requiredProperties = []
def addProperty(self, property):
self.properties += [property]
if property.required:
self.requiredProperties += [property.property_name]
def __str__(self):
return self.__repr__()
def __repr__(self):
return pp.pformat(self.to_swagger_dict())
def to_swagger_dict(self):
rep = {}
rep[self.name] = {
'type': "object",
'required': self.requiredProperties,
'properties': {}
}
for prop in self.properties:
rep[self.name]['properties'][prop.property_name] = prop.propertyType
return rep
@singledispatch
def to_serializable(val):
"""Default json serialization"""
return val
@to_serializable.register(PropertyType)
@to_serializable.register(SimplePropertyType)
@to_serializable.register(NumberPropertyType)
@to_serializable.register(ArrayPropertyType)
@to_serializable.register(ReferencePropertyType)
@to_serializable.register(SwaggerProperty)
@to_serializable.register(SwaggerDoc)
def ts_swagger(obj):
"""Override json serialization for Swagger-related classses"""
return obj.to_swagger_dict()
def is_simple_type(s: str):
""" Simple extensible function to determine if a Scala class is a SimplePropertyType """
switcher = {
'String': True,
'Char': True,
'Boolean': True
}
return switcher.get(s, False)
def is_number_type(s: str):
""" Simple extensible function to determine if a Scala class is a NumberPropertyType """
switcher = {
'Int': True,
'Long': True,
'Float': True,
'Double': True
}
return switcher.get(s, False)
def isArrayType(s: str):
""" Simple extensible function to determine if a Scala class is a ArrayPropertyType """
switcher = {
'Array': True,
'List': True,
'ArrayBuffer': True
}
return switcher.get(s, False)
def extract_super_type(s: str):
""" Takes a type string and returns the container type (i.e. Option from Option[String] or List from List[String])
"""
match = re.search(r'^(.*)\[.*$', s) # Search for pattern <Type>[<SubType>] and extract <Type> into group #1
if match is None:
return None
else:
return match.group(1)
def extract_sub_type(s: str):
""" Takes a type string and returns the sub type (i.e. String from Option[String] or List[String])
"""
match = re.search(r'^.*\[(.*)\]$', s) # Extract type from the outermost parentheses into group #1
if match is None:
print('[ERROR]: No subtype found for string "{}"'.format(s))
raise Exception("Invalid input: No outer type found")
else:
return match.group(1)
def extract_params_list(s: str):
""" Takes a case class string and returns the class name and internal parameters
"""
match = re.search(r'\((.*)\)$', s)
if match is None:
print('[ERROR]: Valid class definition not found for string\n{}'.format(s))
raise Exception("Invalid input: Unable to parse class")
else:
return match.group(1)
def to_property_type(typeString: str):
""" Takes a type string and parses it to return the appropriate PropertyType
"""
print('Processing typeString "{}"'.format(typeString))
superType = extract_super_type(typeString)
subType = typeString
required = True
if superType is not None:
if superType == 'Option':
required = False
subType = extract_sub_type(typeString)
if isArrayType(superType):
listType = extract_sub_type(typeString)
return ArrayPropertyType(to_property_type(listType), required = required)
elif is_simple_type(subType): # Base case
return SimplePropertyType(subType, required = required)
elif is_number_type(subType):
return NumberPropertyType(subType, required = required)
else:
return ReferencePropertyType(subType, required = required) # Default is Reference Type if no other type is found
def get_class_strings_from_file():
""" Reads file input.txt and returns array of strings with spaces removed
for each case class in the file. The file must contain only the case class
definitions or the output will be unpredictable
"""
with open("input.txt", "r") as file:
if file.mode == 'r':
contents = file.read()
else:
print("Error opening file to read")
sys.exit()
class_strings = contents.split("case class")
split_contents = ["".join(item.split()) for item in class_strings]
print(split_contents)
split_contents.remove('') # Remove extraneous empty string caused by above action
return split_contents
def create_swagger_doc(case_class_string):
""" Constructs swagger doc object from the provided case class string by extracting the
class name and parameters and converting the parameters to the appropriate sub-class of
ParameterType to ensure correct serialization
"""
class_name = case_class_string.split("(")[0]
print("Processing class: {}".format(class_name))
param_string = extract_params_list(case_class_string)
print(param_string)
param_list = param_string.split(",")
result = SwaggerDoc(class_name)
for parameter in param_list:
parameter_without_defaults = re.sub(r'=.*', '', parameter)
split_parameter = parameter_without_defaults.split(':')
name = split_parameter[0]
typeName = split_parameter[1]
propType = to_property_type(typeName)
print('Adding property {} with details {}'.format(name, propType))
result.addProperty(SwaggerProperty(name, propType, propType.required))
return result
def main():
case_classes_strings = get_class_strings_from_file()
for case_class_string in case_classes_strings:
case_class_doc = create_swagger_doc(case_class_string)
with open('output/{}_output_swagger.json'.format(case_class_doc.name), 'w') as out_file:
out_file.write(json.dumps(case_class_doc, default=to_serializable, sort_keys=True, indent=SWAGGER_INDENT))
if __name__ == '__main__':
main()