somewhat daily mutterings

/Programming Creating an IntelliJ Module Dependency Graph with Only Unix tools, Dot, and GraphViz

Every so often I like to generate a dependency graph of the modules in our system. Historically, I've used an IntelliJ plug-in to do it. The plug-in generated a "graphml" file that could be displayed using yEd. All-in-all a pretty good approach.

So, yesterday I went to do just that. However, the plug-in apparently doesn't work in IntelliJ 9.x. Bummer. What to do? Well, I know that IntelliJ module definitions are stored in .iml files. I also know these files are XML. So, I popped open one of our .imls and discovered that module dependencies are recorded as follows:

<orderEntry type="module" module-name="bridging" />
I thought to myself, "Self, seems like I should be able to process our .iml files with some Unix utilities and generate a "dot" file that can be rendered by GraphViz. I'll bet I can do that in a half-hour." I won the bet.

Here is the script I hacked out in about 20 minutes. I first did it at the command line, then canned it in a .sh file.

  echo 'digraph g {'
  echo 'graph [ ratio="1.0" ];'
  echo 'node [ shape="rectangle", style="bold", width="5.0", height="2.0", fontsize="42" ];'

  # Find all the module files beneath this directory
  # Process only orderEntry elements of those files
  # Get rid of XML stuff
  # Extract module name from file name
  # Unquote to get tokens accessible to awk
  # Output node dependencies
  # Strip out uninteresting nodes (could be done earlier, but prettier at the bottom).
  find . -name '*.iml' \
      | xargs grep -H 'orderEntry.*module' \
      | sort \
      | sed 's///g' \
      | sed 's/\..*\///g;s/\.iml://g' \
      | sed 's/"/ /g;' \
      | awk '{print $1, "->", $6, ";"}' \
      | grep -v 'webapp' \
      | grep -v 'devTools' \
      | grep -v 'common' \
  echo '}'

Note: I make no claims about the elegance of the script!

The above script processes all the .iml files in our project, extracts the module dependency lines, does some sed replacements to get useable tokens, and awk to print out the actual dependency lines. If you open the file in GraphViz, it generates a diagram something like this:

This, my friends, is why all the cool kids run Unix-like OSs (Mac OS X in my case).

Posted: Wed Sep 29 20:29:11 -0700 2010

Thanks for visiting! Send comments to Mike Thomas.