blob: 4c8a0f1409b8d8d9e0e4f70e76f08920c2bcb7ba [file] [log] [blame]
Sapan Bhatia3a45f8b2014-01-14 21:20:16 -05001#!/usr/bin/python
2
3import os
4import pdb
5import sys
6import json
7import re
8from django.template import Context, Template
9
10# Django set up
11
12sys.path.append('.')
13os.environ.setdefault("DJANGO_SETTINGS_MODULE", "planetstack.settings")
14from django.db.models.fields.related import ForeignKey
15from core.models import *
16
17g = globals()
18
19def enum_classes():
20 model_classes = []
21 for c in g.values():
22 if type(c)==type(PlCoreBase):
23 model_classes.append(c)
24 return model_classes
25
26
27class GenObj(object):
28 def __str__(self):
29 return str(self.model.__name__.lower())
30
31 def __init__(self, m):
32 self.model = m
33 self.props = []
34 self.refs = []
35
36 def plural(self):
37 name = str(self)
38 if (name.endswith('s')):
39 return name+'es'
40 else:
41 return name+'s'
42
43 def camel(self):
44 name = str(self.model.__name__)
45 return name.title()
46
47class Generator(dict):
48 def all(self):
49 return self.values()
50
51 def regex(self, r):
52 filtered = filter(lambda o:re.match(r,str(o)), self.values())
53 return filtered
54
55 def add_object(self, o):
56 obj = GenObj(o)
57 fields = o._meta.fields
58 self[str(obj).lower()]=obj
59
60 def compute_links(self):
61 for obj in self.values():
62 fields = obj.model._meta.fields
63 for f in fields:
64 if type(f)==ForeignKey and f.name in self.keys():
65 refobj = self[f.name]
66 obj.refs.append(refobj)
67 else:
68 obj.props.append(f.name)
69
70def main():
71 try:
72 output = sys.argv[1]
73 except:
74 print 'Usage: modelgen <output template>'
75 exit(1)
76
77 generator = Generator()
78
79 models = enum_classes()
80
81 for m in models:
82 generator.add_object(m)
83
84 generator.compute_links()
85 template_contents = open(output).read()
86 template = Template(template_contents)
87 context = Context({'generator':generator})
88 print template.render(context)
89
90
91if (__name__=='__main__'):
92 main()