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