-
Notifications
You must be signed in to change notification settings - Fork 3
/
grepp.go
342 lines (321 loc) · 8.81 KB
/
grepp.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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
// This file is part of grepp.
//
// Copyright (C) 2012-2024 David Gamba Rios
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
/*
Package main provides an improved version of the most common combinations of grep, find and sed in a single script.
*/
package main
import (
"context"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
greppLib "github.com/DavidGamba/dgtools/grepp/lib/grepp"
l "github.com/DavidGamba/dgtools/grepp/logging"
"github.com/DavidGamba/ffind/lib/ffind"
"github.com/mgutz/ansi"
)
func checkPatternInFile(filename string, pattern string, ignoreCase bool) (bool, error) {
re, _ := getRegex(pattern, ignoreCase)
for le := range ReadLineByLine(filename, bufferSize) {
if le.Error != nil {
return false, le.Error
}
match := re.MatchString(string(le.Line))
if match {
return true, nil
}
}
return false, nil
}
type lineMatch struct {
filename string
n int
match [][]string
end []string
line string
}
func getRegex(pattern string, ignoreCase bool) (re, reEnd *regexp.Regexp) {
if ignoreCase {
re = regexp.MustCompile(`(?i)(.*?)(?P<pattern>` + pattern + `)`)
reEnd = regexp.MustCompile(`(?i).*` + pattern + `(.*?)$`)
} else {
re = regexp.MustCompile(`(.*?)(?P<pattern>` + pattern + `)`)
reEnd = regexp.MustCompile(`.*` + pattern + `(.*?)$`)
}
return
}
// TODO: Handle error properly here
func searchInFile(filename, pattern string, ignoreCase bool) <-chan lineMatch {
c := make(chan lineMatch)
re, reEnd := getRegex(pattern, ignoreCase)
go func() {
for le := range ReadLineByLine(filename, bufferSize) {
if le.Error != nil {
l.Error.Fatal(le.Error)
}
match := re.FindAllStringSubmatch(string(le.Line), -1)
remainder := reEnd.FindStringSubmatch(string(le.Line))
c <- lineMatch{filename: filename, n: le.LineNumber, line: string(le.Line), match: match, end: remainder}
}
close(c)
}()
return c
}
func color(color string, line string, useColor bool) string {
if useColor {
return fmt.Sprintf("%s%s", color, line)
}
return line
}
func colorReset(useColor bool) string {
if useColor {
return ansi.Reset
}
return ""
}
func (g grepp) writeLineMatch(file *os.File, lm lineMatch) {
for _, m := range lm.match {
replace := g.replace
if strings.Contains(g.replace, `\1`) {
if len(m) >= 4 {
replace = strings.ReplaceAll(replace, `\1`, m[3])
}
if len(m) >= 5 {
replace = strings.ReplaceAll(replace, `\2`, m[4])
}
if len(m) >= 6 {
replace = strings.ReplaceAll(replace, `\3`, m[5])
}
if len(m) >= 7 {
replace = strings.ReplaceAll(replace, `\4`, m[6])
}
if len(m) >= 8 {
replace = strings.ReplaceAll(replace, `\5`, m[7])
}
}
file.WriteString(m[1] + replace)
}
file.WriteString(lm.end[len(lm.end)-1] + "\n")
}
// Each section is in charge of starting with the color or reset.
func (g grepp) printLineMatch(lm lineMatch) {
stringLine := func() string {
if g.useColor {
result := ansi.Reset
l.Debug.Printf("[printLineMatch] %#v\n", lm)
for _, m := range lm.match {
replace := g.replace
if strings.Contains(g.replace, `\1`) {
if len(m) >= 4 {
replace = strings.ReplaceAll(replace, `\1`, m[3])
}
if len(m) >= 5 {
replace = strings.ReplaceAll(replace, `\2`, m[4])
}
if len(m) >= 6 {
replace = strings.ReplaceAll(replace, `\3`, m[5])
}
if len(m) >= 7 {
replace = strings.ReplaceAll(replace, `\4`, m[6])
}
if len(m) >= 8 {
replace = strings.ReplaceAll(replace, `\5`, m[7])
}
l.Debug.Printf("[printLineMatch] replace: %s\n", replace)
}
result += fmt.Sprintf("%s%s%s%s%s%s",
stripCtlFromUTF8(m[1]),
ansi.Red,
stripCtlFromUTF8(m[2]),
ansi.Green,
stripCtlFromUTF8(replace),
ansi.Reset)
}
result += stripCtlFromUTF8(lm.end[len(lm.end)-1])
return result
}
return stripCtlFromUTF8(lm.line)
}
result := ""
if g.showFile {
result += color(ansi.Magenta, lm.filename, g.useColor) + " " + color(ansi.Blue, ":", g.useColor)
}
if g.useNumber {
result += color(ansi.Green, strconv.Itoa(lm.n), g.useColor) + color(ansi.Blue, ":", g.useColor)
}
result += colorReset(g.useColor) + " " + stringLine()
fmt.Fprintln(g.Stdout, result)
}
// Each section is in charge of starting with the color or reset.
func (g grepp) printMinorWarning(line string) {
result := color(ansi.LightBlack, line, g.useColor)
fmt.Fprintln(g.Stderr, result)
}
// Each section is in charge of starting with the color or reset.
func (g grepp) printLineContext(lm lineMatch) {
result := ""
if g.showFile {
result += color(ansi.Magenta, lm.filename, g.useColor) + " " + color(ansi.Blue, "-", g.useColor)
}
if g.useNumber {
result += color(ansi.Green, strconv.Itoa(lm.n), g.useColor) + color(ansi.Blue, "-", g.useColor)
}
result += colorReset(g.useColor) + " " + lm.line
fmt.Fprintln(g.Stdout, result)
}
type grepp struct {
ignoreBinary bool
caseSensitive bool
useColor bool
useNumber bool
filenameOnly bool
replace string
force bool
context int
searchBase string
// Controls whether or not to show the filename. If the given location is a
// file then there is no need to show the filename
showFile bool
showBufferSizeErrors bool
bufferSizeErrorsC int
pattern string
filePattern string
ignoreFilePattern string
ignoreExtensionList []string
Stdout io.Writer
Stderr io.Writer
}
func (g grepp) String() string {
return fmt.Sprintf("ignoreBinary: %v, caseSensitive: %v, useColor %v, useNumber %v, filenameOnly %v, force %v",
g.ignoreBinary, g.caseSensitive, g.useColor, g.useNumber, g.filenameOnly, g.force)
}
func (g grepp) getFileList() <-chan ffind.FileError {
c := make(chan ffind.FileError)
go func() {
if g.showFile {
ch := ffind.ListRecursive(
g.searchBase,
true,
&ffind.BasicFileMatch{
IgnoreDirResults: true,
IgnoreFileResults: false,
IgnoreVCSDirs: true,
IgnoreHidden: true,
IgnoreFileExtensionList: g.ignoreExtensionList,
},
ffind.SortFnByName)
for e := range ch {
if e.Error != nil {
fmt.Fprintf(os.Stderr, "ERROR: '%s' %s\n", e.Path, e.Error)
// Ignore broken symlinks
if os.IsNotExist(e.Error) {
continue
}
}
c <- e
}
} else {
// TODO: FileInfo is not generated here. Check if it is needed.
c <- ffind.FileError{
Path: g.searchBase,
}
}
close(c)
}()
return c
}
func (g grepp) Run(ctx context.Context) error {
for ch := range g.getFileList() {
filename := ch.Path
if g.ignoreBinary && !greppLib.IsTextMIME(filename) {
continue
}
if g.filenameOnly {
ok, err := checkPatternInFile(filename, g.pattern, !g.caseSensitive)
if err != nil {
if errors.Is(err, errorBufferSizeTooSmall) {
if g.showBufferSizeErrors {
g.printMinorWarning(fmt.Sprintf("%s : %s\n", filename, err.Error()))
} else {
g.bufferSizeErrorsC++
}
} else {
fmt.Fprintf(g.Stderr, "%s\n", err)
}
} else if ok {
fmt.Fprintf(g.Stdout, "%s%s\n", color(ansi.Magenta, filename, g.useColor), colorReset(g.useColor))
}
} else {
ok, err := checkPatternInFile(filename, g.pattern, !g.caseSensitive)
if err != nil {
if errors.Is(err, errorBufferSizeTooSmall) {
if g.showBufferSizeErrors {
g.printMinorWarning(fmt.Sprintf("%s : %s\n", filename, err.Error()))
} else {
g.bufferSizeErrorsC++
}
} else {
fmt.Fprintf(g.Stderr, "%s\n", err)
}
} else if ok {
var tmpFile *os.File
var err error
if g.force {
tmpFile, err = os.CreateTemp("", filepath.Base(filename)+"-")
defer tmpFile.Close()
if err != nil {
l.Error.Println("cannot open ", tmpFile)
l.Error.Fatal(err)
}
l.Debug.Printf("tmpFile: %v", tmpFile.Name())
}
for d := range searchInFile(filename, g.pattern, !g.caseSensitive) {
if len(d.match) == 0 {
if g.context > 0 {
g.printLineContext(d)
}
} else {
g.printLineMatch(d)
}
if g.force {
if len(d.match) == 0 {
tmpFile.WriteString(d.line + "\n")
} else {
g.writeLineMatch(tmpFile, d)
}
}
}
if g.force {
tmpFile.Close()
err = copyFileContents(tmpFile.Name(), filename)
if err != nil {
l.Warning.Printf("Couldn't update file: %s. '%s'\n", filename, err)
}
}
}
}
}
if g.bufferSizeErrorsC > 0 {
fmt.Fprintf(g.Stderr, "WARNING: %s found %d times\n", errorBufferSizeTooSmall, g.bufferSizeErrorsC)
}
return nil
}
func (g *grepp) SetStderr(w io.Writer) {
l.Warning.SetOutput(w)
l.Error.SetOutput(w)
g.Stderr = w
}
func (g *grepp) SetStdout(w io.Writer) {
l.Info.SetOutput(w)
g.Stdout = w
}