-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvisualizer_graphviz.go
More file actions
executable file
·74 lines (60 loc) · 1.9 KB
/
Copy pathvisualizer_graphviz.go
File metadata and controls
executable file
·74 lines (60 loc) · 1.9 KB
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
package msm
import (
"bytes"
"fmt"
"sort"
)
func getSortedTransitionKeys(fm *FSM) []TransitionKey {
// we sort the key alphabetically to have a reproducible graph output
sortedTransitionKeys := make([]TransitionKey, 0)
for transition := range fm.Table {
sortedTransitionKeys = append(sortedTransitionKeys, transition)
}
sort.Slice(sortedTransitionKeys, func(i, j int) bool {
if sortedTransitionKeys[i].State == sortedTransitionKeys[j].State {
return sortedTransitionKeys[i].Event.Name() < sortedTransitionKeys[j].Event.Name()
}
return sortedTransitionKeys[i].State < sortedTransitionKeys[j].State
})
return sortedTransitionKeys
}
func getSortedStates(fm *FSM) []string {
// we sort the key alphabetically to have a reproducible graph output
states := make(map[string]struct{})
for src, transitions := range fm.Table {
states[string(src.State)] = struct{}{}
for _, transition := range transitions {
states[string(transition.NewState)] = struct{}{}
}
}
sortedStates := make([]string, 0)
for state := range states {
sortedStates = append(sortedStates, state)
}
sort.Slice(sortedStates, func(i, j int) bool {
return sortedStates[i] < sortedStates[j]
})
return sortedStates
}
// Visualize outputs a visualization of a FSM in Graphviz format.
func Visualize(fm *FSM) string {
var buf bytes.Buffer
// we sort the key alphabetically to have a reproducible graph output
sortedEKeys := getSortedTransitionKeys(fm)
sortedStateKeys := getSortedStates(fm)
buf.WriteString(`digraph fsm {\n`)
for _, k := range sortedEKeys {
v := fm.Table[k]
for _, transition := range v {
buf.WriteString(fmt.Sprintf(` "%s" -> "%s" [ label = "%s" ];`, k.State, transition.NewState, k.Event))
buf.WriteString("\n")
}
}
buf.WriteString("\n")
for _, k := range sortedStateKeys {
buf.WriteString(fmt.Sprintf(` "%s";`, k))
buf.WriteString("\n")
}
buf.WriteString("}\n")
return buf.String()
}