blob: 6b7f37205497824715af28d33892efa08a6ea598 [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 Bhatia5ea307d2017-07-19 00:13:21 -040017from base import *
18import pdb
19
Sapan Bhatiad8e4a232017-07-12 21:20:06 -040020def django_content_type_string(xptags):
21 # Check possibility of KeyError in caller
22 content_type = xptags['content_type']
23
24 try:
25 content_type = eval(content_type)
26 except:
27 pass
28
29 if (content_type=='url'):
30 return 'URLField'
31 if (content_type=='date'):
32 return 'DateTimeField'
33 elif (content_type=='ip'):
34 return 'GenericIPAddressField'
35 elif (content_type=='stripped' or content_type=='"stripped"'):
36 return 'StrippedCharField'
37 else:
38 raise Exception('Unknown Type: %s'%content_type)
39
40def django_string_type(xptags):
41 try:
42 max_length = eval(xptags['max_length'])
43 except:
44 max_length = 1024 * 1024
45
46 if ('content_type' in xptags):
47 return django_content_type_string(xptags)
48 elif (max_length<1024*1024):
49 return 'CharField'
50 else:
51 return 'TextField'
52
53def xproto_django_type(xptype, xptags):
54 if (xptype=='string'):
55 return django_string_type(xptags)
56 elif (xptype=='float'):
57 return 'FloatField'
58 elif (xptype=='bool'):
59 return 'BooleanField'
60 elif (xptype=='uint32'):
61 return 'IntegerField'
62 elif (xptype=='int32'):
63 return 'IntegerField'
64 elif (xptype=='int64'):
65 return 'BigIntegerField'
66 else:
67 raise Exception('Unknown Type: %s'%xptype)
68
69def xproto_django_link_type(f):
70 if (f['link_type']=='manytoone'):
71 return 'ForeignKey'
Sapan Bhatia9590a882017-08-01 08:35:23 -040072 elif (f['link_type']=='onetoone'):
73 return 'OneToOneField'
Sapan Bhatiad8e4a232017-07-12 21:20:06 -040074 elif (f['link_type']=='manytomany'):
75 if (f['dst_port']):
76 return 'ManyToManyField'
77 else:
78 return 'GenericRelation'
79
80def map_xproto_to_django(f):
81 allowed_keys=['help_text','default','max_length','modifier','blank','choices','db_index','null','editable','on_delete','verbose_name', 'auto_now_add']
82
83 m = {'modifier':{'optional':True, 'required':False, '_target':'null'}}
84 out = {}
85
86 for k,v in f['options'].items():
87 if (k in allowed_keys):
88 try:
89 kv2 = m[k]
90 out[kv2['_target']] = kv2[v]
91 except:
92 out[k] = v
93 return out
94
95def xproto_django_link_options_str(field, dport=None):
96 output_dict = map_xproto_to_django(field)
97
98 if (dport and (dport=='+' or '+' not in dport)):
99 output_dict['related_name'] = '%r'%dport
100
101 try:
102 if field['through']:
103 d = {}
104 if isinstance(field['through'], str):
105 split = field['through'].rsplit('.',1)
106 d['name'] = split[-1]
107 if len(split)==2:
108 d['package'] = split[0]
109 d['fqn'] = 'package' + '.' + d['name']
110 else:
111 d['fqn'] = d['name']
112 d['package'] = ''
113 else:
114 d = field['through']
115
116 if not d['name'].endswith('_'+field['name']):
117 output_dict['through'] = '%r'%d['fqn']
118 except KeyError:
119 pass
120
121 return format_options_string(output_dict)
122
123def format_options_string(d):
124 if (not d):
125 return ''
126 else:
127
128 lst = []
129 for k,v in d.items():
130 if (type(v)==str and k=='default' and v.endswith('()"')):
131 lst.append('%s = %s'%(k,v[1:-3]))
132 elif (type(v)==str and v.startswith('"')):
133 try:
134 tup = eval(v[1:-1])
135 if (type(tup)==tuple):
136 lst.append('%s = %r'%(k,tup))
137 else:
138 lst.append('%s = %s'%(k,v))
139 except:
140 lst.append('%s = %s'%(k,v))
141 elif (type(v)==bool):
142 lst.append('%s = %r'%(k,bool(v)))
143 else:
144 try:
145 lst.append('%s = %r'%(k,int(v)))
146 except ValueError:
147 lst.append('%s = %s'%(k,v))
148
149 return ', '.join(lst)
150
151def xproto_django_options_str(field, dport=None):
152 output_dict = map_xproto_to_django(field)
153
154 if (dport=='_'):
155 dport = '+'
156
157 if (dport and (dport=='+' or '+' not in dport)):
158 output_dict['related_name'] = '%r'%dport
159
160 return format_options_string(output_dict)
Sapan Bhatia5ea307d2017-07-19 00:13:21 -0400161
162def xproto_validations(options):
163 try:
164 return [map(str.strip, validation.split(':')) for validation in unquote(options['validators']).split(',')]
165 except KeyError:
166 return []