Build a dependency graph in python

Assuming your input from above is given as a string in raw:

import networkx as nx
import re

regex = re.compile(r'^([A-Z]+)::Requires\s+=\s([A-Z"]+)$')

G = nx.DiGraph()
roots = set()
for l in raw.splitlines():
    if len(l):
        target, prereq = regex.match(l).groups()
        if prereq == '""':
            roots.add(target)
        else:
            G.add_edge(prereq, target)

Now print the tree(s):

for s in roots:
    print s
    spacer = {s: 0}
    for prereq, target in nx.dfs_edges(G, s):
        spacer[target] = spacer[prereq] + 2
        print '{spacer}+-{t}'.format(
                                     spacer=" " * spacer[prereq],
                                     t=target)
    print ''

this prints:

A
+-H
+-B
  +-C

AA
+-BB
  +-CC

This requires that all roots are presented through root::Requires = "" in order for them to be identified as such.

Leave a Comment

tech