Sapan Bhatia | 3a45f8b | 2014-01-14 21:20:16 -0500 | [diff] [blame] | 1 | #!/usr/bin/python |
| 2 | |
| 3 | import os |
| 4 | import pdb |
| 5 | import sys |
| 6 | import json |
| 7 | import re |
| 8 | from django.template import Context, Template |
| 9 | |
| 10 | # Django set up |
| 11 | |
| 12 | sys.path.append('.') |
| 13 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "planetstack.settings") |
| 14 | from django.db.models.fields.related import ForeignKey |
| 15 | from core.models import * |
| 16 | |
| 17 | g = globals() |
| 18 | |
| 19 | def 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 | |
| 27 | class 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 | |
| 47 | class 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 | |
| 70 | def 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 | |
| 91 | if (__name__=='__main__'): |
| 92 | main() |