Skip to main content

Graphviz: fast and simple diagrams

Lately I've been looking for tools that take plain-text and generate a representation useful for humans. These are generally easy to use with git, and to build scripts around. Also, because they are operated from plain-text, they usually can be treated as a distraction-free way of organizing data.

Graphviz is one of such tools, it allows us to define this:

1
2
3
4
5
6
7
8
digraph {
  rankdir=LR;  // Set orientation as horizontal

  // And just define the connections.
  one -> two -> three;
  three -> four;
  four -> two;
}

And obtain this image:

Render of the sample code

Good for scripting

It can be used by a quick & dirty script to process and summarize some information:

parse-makefile.sh

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#!/usr/bin/env bash
#
# Important lines of a makefile
#
#   compiled_program: program.c program.h
#    ↑ target         ↑ dependencies


if [ -z "$1" ];then
    echo "$0 <Makefile>"
    exit 0
fi

MAKEFILE="$1"

echo 'digraph {'  # Start directed graph
for t in $(grep -P '^[^#\s:]*:' "$MAKEFILE"|cut -d: -f1|tr -d "\"'");do

    # Targets with special meaning
    if [ "$t" == ".PHONY" ] || [ "$t" == ".INTERMEDIATE" ]; then
        continue
    fi

    echo "    \"$t\";";  # Have the target stand alone if there's no dependencies

    for dependency in $(grep "^$t:" "$MAKEFILE" | cut -d: -f2-|tr -d "\"'");do
        echo "    \"$dependency\" -> \"$t\"";
    done
done

echo '}' # Finish graph

Execution

On Distel's Makefile

1
bash parse-makefile.sh distel/Makefile > makefile.dot && dot makefile.dot -Tsvg -o makefile.svg

Result

Result of the script above

Simple and compact

It can also be used on an editor with a live preview plugin ( Emacs, VSCode ...) to generate documentation without having to point-and-click or worry about the layout.

This was generated from the old Plaza's task tree, where tasks were just added and linked to its dependencies to generate the following "technology tree":

Old Plaza's task tree

Anyway, it's a tool that strikes a good balance between power and simplicty. It also has too many options to list them here, just search for whatever you need and you'll find it :)

Just keep it in mind if you sometime need a tool to generate diagrams either manually or automatically, I've found it specially useful for hierarchical structures like dependencie trees.

References