-
Notifications
You must be signed in to change notification settings - Fork 0
/
process.go
126 lines (102 loc) · 1.96 KB
/
process.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package vl
import (
"bufio"
"io"
"os"
"regexp"
"strconv"
"strings"
verticaltable "github.com/bayashi/go-verticaltable"
)
type Column struct {
Label string
Show bool
}
type Header struct {
Columns []*Column
}
type Options struct {
GrepRe []*regexp.Regexp
Labels []string
VtOpts *verticaltable.VTOptions
NoPager bool
PS bool
}
type VL struct {
Count int
Header *Header
Options *Options
Splitter *regexp.Regexp
}
func (v *VL) Process(out io.Writer) {
s := bufio.NewScanner(os.Stdin)
for s.Scan() {
line := s.Bytes()
v.processLine(out, line)
}
}
func (v *VL) processLine(out io.Writer, origLine []byte) {
if len(origLine) == 0 {
return
}
if v.Count == 0 {
v.Header = v.ParseHeader(origLine)
}
if v.Count > 0 {
if len(v.Options.GrepRe) > 0 && v.isFiltered(origLine) {
return
}
vt := verticaltable.NewTable(out, v.Options.VtOpts)
vt.Header(strconv.Itoa(v.Count))
for i, elem := range v.parseLine(origLine) {
if !v.Header.Columns[i].Show {
continue
}
vt.Row(v.Header.Columns[i].Label, elem)
}
vt.Render()
}
v.Count++
}
func (v *VL) ParseHeader(line []byte) *Header {
var re string
if v.Options.PS {
re = `\s+`
} else {
re = `\s\s+`
}
v.Splitter = regexp.MustCompile(re)
labels := v.Splitter.Split(strings.TrimSpace(string(line)), -1)
hs := &Header{}
for _, label := range labels {
c := &Column{
Label: label,
Show: isShownLabel(label, v.Options.Labels),
}
hs.Columns = append(hs.Columns, c)
}
return hs
}
func isShownLabel(label string, labels []string) bool {
if len(labels) == 0 {
return true
}
for _, l := range labels {
if l == label {
return true
}
}
return false
}
// true:filtering, false:show
func (v *VL) isFiltered(origLine []byte) bool {
for _, r := range v.Options.GrepRe {
if !r.Match(origLine) {
return true
}
}
return false
}
func (v *VL) parseLine(origLine []byte) []string {
return v.Splitter.Split(string(origLine), len(v.Header.Columns))
}