Manually copied files that did not get merged over from ansible branch
[plstackapi.git] / planetstack / dmdot
1 #!/usr/bin/python
2
3 import os
4 import pdb
5 import sys
6 import json
7
8 sys.path.append('.')
9
10 os.environ.setdefault("DJANGO_SETTINGS_MODULE", "planetstack.settings")
11
12 from django.db.models.fields.related import ForeignKey
13
14 # defaults
15 app = "core"
16 output = "-json"
17
18 # syntax: dmdot [-json | -dot] [app_name]
19
20 # poor man's argument parser
21 for arg in sys.argv[1:]:
22     if arg.startswith("-"):
23         output = arg
24     else:
25         app = arg
26
27 app = app + ".models"
28 #models_module = imp.load_source(app, ".")
29 models_module = __import__(app)
30 for part in app.split(".")[1:]:
31     if hasattr(models_module, "PlCoreBase"):
32         break
33     models_module = getattr(models_module,part)
34
35 PlCoreBase = getattr(models_module,"PlCoreBase")
36
37 model_classes = []
38 class_names = []
39 lower_class_names = {}
40 for classname in dir(models_module):
41         c = getattr(models_module, classname, None)
42         if type(c)==type(PlCoreBase):
43                 model_classes.append(c)
44                 class_names.append(c.__name__)
45                 lower_class_names[c.__name__.lower()] = c
46
47 # django doesn't use the correct case in field.name.title() for objects that
48 # have CamelCased class names. So, compare everything in lower case.
49
50 if (output=='-dot'):
51         print "digraph plstack {";
52         for c in model_classes:
53                 fields = c._meta.fields
54                 for f in fields:
55                         if type(f)==ForeignKey and f.name.lower() in lower_class_names:
56                                 linked_class = lower_class_names[f.name.lower()]
57                                 print '\t"%s"->"%s";'%(c.__name__,linked_class.__name__)
58         print "}\n";
59 elif (output=='-json'):
60         d = {}
61         for c in model_classes:
62                 fields = c._meta.fields
63                 for f in fields:
64                         if type(f)==ForeignKey and f.name.lower() in lower_class_names:
65                                 linked_class = lower_class_names[f.name.lower()]
66                                 try:
67                                         d[c.__name__].append(linked_class.__name__)
68                                 except KeyError:
69                                         d[c.__name__]=[linked_class.__name__]
70         print json.dumps(d,indent=4)
71         
72