Fix logger name in depgraph2dot.py.
[depgraph.git] / depgraph2dot.py
index 23ad7f374b78207e0fdba8e7a08d82960d4f1161..8e47ffe0521409f39efd5d93801f5f6113fac835 100755 (executable)
 # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 
-import sys, getopt, colorsys, imp, re, pprint
+"""Convert `py2depgraph` dependency data to Graphviz dot syntax.
+"""
+
+import colorsys
 from hashlib import md5
+import logging
+import imp
 from os import popen, getuid  # for finding C extension dependencies with system calls
 from pwd import getpwuid
+import re
+import sys
+
+
+LOG = logging.getLogger('depgraph2py')
+LOG.setLevel(logging.DEBUG)
+_STREAM_HANDLER = logging.StreamHandler()
+_STREAM_HANDLER.setLevel(logging.CRITICAL)
+_STREAM_HANDLER.setFormatter(
+    logging.Formatter('%(levelname)s - %(message)s'))
+LOG.addHandler(_STREAM_HANDLER)
 
 USER=getpwuid(getuid())[0] # get effective user name
 
@@ -58,7 +74,6 @@ class hooks (object) :
        self._link_outside_visited_nodes = link_outside_visited_nodes
         self._ignore_builtins = ignore_builtins
         self._entered_bonus_nodes = {} # a dict of bonus nodes already printed
-        self._debug = False
     def continue_test(self) :
         return True
     def visible_mod_test(self, mod_name, dep_dict, type, path,
@@ -68,7 +83,7 @@ class hooks (object) :
         Return false if it should be completely omitted.
         """
        if self._invisible_name(mod_name) == True :
-            if self._debug :  print "\t\tinvisible module", mod_name
+            LOG.debug('invisible module %s' % mod_name)
             return False
        if self._link_outside_visited_nodes == False \
                 and check_external_link == True \
@@ -77,32 +92,31 @@ class hooks (object) :
                                      mod_name, type, path) == False:
                 return False # don't draw nodes we wouldn't visit
         return True
-    def follow_edge_test(self, module_name, type, path, 
+    def follow_edge_test(self, module_name, type, path,
                          dname, dtype, dpath):
-        if self._debug :
-            print "\ttesting edge from %s %s %s to %s %s %s" \
-                % (module_name, type, path, dname, dtype, dpath)
+        LOG.debug('testing edge from %s %s %s to %s %s %s'
+                  % (module_name, type, path, dname, dtype, dpath))
         if self.visible_mod_test(dname, None, dtype, dpath,
                                  check_external_link=False) == False :
-            if self._debug :  print "\t\tinvisible target module"
+            LOG.debug('invisible target module')
             return False # don't draw edges to invisible modules
         elif dname == '__main__':
             # references *to* __main__ are never interesting. omitting them means
             # that main floats to the top of the page
-            if self._debug :  print "\t\ttarget is __main__"
+            LOG.debug('target is __main__')
             return False
         elif self._invisible_path(path) == True and module_name != '__main__' :
             # the path for __main__ seems to be it's filename
-            if self._debug :  print "\t\tinvisible module parent path", path
+            LOG.debug('invisible module parent path %s' % path)
             return False # don't draw edges from invisible path modules
         elif self._link_outside_visited_nodes == False \
                 and self._invisible_path(dpath) == True :
-            if self._debug :  print "\t\tinvisible module path", dpath
-            return False # don't draw edges to invisible path modules            
-        elif dtype == imp.PKG_DIRECTORY:
-            # don't draw edges to packages.
-            if self._debug :  print "\t\tpackage"
-            return False
+            LOG.debug('invisible module path %s' % dpath)
+            return False # don't draw edges to invisible path modules
+        #elif dtype == imp.PKG_DIRECTORY:
+        #    # don't draw edges to packages.
+        #    LOG.debug('package')
+        #    return False
         return True
     def _invisible_name(self, mod_name) :
         if mod_name in self._invisible_mods :
@@ -169,14 +183,14 @@ class dotformat (object) :
 
     def _fix_name(self, mod_name):
         # Convert a module name to a syntactically correct node name
-        return mod_name.replace('.','_')    
+        return mod_name.replace('.','_')
     def _label(self,s):
         # Convert a module name to a formatted node label.
         return '\\.\\n'.join(s.split('.'))
     def _weight(self, mod_name, target_name):
         # Return the weight of the dependency from a to b. Higher weights
         # usually have shorter straighter edges. Return 1 if it has normal weight.
-        # A value of 4 is usually good for ensuring that a related pair of modules 
+        # A value of 4 is usually good for ensuring that a related pair of modules
         # are drawn next to each other.
         #
         if target_name.split('.')[-1].startswith('_'):
@@ -217,7 +231,7 @@ class dotformat (object) :
         vf = float(ord(n[3]))/0xff
         r,g,b = colorsys.hsv_to_rgb(hf, 0.3+0.6*sf, 0.8+0.2*vf)
         return '#%02x%02x%02x' % (r*256,g*256,b*256)
-    
+
     # abstract out most of the dot language for head and edge declarations
     def _dot_node(self, name, attrs) :
         string = '  %s' % self._fix_name(name)
@@ -313,14 +327,13 @@ class pydepgraphdot (object) :
         else :
             self._hooks = hooks()
         self.reset()
-        self._debug=False
 
-    def render(self, root_module='__main__'):
-        depgraph,types,paths = self.get_data()
+    def render(self, ifile, root_module='__main__'):
+        depgraph,types,paths = self.get_data(ifile)
 
         if root_module != None :
             self.add_module_target(root_module)
-            
+
         depgraph,type,paths = self.fill_missing_deps(depgraph, types, paths)
 
         f = self.get_output_file()
@@ -329,11 +342,11 @@ class pydepgraphdot (object) :
 
         while True :
             if self._hooks.continue_test() == False :
-                if self.debug :  print '\t\tcontinue_test() False'
+                LOG.debug('continue_test() False')
                 break
             mod = self.next_module_target()
             if mod == None :
-                if self._debug :  print '\t\tout of modules'
+                LOG.debug('out of modules')
                 break # out of modules
             # I don't know anything about the underlying implementation,
             # but I assume `key in dict` is more efficient than `key in list`
@@ -343,7 +356,7 @@ class pydepgraphdot (object) :
             type = types[mod]
             path = paths[mod]
             if self._hooks.visible_mod_test(mod, deps, type, path) == False :
-                if self._debug :  print '\t\tinvisible module'
+                LOG.debug('invisible module')
                 continue
             f.write(self._dotformat.module(mod, deps, type, path))
             ds = deps.keys() # now we want a consistent ordering,
@@ -351,19 +364,19 @@ class pydepgraphdot (object) :
             for d in ds :
                 if self._hooks.follow_edge_test(mod, type, path,
                                                 d, types[d], paths[d]) :
-                    if self._debug :  print '\t\tfollow to %s' % d
-                    #print "%s, %s, %s, %s, %s, %s, %s" % (mod, deps, type, path, d, types[d], paths[d]) 
+                    LOG.debug('follow to %s' % d)
+                    #print "%s, %s, %s, %s, %s, %s, %s" % (mod, deps, type, path, d, types[d], paths[d])
                     f.write(self._dotformat.edge(mod, deps, type, path,
                                                  d, types[d], paths[d]))
                     self.add_module_target(d)
                 else :
-                    if self._debug :  print "\t\tdon't follow to %s" % d
+                    LOG.debug("don't follow to %s" % d)
 
         f.write(self._dotformat.footer())
 
     # data processing methods (input, output, checking)
-    def get_data(self):
-        t = eval(sys.stdin.read())
+    def get_data(self, ifile):
+        t = eval(ifile.read())
         return t['depgraph'],t['types'],t['paths']
     def get_output_file(self):
         return sys.stdout
@@ -374,15 +387,13 @@ class pydepgraphdot (object) :
                 if not depgraph.has_key(dep):
                     # if dep not listed in depgraph somehow...
                     # add it in, with no further dependencies
-                    depgraph[dep] = {}        
+                    depgraph[dep] = {}
                     # add dummies to types and paths too, if neccessary
                    if not dep in types :
                         types[dep] = None
                    if not dep in paths :
                         paths[dep] = None
-                    if self._debug :
-                        print "Adding dummy entry for missing module '%s'" \
-                              % dep
+                    LOG.debug("Adding dummy entry for missing module '%s'"%dep)
         return (depgraph, types, paths)
 
     # keep a list of modules for a breadth-first search.
@@ -393,34 +404,48 @@ class pydepgraphdot (object) :
     def add_module_target(self, target_module) :
         if not target_module in self._modules_entered :
             # add to the back of the stack
-            if self._debug :  print '\tpush', target_module
+            LOG.debug('push %s' % target_module)
             self._modules_todo.append(target_module)
             self._modules_entered.append(target_module)
         # otherwise, it's already on the list, so don't worry about it.
     def next_module_target(self) :
         if len(self._modules_todo) > 0 :
-            if self._debug :  print '\tpop', self._modules_todo[0]
+            LOG.debug('pop %s' % self._modules_todo[0])
             return self._modules_todo.pop(0) # remove from front of the list
         else :
             return None # no more modules! we're done.
 
-            
-def main():
-    opts,args = getopt.getopt(sys.argv,'',['mono'])
-    colored = True
-    for o,v in opts:
-        if o=='--mono':
-            colored = False
+
+if __name__=='__main__':
+    from optparse import OptionParser
+
+    usage = '%prog [options]'
+    p = OptionParser(usage=usage, description=__doc__)
+    p.add_option('-v', '--verbose', default=0, action='count',
+                 help='Increment verbosity.')
+    p.add_option('-m', '--mono', dest='color', default=True,
+                 action='store_false', help="Don't use color.")
+    p.add_option('-i', '--input', dest='input', default='-',
+                 help="Path to input file ('-' for stdin, %default).")
+    options,args = p.parse_args()
+
+    log_level = logging.CRITICAL - 10*options.verbose
+    _STREAM_HANDLER.setLevel(log_level)
 
     # Fancyness with shared hooks instance so we can do slick thinks like
-    # printing all modules just inside an invisible zone, since we'll need 
+    # printing all modules just inside an invisible zone, since we'll need
     # the dotformatter to know which nodes are visible.
     hk = hooks(link_outside_visited_nodes=False)
-    #hk._debug = True
-    dt = dotformat_Cext(colored=colored, hooks_instance=hk)
+    dt = dotformat_Cext(colored=options.color, hooks_instance=hk)
     py = pydepgraphdot(hooks_instance=hk, dotformat_instance=dt)
-    #py._debug = True
-    py.render()
 
-if __name__=='__main__':
-    main()
+    if options.input == '-':
+        ifile = sys.stdin
+    else:
+        ifile = open(options.input, 'r')
+
+    try:
+        py.render(ifile)
+    finally:
+        if options.input != '-':
+            ifile.close()