-
Notifications
You must be signed in to change notification settings - Fork 153
/
format.go
55 lines (48 loc) · 1.01 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
package flux
import (
"encoding/json"
"fmt"
)
// TODO(nathanielc): Add better options for formatting plans as Graphviz dot format.
type FormatOption func(*formatter)
func Formatted(q *Spec, opts ...FormatOption) fmt.Formatter {
f := formatter{
q: q,
}
for _, o := range opts {
o(&f)
}
return f
}
func FmtJSON(f *formatter) { f.json = true }
type formatter struct {
q *Spec
json bool
}
func (f formatter) Format(fs fmt.State, c rune) {
if c == 'v' && fs.Flag('#') {
fmt.Fprintf(fs, "%#v", f.q)
return
}
if f.json {
f.formatJSON(fs)
} else {
f.formatDAG(fs)
}
}
func (f formatter) formatJSON(fs fmt.State) {
e := json.NewEncoder(fs)
e.SetIndent("", " ")
e.Encode(f.q)
}
func (f formatter) formatDAG(fs fmt.State) {
fmt.Fprint(fs, "digraph QuerySpec {\n")
_ = f.q.Walk(func(o *Operation) error {
fmt.Fprintf(fs, "%s[kind=%q];\n", o.ID, o.Spec.Kind())
for _, child := range f.q.Children(o.ID) {
fmt.Fprintf(fs, "%s->%s;\n", o.ID, child.ID)
}
return nil
})
fmt.Fprintln(fs, "}")
}