GO - Create a dependency graph en

By Spider.007 on Wednesday 4 December 2013 11:02
Category: go, Views: 2.743

Creating a dependency graph for your go file is simple; but I couldn't really find what I needed; so I created this simple script. It creates graphs from the `go list` output. Usage is simple, install graphviz and type:

$ go build dependency-graph.go
$ ./dependency-graph FILE.go | dot -Tpng > FILE.png


You can also pass go-packages as starting point:
$ ./dependency-graph net/mail | dot -Tpng > FILE.png


The code:

Go:
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package main

import (
    "encoding/json"
    "fmt"
    "os"
    "os/exec"
)

type goList struct {
    Imports []string
}

var done = make(map[string]bool)

func getDeps(p string) []string {
    o, err := exec.Command("go", "list", "-json", p).Output()

    if err != nil {
        fmt.Fprintf(os.Stderr, "Error: %s", err)
    }

    list := goList{}
    json.Unmarshal(o, &list)

    return list.Imports
}

func printRecursive(p string) {
    done[p] = true

    for _, d := range getDeps(p) {
        fmt.Printf("\t\"%s\" -- \"%s\";\n", p, d)

        if !done[d] {
            printRecursive(d)
        }
    }
}

func main() {
    fmt.Println("graph G {")
    printRecursive(os.Args[1])
    fmt.Println("}")
}

Volgende: A safe backup-server with rsync, chroot and forced commands 11-'12 A safe backup-server with rsync, chroot and forced commands

Comments

Comments are closed