-
Notifications
You must be signed in to change notification settings - Fork 172
/
view.go
98 lines (84 loc) · 2.45 KB
/
view.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
package ffmpeg_go
import (
"bytes"
"fmt"
)
type ViewType string
const (
// FlowChart the diagram type for output in flowchart style (https://mermaid-js.github.io/mermaid/#/flowchart) (including current state
ViewTypeFlowChart ViewType = "flowChart"
// StateDiagram the diagram type for output in stateDiagram style (https://mermaid-js.github.io/mermaid/#/stateDiagram)
ViewTypeStateDiagram ViewType = "stateDiagram"
)
func (s *Stream) View(viewType ViewType) (string, error) {
switch viewType {
case ViewTypeFlowChart:
return visualizeForMermaidAsFlowChart(s)
case ViewTypeStateDiagram:
return visualizeForMermaidAsStateDiagram(s)
default:
return "", fmt.Errorf("unknown ViewType: %s", viewType)
}
}
func visualizeForMermaidAsStateDiagram(s *Stream) (string, error) {
var buf bytes.Buffer
nodes := getStreamSpecNodes([]*Stream{s})
var dagNodes []DagNode
for i := range nodes {
dagNodes = append(dagNodes, nodes[i])
}
sorted, outGoingMap, err := TopSort(dagNodes)
if err != nil {
return "", err
}
buf.WriteString("stateDiagram\n")
for _, node := range sorted {
next := outGoingMap[node.Hash()]
for k, v := range next {
for _, nextNode := range v {
label := string(k)
if label == "" {
label = "<>"
}
buf.WriteString(fmt.Sprintf(` %s --> %s: %s`, node.ShortRepr(), nextNode.Node.ShortRepr(), label))
buf.WriteString("\n")
}
}
}
return buf.String(), nil
}
// visualizeForMermaidAsFlowChart outputs a visualization of a FSM in Mermaid format (including highlighting of current state).
func visualizeForMermaidAsFlowChart(s *Stream) (string, error) {
var buf bytes.Buffer
nodes := getStreamSpecNodes([]*Stream{s})
var dagNodes []DagNode
for i := range nodes {
dagNodes = append(dagNodes, nodes[i])
}
sorted, outGoingMap, err := TopSort(dagNodes)
if err != nil {
return "", err
}
buf.WriteString("graph LR\n")
for _, node := range sorted {
buf.WriteString(fmt.Sprintf(` %d[%s]`, node.Hash(), node.ShortRepr()))
buf.WriteString("\n")
}
buf.WriteString("\n")
for _, node := range sorted {
next := outGoingMap[node.Hash()]
for k, v := range next {
for _, nextNode := range v {
// todo ignore merged output
label := string(k)
if label == "" {
label = "<>"
}
buf.WriteString(fmt.Sprintf(` %d --> |%s| %d`, node.Hash(), fmt.Sprintf("%s:%s", nextNode.Label, label), nextNode.Node.Hash()))
buf.WriteString("\n")
}
}
}
buf.WriteString("\n")
return buf.String(), nil
}