blob: 93f45818f7e4c7715187c23e49e209b3ada66263 [file] [log] [blame]
Matteo Scandolod2044a42017-08-07 16:08:28 -07001
2# Copyright 2017-present Open Networking Foundation
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16
Sapan Bhatiaff1b8fa2017-04-10 19:44:38 -070017import pdb
Sapan Bhatiac4f803f2017-04-21 11:50:39 +020018import re
Sapan Bhatia7886e122017-05-17 11:19:39 +020019from pattern import en
20
Sapan Bhatiaf7934b52017-06-12 05:04:23 -070021class FieldNotFound(Exception):
22 def __init__(self, message):
23 super(FieldNotFound, self).__init__(message)
24
Sapan Bhatiad4567592017-07-24 17:26:26 -040025def xproto_debug(**kwargs):
26 print kwargs
27 pdb.set_trace()
28
Sapan Bhatia943dad52017-05-19 18:41:01 +020029def xproto_unquote(s):
30 return unquote(s)
31
Sapan Bhatia49b54ae2017-05-19 17:11:32 +020032def unquote(s):
33 if (s.startswith('"') and s.endswith('"')):
34 return s[1:-1]
Matteo Scandolo292cc2a2017-07-31 19:02:12 -070035 else:
36 return s
Sapan Bhatia49b54ae2017-05-19 17:11:32 +020037
38def xproto_singularize(field):
39 try:
40 # The user has set a singular, as an exception that cannot be handled automatically
41 singular = field['options']['singular']
42 singular = unquote(singular)
43 except KeyError:
44 singular = en.singularize(field['name'])
45
46 return singular
47
Sapan Bhatiacb35e7f2017-05-24 12:17:28 +020048def xproto_singularize_pluralize(field):
49 try:
50 # The user has set a plural, as an exception that cannot be handled automatically
51 plural = field['options']['plural']
52 plural = unquote(plural)
53 except KeyError:
54 plural = en.pluralize(en.singularize(field['name']))
55
56 return plural
57
Sapan Bhatia7886e122017-05-17 11:19:39 +020058def xproto_pluralize(field):
59 try:
60 # The user has set a plural, as an exception that cannot be handled automatically
61 plural = field['options']['plural']
Sapan Bhatia49b54ae2017-05-19 17:11:32 +020062 plural = unquote(plural)
Sapan Bhatia7886e122017-05-17 11:19:39 +020063 except KeyError:
64 plural = en.pluralize(field['name'])
65
66 return plural
Sapan Bhatiac4f803f2017-04-21 11:50:39 +020067
Sapan Bhatiaa3d2e622017-07-31 22:25:55 -040068def xproto_base_def(model_name, base, suffix='', suffix_list=[]):
Sapan Bhatia4e80a262017-05-19 23:10:51 +020069 if (model_name=='XOSBase'):
70 return '(models.Model, PlModelMixIn)'
71 elif (not base):
Sapan Bhatiaff1b8fa2017-04-10 19:44:38 -070072 return ''
73 else:
Sapan Bhatiaa3d2e622017-07-31 22:25:55 -040074 int_base = [i['name']+suffix for i in base if i['name'] in suffix_list]
75 ext_base = [i['name'] for i in base if i['name'] not in suffix_list]
76 return '(' + ','.join(int_base + ext_base) + ')'
Sapan Bhatiaff1b8fa2017-04-10 19:44:38 -070077
Sapan Bhatia504cc972017-04-27 01:56:28 +020078def xproto_first_non_empty(lst):
79 for l in lst:
80 if l: return l
81
Sapan Bhatia943dad52017-05-19 18:41:01 +020082def xproto_api_type(field):
83 try:
84 if (unquote(field['options']['content_type'])=='date'):
Scott Baker450e5d02017-09-06 11:18:16 -070085 return 'double'
Sapan Bhatia943dad52017-05-19 18:41:01 +020086 except KeyError:
87 pass
88
89 return field['type']
90
Sapan Bhatiac4f803f2017-04-21 11:50:39 +020091
92def xproto_base_name(n):
93 # Hack - Refactor NetworkParameter* to make this go away
94 if (n.startswith('NetworkParameter')):
95 return '_'
96
Sapan Bhatia4e80a262017-05-19 23:10:51 +020097 expr = r'^[A-Z]+[a-z]*'
Sapan Bhatiac4f803f2017-04-21 11:50:39 +020098
99 try:
100 match = re.findall(expr, n)[0]
101 except:
102 return '_'
103
104 return match
Sapan Bhatiaae9645c2017-05-05 15:35:54 +0200105
Sapan Bhatia943dad52017-05-19 18:41:01 +0200106def xproto_base_fields(m, table):
107 fields = []
108
109 for b in m['bases']:
Sapan Bhatia3cfdf632017-06-08 05:14:03 +0200110 option1 = b['fqn']
111 try:
112 option2 = m['package'] + '.' + b['name']
113 except TypeError:
114 option2 = option1
Sapan Bhatia943dad52017-05-19 18:41:01 +0200115
Sapan Bhatia3cfdf632017-06-08 05:14:03 +0200116 accessor = None
117 if option1 in table: accessor = option1
118 elif option2 in table: accessor = option2
119
120 if accessor:
121 base_fields = xproto_base_fields(table[accessor], table)
122
123 model_fields = table[accessor]['fields']
Sapan Bhatia943dad52017-05-19 18:41:01 +0200124 fields.extend(base_fields)
125 fields.extend(model_fields)
126
127 return fields
Sapan Bhatiad022aeb2017-06-07 15:49:55 +0200128
Sapan Bhatiacb35e7f2017-05-24 12:17:28 +0200129def xproto_base_rlinks(m, table):
130 links = []
131
132 for base in m['bases']:
133 b = base['name']
134 if b in table:
135 base_rlinks = xproto_base_rlinks(table[b], table)
136
137 model_rlinks = table[b]['rlinks']
138 links.extend(base_rlinks)
139 links.extend(model_rlinks)
140
141 return links
142
Sapan Bhatiad022aeb2017-06-07 15:49:55 +0200143def xproto_base_links(m, table):
144 links = []
145
Sapan Bhatia3cfdf632017-06-08 05:14:03 +0200146 for base in m['bases']:
147 b = base['name']
Sapan Bhatiad022aeb2017-06-07 15:49:55 +0200148 if b in table:
149 base_links = xproto_base_links(table[b], table)
150
151 model_links = table[b]['links']
152 links.extend(base_links)
153 links.extend(model_links)
154 return links
155
Sapan Bhatiad022aeb2017-06-07 15:49:55 +0200156def xproto_string_type(xptags):
157 try:
158 max_length = eval(xptags['max_length'])
159 except:
160 max_length = 1024
161
162 if ('varchar' not in xptags):
163 return 'string'
164 else:
165 return 'text'
166
Sapan Bhatiaf7934b52017-06-12 05:04:23 -0700167def xproto_tuplify(nested_list_or_set):
168 if not isinstance(nested_list_or_set, list) and not isinstance(nested_list_or_set, set):
169 return nested_list_or_set
170 else:
171 return tuple([xproto_tuplify(i) for i in nested_list_or_set])
172
173def xproto_field_graph_components(fields, tag='unique_with'):
174 def find_components(graph):
175 pending = set(graph.keys())
176 components = []
177
178 while pending:
179 front = { pending.pop() }
180 component = set()
181
182 while front:
183 node = front.pop()
184 neighbours = graph[node]
185 neighbours-=component # These we have already visited
186 front |= neighbours
187
188 pending-=neighbours
189 component |= neighbours
190
191 components.append(component)
192
193 return components
194
195 field_graph = {}
196 field_names = {f['name'] for f in fields}
197
198 for f in fields:
199 try:
200 tagged_str = unquote(f['options'][tag])
201 tagged_fields = tagged_str.split(',')
202
203 for uf in tagged_fields:
204 if uf not in field_names:
205 raise FieldNotFound('Field %s not found'%uf)
206
207 field_graph.setdefault(f['name'],set()).add(uf)
208 field_graph.setdefault(uf,set()).add(f['name'])
209 except KeyError:
210 pass
211
212 components = find_components(field_graph)
213 return components
214
Sapan Bhatiacb35e7f2017-05-24 12:17:28 +0200215def xproto_api_opts(field):
216 options = []
217 if 'max_length' in field['options'] and field['type']=='string':
218 options.append('(val).maxLength = %s'%field['options']['max_length'])
Sapan Bhatiaf7934b52017-06-12 05:04:23 -0700219
Sapan Bhatiacb35e7f2017-05-24 12:17:28 +0200220 try:
221 if field['options']['null'] == 'False':
222 options.append('(val).nonNull = true')
223 except KeyError:
224 pass
Sapan Bhatiaf7934b52017-06-12 05:04:23 -0700225
Sapan Bhatiacb35e7f2017-05-24 12:17:28 +0200226 if 'link' in field and 'model' in field['options']:
227 options.append('(foreignKey).modelName = "%s"'%field['options']['model'])
Sapan Bhatiaf7934b52017-06-12 05:04:23 -0700228
Sapan Bhatiacb35e7f2017-05-24 12:17:28 +0200229 if options:
230 options_str = '[' + ', '.join(options) + ']'
231 else:
232 options_str = ''
233
234 return options_str
Matteo Scandolo67654fa2017-06-09 09:33:17 -0700235
Matteo Scandolo3b7857b2017-06-30 16:22:33 -0700236def xproto_tosca_required(null, blank, default=None):
237
238 if null == 'True' or blank == 'True' or default != 'False':
239 return "false"
240 return "true"
241
242def xproto_tosca_field_type(type):
243 """
244 TOSCA requires fields of type 'bool' to be 'boolean'
245 """
246 if type == "bool":
247 return "boolean"
248 else:
249 return type
Matteo Scandolo431781c2017-09-06 15:33:07 -0700250
251def xproto_type_to_swagger_type(f):
252 try:
253 content_type = f['options']['content_type']
254 content_type = eval(content_type)
255 except:
256 content_type = None
257 pass
258
259 if 'choices' in f['options']:
260 return 'string'
261 elif content_type == 'date':
262 return 'string'
263 elif f['type'] == 'bool':
264 return 'boolean'
265 elif f['type'] == 'string':
266 return 'string'
267 elif f['type'] in ['int','uint32','int32'] or 'link' in f:
268 return 'integer'
269 elif f['type'] in ['double','float']:
270 return 'string'
271
272def xproto_field_to_swagger_enum(f):
273 if 'choices' in f['options']:
274 list = []
275
276 for c in eval(xproto_unquote(f['options']['choices'])):
277 list.append(c[0])
278
279 return list
280 else:
281 return False