blob: e49892ecdafadd27c4d976a224d3b9dd5a9be7be [file] [log] [blame]
Matteo Scandoloa6a3aee2019-11-26 13:30:14 -07001package fsm
2
3import (
4 "bytes"
5 "fmt"
6)
7
8// Visualize outputs a visualization of a FSM in Graphviz format.
9func Visualize(fsm *FSM) string {
10 var buf bytes.Buffer
11
12 states := make(map[string]int)
13
14 buf.WriteString(fmt.Sprintf(`digraph fsm {`))
15 buf.WriteString("\n")
16
17 // make sure the initial state is at top
18 for k, v := range fsm.transitions {
19 if k.src == fsm.current {
20 states[k.src]++
21 states[v]++
22 buf.WriteString(fmt.Sprintf(` "%s" -> "%s" [ label = "%s" ];`, k.src, v, k.event))
23 buf.WriteString("\n")
24 }
25 }
26
27 for k, v := range fsm.transitions {
28 if k.src != fsm.current {
29 states[k.src]++
30 states[v]++
31 buf.WriteString(fmt.Sprintf(` "%s" -> "%s" [ label = "%s" ];`, k.src, v, k.event))
32 buf.WriteString("\n")
33 }
34 }
35
36 buf.WriteString("\n")
37
38 for k := range states {
39 buf.WriteString(fmt.Sprintf(` "%s";`, k))
40 buf.WriteString("\n")
41 }
42 buf.WriteString(fmt.Sprintln("}"))
43
44 return buf.String()
45}