utils.go 935 B

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