/
format.go
77 lines (68 loc) · 1.89 KB
/
format.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
package plan
import (
"fmt"
"runtime/debug"
"strings"
)
type FormatOption func(*formatter)
// Formatted accepts a plan.Spec and options, and returns a Formatter
// that can be used with the standard fmt package, e.g.,
// fmt.Println(Formatted(plan, WithDetails())
func Formatted(p *Spec, opts ...FormatOption) fmt.Formatter {
f := formatter{
p: p,
}
for _, o := range opts {
o(&f)
}
return f
}
// WithDetails returns a FormatOption that can be used to provide extra details
// in a formatted plan.
func WithDetails() FormatOption {
return func(f *formatter) {
f.withDetails = true
}
}
// Detailer provides an optional interface that ProcedureSpecs can implement.
// Implementors of this interface will have their details appear in the
// formatted output for a plan if the WithDetails() option is set.
type Detailer interface {
PlanDetails() string
}
type formatter struct {
withDetails bool
p *Spec
}
func (f formatter) Format(fs fmt.State, c rune) {
// Panicking while producing debug output is frustrating, so catch any panics and
// continue if that happens.
defer func() {
if e := recover(); e != nil {
_, _ = fmt.Fprintf(fs, "panic while formatting plan: %v\n", e)
_, _ = fmt.Fprintf(fs, "stack: %s\n", string(debug.Stack()))
}
}()
_, _ = fmt.Fprintf(fs, "digraph {\n")
var edges []string
_ = f.p.BottomUpWalk(func(pn Node) error {
_, _ = fmt.Fprintf(fs, " %v\n", pn.ID())
if f.withDetails {
if d, ok := pn.ProcedureSpec().(Detailer); ok {
lines := strings.Split(strings.TrimSpace(d.PlanDetails()), "\n")
for _, line := range lines {
_, _ = fmt.Fprintf(fs, " // %s\n", line)
}
}
}
for _, pred := range pn.Predecessors() {
edges = append(edges, fmt.Sprintf(" %v -> %v", pred.ID(), pn.ID()))
}
return nil
})
_, _ = fmt.Fprintf(fs, "\n")
for _, e := range edges {
_, _ = fmt.Fprintf(fs, "%v\n", e)
}
_, _ = fmt.Fprintf(fs, "}\n")
}