-
Notifications
You must be signed in to change notification settings - Fork 1
/
grep.go
224 lines (210 loc) · 5.21 KB
/
grep.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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
package fsearch
import (
"bytes"
"fmt"
"io"
"log"
"net/http"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"sync"
)
type DirGrep struct {
Dir string
}
func NewDirGrep(dir string) *DirGrep {
return &DirGrep{Dir: dir}
}
// FileNames get all file names in the directory.
func (f *DirGrep) FileNames() []string {
return f.fileNamesBy(nil)
}
// fileNamesBy get file names by fileMap, if fileMap is empty, all files in the directory are searched.
func (f *DirGrep) fileNamesBy(fileMap map[string]struct{}) []string {
dirEntries, err := os.ReadDir(f.Dir)
if err != nil {
return nil
}
var fileNames []string
for _, entry := range dirEntries {
if entry.IsDir() {
continue
}
// filter file by file name when start with .
if strings.HasPrefix(entry.Name(), ".") {
continue
}
// filter file if there is no dot in the file name
if !strings.Contains(entry.Name(), ".") {
continue
}
// filter file if binary file
if isBinaryFile(filepath.Join(f.Dir, entry.Name())) {
continue
}
if len(fileMap) == 0 {
fileNames = append(fileNames, entry.Name())
continue
}
if _, ok := fileMap[entry.Name()]; ok {
fileNames = append(fileNames, entry.Name())
}
}
return fileNames
}
// check if the file is binary file
func isBinaryFile(filePath string) bool {
cmd := exec.Command("file", filePath)
var out bytes.Buffer
cmd.Stdout = &out
err := cmd.Run()
if err != nil {
return false
}
return strings.Contains(out.String(), "binary")
}
// SearchAndWriteParam is the parameter of SearchAndWrite.
type SearchAndWriteParam struct {
Writer io.Writer // The Writer is used to write the search results.
HostName string // The HostName is used to distinguish the host where the file is located.
MaxLines int // At most MaxLines lines of output are printed for each file searched. The default is defaultMaxLines.
FileMap map[string]struct{} // The FileMap is used to filter the files to be searched. If the fileMap is empty, all files in the directory are searched.
Kws []string // The Kws is the keyword to be searched.
}
type fileNameAndLines struct {
fileName string
lines []string
}
func (f *DirGrep) SearchAndWrite(param *SearchAndWriteParam) {
if param == nil {
return
}
w := param.Writer
hostName := param.HostName
maxLines := param.MaxLines
if maxLines <= 0 {
maxLines = defaultMaxLines
}
fileMap := param.FileMap
kws := param.Kws
if len(kws) == 0 {
return
}
fileNames := f.fileNamesBy(fileMap)
chanLines := make(chan *fileNameAndLines, len(fileNames))
var wg sync.WaitGroup
for _, name := range fileNames {
name := name
filePath := filepath.Join(f.Dir, name)
wg.Add(1)
go func() {
defer wg.Done()
lines := grepFromFile(maxLines, filePath, kws...)
if len(lines) == 0 {
return
}
chanLines <- &fileNameAndLines{
fileName: name,
lines: lines,
}
}()
}
go func() {
wg.Wait()
close(chanLines)
}()
for fLines := range chanLines {
name := fLines.fileName
lines := fLines.lines
_, err := w.Write([]byte(fmt.Sprintf("<<<<<< --------------------%s %s -------------------- >>>>>>\n", hostName, name)))
if err != nil {
return
}
for _, line := range lines {
_, err := w.Write([]byte(line + "\n"))
if err != nil {
return
}
if flusher, ok := w.(http.Flusher); ok {
flusher.Flush()
}
}
}
}
func buildLines(buffer []byte, maxLines int, kwsFilter []string) []string {
p := bytes.TrimSpace(buffer)
text := string(p)
lines := strings.Split(text, "\n")
if len(kwsFilter) == 0 {
if len(lines) > maxLines {
return lines[:maxLines]
}
return lines
}
linesFilter := make([]string, 0, len(lines))
for _, line := range lines {
write := true
// if any kw not in line, not write
for _, kw := range kwsFilter {
if !strings.Contains(line, kw) {
write = false
break
}
}
if write {
if len(linesFilter) >= maxLines {
break
}
linesFilter = append(linesFilter, line)
}
}
return linesFilter
}
func grepFromFile(maxLines int, filePath string, kws ...string) []string {
kws = parseDuplicateKws(kws)
if len(kws) == 0 {
return nil
}
kwsFilter := kws[1:]
grepMaxLines := maxLines
if len(kwsFilter) > 0 {
grepMaxLines = maxLines * 2
}
// maxLines * 2 in case the number of lines found by the grep command in the file is not enough maxLines
cmdArgs := []string{"-m", strconv.Itoa(grepMaxLines), "--color=never", "-a", "--", kws[0], filePath}
log.Printf("grep %s\n", strings.Join(cmdArgs, " "))
cmd := exec.Command("grep", cmdArgs...)
var buf bytes.Buffer
cmd.Stdout = &buf
cmd.Stderr = &buf
err := cmd.Run()
if err != nil {
// err may be io.EOF, we ignore it
// signal: broken pipe when exceed maxLines, we ignore it
// exit status 1 when no match, we ignore it
return nil
}
return buildLines(buf.Bytes(), maxLines, kwsFilter)
}
// parseDuplicateKws parse duplicate []string and remain the order
func parseDuplicateKws(kws []string) []string {
if len(kws) == 0 {
return nil
}
kwsMap := make(map[string]struct{}, len(kws))
var kwsResult []string
for _, kw := range kws {
if kw == "" {
continue
}
if _, ok := kwsMap[kw]; ok {
continue
}
kwsMap[kw] = struct{}{}
kwsResult = append(kwsResult, kw)
}
return kwsResult
}