-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathprinter.go
More file actions
92 lines (75 loc) · 1.77 KB
/
printer.go
File metadata and controls
92 lines (75 loc) · 1.77 KB
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
package main
import (
"fmt"
"io"
"log"
"regexp"
"text/template"
"github.com/egonelbre/spexs2/search"
)
type strFeature func(*search.Query) string
func (s *AppSetup) initPrinter() {
format := s.conf.Printer.Format
header := s.conf.Printer.Header
showHeader := s.conf.Printer.ShowHeader
if header == "" {
regHdr := regexp.MustCompile(`[\{\}]`)
header = regHdr.ReplaceAllString(format, "")
}
features := make(map[string]strFeature)
featureIdx := 0
regFeature := regexp.MustCompile(`[a-zA-Z?() @~,]+`)
format = regFeature.ReplaceAllStringFunc(format,
func(call string) string {
feature, info := s.makeFeatureEx(call)
var feat strFeature
if !info {
feat = func(q *search.Query) string {
val, _ := feature(q)
return fmt.Sprintf("%v", val)
}
} else {
feat = func(q *search.Query) string {
_, info := feature(q)
return info
}
}
name := fmt.Sprintf("f%v", featureIdx)
featureIdx++
features[name] = feat
return "{{." + name + "}}"
})
tmpl, err := template.New("").Parse(format)
if err != nil {
log.Println("Unable to create template based on output format. ", format)
log.Fatal(err)
}
printQuery := func(out io.Writer, q *search.Query) {
values := make(map[string]string)
for name, fn := range features {
values[name] = fn(q)
}
err = tmpl.Execute(out, values)
if err != nil {
log.Println("Unable to output pattern.")
log.Fatal(err)
}
}
s.printQuery = printQuery
s.Printer = func(out io.Writer, pool search.Pooler) {
values := pool.Values()
if showHeader {
fmt.Fprint(out, header)
}
if !s.conf.Printer.Reverse {
for _, q := range values {
printQuery(out, q)
}
} else {
for i := len(values) - 1; i >= 0; i-- {
q := values[i]
printQuery(out, q)
}
}
}
}