2008/01/19

A very easy way to view dependencies: GraphViz

There is a wonderful and powerful tool called GraphViz that is able to draw graphs very easily. When I visited its website for the first time I thought it was very difficult to use, and this is completely false, so I will show how easy it can be.

This tool can do very powerful and complex graphs, but for the impatients (like me), that want to understand quickly how it works and be able to use it in another context (e.g. to show JAR dependencies in a Java application), I will show a very minimal example. Let's go.

First, you must download and install GraphViz. It is very easy to install. For Windows you have an installer, and for Linux you can use your favourite installer (at least Graphviz it's present in the Ubuntu Gutsy repositories, I don't know the other distributions).

Now, we will write a minimal text file with the dependencies we want to draw. Use your favourite editor and write a text file called 'sample.dot' with this content:

digraph g {
node1 -> node2
node2 -> node3
node2 -> node4
}

Now, you simply have to call the executable dot, from the GraphViz tool:

dot -Tpng -osample.png sample.dot

Pretty simple, isn't it ? We say we want to generate a PNG image (-T is the type of output file) and write it to an output file 'sample.png' from our graph file 'sample.dot'.

And the result is this:


Now, you can take a look at the documentation to know how to customize your graphs: you can specify colours, widths and shapes of your nodes, etc.

And one last advice: if the names of your nodes have spaces or special characters (like ':' or '\'), double quote them in the '.dot' file or you will get errors. So our last file would look like this:

digraph g {
"node1" -> "node2"
"node2" -> "node3"
"node2" -> "node4"
}

That's all. Enjoy making images of your dependencies!