This repository has been archived by the owner on Dec 1, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 12
/
tree_dotgraph.go
109 lines (92 loc) · 2.4 KB
/
tree_dotgraph.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package iavl
import (
"bytes"
"fmt"
"io"
"text/template"
)
type graphEdge struct {
From, To string
}
type graphNode struct {
Hash string
Label string
Value string
Attrs map[string]string
}
type graphContext struct {
Edges []*graphEdge
Nodes []*graphNode
}
var graphTemplate = `
strict graph {
{{- range $i, $edge := $.Edges}}
"{{ $edge.From }}" -- "{{ $edge.To }}";
{{- end}}
{{range $i, $node := $.Nodes}}
"{{ $node.Hash }}" [label=<{{ $node.Label }}>,{{ range $k, $v := $node.Attrs }}{{ $k }}={{ $v }},{{end}}];
{{- end}}
}
`
var tpl = template.Must(template.New("iavl").Parse(graphTemplate))
var defaultGraphNodeAttrs = map[string]string{
"shape": "circle",
}
func WriteDOTGraph(w io.Writer, tree *ImmutableTree, paths []PathToLeaf) {
ctx := &graphContext{}
root := tree.getRoot()
if root == nil {
return
}
root.hashWithCount()
root.traverse(tree, true, func(node *Node) bool {
graphNode := &graphNode{
Attrs: map[string]string{},
Hash: fmt.Sprintf("%x", node.hash),
}
for k, v := range defaultGraphNodeAttrs {
graphNode.Attrs[k] = v
}
shortHash := graphNode.Hash[:7]
graphNode.Label = mkLabel(fmt.Sprintf("%x", node.key), 16, "sans-serif")
graphNode.Label += mkLabel(shortHash, 10, "monospace")
graphNode.Label += mkLabel(fmt.Sprintf("version=%d", node.version), 10, "monospace")
if node.value != nil {
graphNode.Label += mkLabel(fmt.Sprintf("%x", node.value), 10, "sans-serif")
}
if node.height == 0 {
graphNode.Attrs["fillcolor"] = "lightgrey"
graphNode.Attrs["style"] = "filled"
}
for _, path := range paths {
for _, n := range path {
if bytes.Equal(n.Left, node.hash) || bytes.Equal(n.Right, node.hash) {
graphNode.Attrs["peripheries"] = "2"
graphNode.Attrs["style"] = "filled"
graphNode.Attrs["fillcolor"] = "lightblue"
break
}
}
}
ctx.Nodes = append(ctx.Nodes, graphNode)
if node.leftNode != nil {
ctx.Edges = append(ctx.Edges, &graphEdge{
From: graphNode.Hash,
To: fmt.Sprintf("%x", node.leftNode.hash),
})
}
if node.rightNode != nil {
ctx.Edges = append(ctx.Edges, &graphEdge{
From: graphNode.Hash,
To: fmt.Sprintf("%x", node.rightNode.hash),
})
}
return false
})
if err := tpl.Execute(w, ctx); err != nil {
panic(err)
}
}
func mkLabel(label string, pt int, face string) string {
return fmt.Sprintf("<font face='%s' point-size='%d'>%s</font><br />", face, pt, label)
}