2to3 -f has_key
[sfa.git] / tools / depgraph2dot.py
1 #!/usr/bin/python
2 # Copyright 2004 Toby Dickenson
3 #
4 # Permission is hereby granted, free of charge, to any person obtaining
5 # a copy of this software and associated documentation files (the
6 # "Software"), to deal in the Software without restriction, including
7 # without limitation the rights to use, copy, modify, merge, publish,
8 # distribute, sublicense, and/or sell copies of the Software, and to
9 # permit persons to whom the Software is furnished to do so, subject
10 # to the following conditions:
11 #
12 # The above copyright notice and this permission notice shall be included
13 # in all copies or substantial portions of the Software.
14 #
15 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
18 # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
19 # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
20 # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
21 # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22
23
24 import sys, getopt, colorsys, imp, hashlib
25
26 class pydepgraphdot:
27
28     def main(self,argv):    
29         opts,args = getopt.getopt(argv,'',['mono'])
30         self.colored = 1
31         for o,v in opts:
32             if o=='--mono':
33                 self.colored = 0
34         self.render()
35
36     def fix(self,s):
37         # Convert a module name to a syntactically correct node name
38         return s.replace('.','_')
39     
40     def render(self):
41         p,t = self.get_data()
42
43         # normalise our input data
44         for k,d in p.items():
45             for v in d.keys():
46                 if v not in p:
47                     p[v] = {}
48                     
49         f = self.get_output_file()                    
50                     
51         f.write('digraph G {\n')
52         #f.write('concentrate = true;\n')
53         #f.write('ordering = out;\n')
54         f.write('ranksep=1.0;\n')
55         f.write('node [style=filled,fontname=Helvetica,fontsize=10];\n')
56         allkd = p.items()
57         allkd.sort()
58         for k,d in allkd:
59             tk = t.get(k)
60             if self.use(k,tk):
61                 allv = d.keys()
62                 allv.sort()
63                 for v in allv:
64                     tv = t.get(v)
65                     if self.use(v,tv) and not self.toocommon(v,tv):
66                         f.write('%s -> %s' % ( self.fix(k),self.fix(v) ) )
67                         self.write_attributes(f,self.edge_attributes(k,v))
68                         f.write(';\n')
69                 f.write(self.fix(k))
70                 self.write_attributes(f,self.node_attributes(k,tk))
71                 f.write(';\n')
72         f.write('}\n')
73
74     def write_attributes(self,f,a):
75         if a:
76             f.write(' [')
77             f.write(','.join(a))
78             f.write(']')
79
80     def node_attributes(self,k,type):
81         a = []
82         a.append('label="%s"' % self.label(k))
83         if self.colored:
84             a.append('fillcolor="%s"' % self.color(k,type))
85         else:
86             a.append('fillcolor=white')
87         if self.toocommon(k,type):
88             a.append('peripheries=2')
89         return a
90                 
91     def edge_attributes(self,k,v):
92         a = []
93         weight = self.weight(k,v)
94         if weight!=1:
95             a.append('weight=%d' % weight)
96         length = self.alien(k,v)
97         if length:
98             a.append('minlen=%d' % length)
99         return a
100             
101     def get_data(self):
102         t = eval(sys.stdin.read())
103         return t['depgraph'],t['types']
104     
105     def get_output_file(self):
106         return sys.stdout
107
108     def use(self,s,type):
109         # Return true if this module is interesting and should be drawn. Return false
110         # if it should be completely omitted. This is a default policy - please override.
111         if s in ('os','sys','qt','time','__future__','types','re','string'):
112             # nearly all modules use all of these... more or less. They add nothing to
113             # our diagram.
114             return 0
115         if s.startswith('encodings.'):
116             return 0
117         if s=='__main__':
118             return 1
119         if self.toocommon(s,type):
120             # A module where we dont want to draw references _to_. Dot doesnt handle these
121             # well, so it is probably best to not draw them at all.
122             return 0
123         return 1
124
125     def toocommon(self,s,type):
126         # Return true if references to this module are uninteresting. Such references
127         # do not get drawn. This is a default policy - please override.
128         #
129         if s=='__main__':
130             # references *to* __main__ are never interesting. omitting them means
131             # that main floats to the top of the page
132             return 1
133         if type==imp.PKG_DIRECTORY:
134             # dont draw references to packages.
135             return 1
136         return 0
137         
138     def weight(self,a,b):
139         # Return the weight of the dependency from a to b. Higher weights
140         # usually have shorter straighter edges. Return 1 if it has normal weight.
141         # A value of 4 is usually good for ensuring that a related pair of modules 
142         # are drawn next to each other. This is a default policy - please override.
143         #
144         if b.split('.')[-1].startswith('_'):
145             # A module that starts with an underscore. You need a special reason to
146             # import these (for example random imports _random), so draw them close
147             # together
148             return 4
149         return 1
150     
151     def alien(self,a,b):
152         # Return non-zero if references to this module are strange, and should be drawn
153         # extra-long. the value defines the length, in rank. This is also good for putting some
154         # vertical space between seperate subsystems. This is a default policy - please override.
155         #
156         return 0
157
158     def label(self,s):
159         # Convert a module name to a formatted node label. This is a default policy - please override.
160         #
161         return '\\.\\n'.join(s.split('.'))
162
163     def color(self,s,type):
164         # Return the node color for this module name. This is a default policy - please override.
165         #
166         # Calculate a color systematically based on the hash of the module name. Modules in the
167         # same package have the same color. Unpackaged modules are grey
168         t = self.normalise_module_name_for_hash_coloring(s,type)
169         return self.color_from_name(t)
170         
171     def normalise_module_name_for_hash_coloring(self,s,type):
172         if type==imp.PKG_DIRECTORY:
173             return s
174         else:
175             i = s.rfind('.')
176             if i<0:
177                 return ''
178             else:
179                 return s[:i]
180         
181     def color_from_name(self,name):
182         n = hashlib.md5(name).digest()
183         hf = float(ord(n[0])+ord(n[1])*0xff)/0xffff
184         sf = float(ord(n[2]))/0xff
185         vf = float(ord(n[3]))/0xff
186         r,g,b = colorsys.hsv_to_rgb(hf, 0.3+0.6*sf, 0.8+0.2*vf)
187         return '#%02x%02x%02x' % (r*256,g*256,b*256)
188
189
190 def main():
191     pydepgraphdot().main(sys.argv[1:])
192
193 if __name__=='__main__':
194     main()
195
196
197