| 1 | package debug |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "fmt" |
| 6 | "github.com/gobwas/glob/match" |
| 7 | "math/rand" |
| 8 | ) |
| 9 | |
| 10 | func Graphviz(pattern string, m match.Matcher) string { |
| 11 | return fmt.Sprintf(`digraph G {graph[label="%s"];%s}`, pattern, graphviz_internal(m, fmt.Sprintf("%x", rand.Int63()))) |
| 12 | } |
| 13 | |
| 14 | func graphviz_internal(m match.Matcher, id string) string { |
| 15 | buf := &bytes.Buffer{} |
| 16 | |
| 17 | switch matcher := m.(type) { |
| 18 | case match.BTree: |
| 19 | fmt.Fprintf(buf, `"%s"[label="%s"];`, id, matcher.Value.String()) |
| 20 | for _, m := range []match.Matcher{matcher.Left, matcher.Right} { |
| 21 | switch n := m.(type) { |
| 22 | case nil: |
| 23 | rnd := rand.Int63() |
| 24 | fmt.Fprintf(buf, `"%x"[label="<nil>"];`, rnd) |
| 25 | fmt.Fprintf(buf, `"%s"->"%x";`, id, rnd) |
| 26 | |
| 27 | default: |
| 28 | sub := fmt.Sprintf("%x", rand.Int63()) |
| 29 | fmt.Fprintf(buf, `"%s"->"%s";`, id, sub) |
| 30 | fmt.Fprintf(buf, graphviz_internal(n, sub)) |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | case match.AnyOf: |
| 35 | fmt.Fprintf(buf, `"%s"[label="AnyOf"];`, id) |
| 36 | for _, m := range matcher.Matchers { |
| 37 | rnd := rand.Int63() |
| 38 | fmt.Fprintf(buf, graphviz_internal(m, fmt.Sprintf("%x", rnd))) |
| 39 | fmt.Fprintf(buf, `"%s"->"%x";`, id, rnd) |
| 40 | } |
| 41 | |
| 42 | case match.EveryOf: |
| 43 | fmt.Fprintf(buf, `"%s"[label="EveryOf"];`, id) |
| 44 | for _, m := range matcher.Matchers { |
| 45 | rnd := rand.Int63() |
| 46 | fmt.Fprintf(buf, graphviz_internal(m, fmt.Sprintf("%x", rnd))) |
| 47 | fmt.Fprintf(buf, `"%s"->"%x";`, id, rnd) |
| 48 | } |
| 49 | |
| 50 | default: |
| 51 | fmt.Fprintf(buf, `"%s"[label="%s"];`, id, m.String()) |
| 52 | } |
| 53 | |
| 54 | return buf.String() |
| 55 | } |