Holger Hildebrandt | fa07499 | 2020-03-27 15:42:06 +0000 | [diff] [blame] | 1 | package fsm |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "fmt" |
| 6 | ) |
| 7 | |
| 8 | // Visualize outputs a visualization of a FSM in Graphviz format. |
| 9 | func 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 | } |