-
Notifications
You must be signed in to change notification settings - Fork 1
/
grepz.go
309 lines (269 loc) · 7.49 KB
/
grepz.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
package main
import (
"bufio"
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"regexp"
"strings"
)
func main() {
var insensitive bool
var useBox bool
var up int
var down int
var bgColorFlag string
var fgColorFlag string
flag.BoolVar(&insensitive, "i", false, "Case insensitive search")
flag.BoolVar(&useBox, "box", false, "Use box highlighting")
flag.BoolVar(&useBox, "b", false, "Use box highlighting (shorthand)")
flag.IntVar(&up, "up", 0, "Lines of context to show after match")
flag.IntVar(&down, "down", 0, "Lines of context to show before match")
flag.StringVar(&bgColorFlag, "bg", "", "Background color of the match\nColors: [red, green, yellow, blue, magenta, cyan, white, black, pink]")
flag.StringVar(&fgColorFlag, "fg", "", "Foreground color of the match\nColors: [red, green, yellow, blue, magenta, cyan, white, black, pink]")
flag.Usage = func() {
fmt.Printf("Usage: grepz [-i] [-box|-b] [-up num] [-down num] <search_term> [<input_file>]\n")
fmt.Printf("Flags:\n")
flag.PrintDefaults()
}
flag.Parse()
args := flag.Args()
if len(args) < 1 {
flag.Usage()
return
}
searchTerm := args[0]
validColors := []string{"red", "green", "yellow", "blue", "magenta", "cyan", "white", "black", "pink"}
if !contains(validColors, bgColorFlag) {
fmt.Printf("Error: %s is not a valid background color\n\n", bgColorFlag)
flag.Usage()
return
}
if !contains(validColors, fgColorFlag) {
fmt.Printf("Error: %s is not a valid foreground color.\n\n", fgColorFlag)
flag.Usage()
return
}
input, err := getInput(args)
if err != nil {
log.Fatal(err)
}
fileContent, err := getFileContent(input)
if err != nil {
log.Fatal(err)
}
regex, err := regexp.Compile(getRegexPattern(searchTerm, insensitive))
if err != nil {
log.Fatal(err)
}
scanner := bufio.NewScanner(strings.NewReader(fileContent))
counter_total := up + down + 1
counter_tmp := counter_total
var chunk_lines []t_chunk_line
var is_printed bool
match_found := false
for scanner.Scan() {
line := scanner.Text()
match := regex.FindString(line)
if (len(match)>0)&&(counter_tmp >= 0) {
match_found = true
var line_highlighted string
if useBox{
line_highlighted = highlightMatchColorBox(line, match, bgColorFlag, fgColorFlag)
} else {
line_highlighted = strings.Replace(line, match, highlightMatchColor(match, bgColorFlag, fgColorFlag), -1)
}
chunk_lines = append(chunk_lines, t_chunk_line{true, line_highlighted})
counter_tmp = counter_total
} else if match_found{
chunk_lines = append(chunk_lines, t_chunk_line{false, line})
}
if (counter_tmp == 0) {
chunk_lines, is_printed = print_chunk(chunk_lines, up, down)
if (is_printed && ((up>0) || (down>0))) {
rgbFg := getColorCode("green")
highlighted := fmt.Sprintf("\x1b[38;2;%d;%d;%dm%s\x1b[0m", rgbFg.R, rgbFg.G, rgbFg.B, "------------------------------------------------------------")
fmt.Println(highlighted)
}
counter_tmp = counter_total
}
counter_tmp = counter_tmp - 1
}
if len(chunk_lines) >= up {
chunk_lines, _ = print_chunk(chunk_lines, up, down)
}
if !match_found{
fmt.Println("No matches found")
}
}
type t_chunk_line struct {
isMatch bool
line string
}
func print_chunk(chunk []t_chunk_line, up int, down int) ([]t_chunk_line, bool) {
is_printed := false
if len(chunk) > 0 {
if (up == 0)&&(down == 0) {
for _, item := range chunk {
fmt.Println(item.line)
}
is_printed = true
} else {
index_first_match := -1
for j:=0; j<len(chunk); j++ {
item := chunk[j]
if(item.isMatch) {
index_first_match = j
break
}
}
index_last_match := -1
for j:=len(chunk)-1; j>=0; j-- {
item := chunk[j]
if(item.isMatch) {
index_last_match = j
break
}
}
if (index_first_match >= 0)&&(index_last_match >= 0) {
var index int
var max int
if (index_first_match - up) < 0 {
index = 0
} else {
index = index_first_match - up
}
max = index_last_match + down + 1
if max > len(chunk) {
max = len(chunk)
}
for j:=index; j<max; j++ {
fmt.Println(chunk[j].line)
}
is_printed = true
}
}
// Remove all items in chunk
return chunk[(len(chunk)-up):], is_printed
} else {
return chunk, is_printed
}
}
//Colors Code//
type RGB struct {
R int
G int
B int
}
func getColorCode(colorOption string) RGB {
// Return the color code corresponding to the background color option
switch colorOption {
case "red":
return RGB{255, 0, 0}
case "green":
return RGB{0, 255, 0}
case "yellow":
return RGB{255, 255, 0}
case "blue":
return RGB{0, 0, 255}
case "magenta":
return RGB{255, 0, 255}
case "cyan":
return RGB{0, 255, 255}
case "white":
return RGB{255, 255, 255}
case "black":
return RGB{0, 0, 0}
case "pink":
return RGB{255, 20, 147}
default:
return RGB{255, 0, 255} // magenta // default for no box mode
}
}
func highlightMatchColor(match, bgColor, fgColor string) string {
var highlighted string
rgbBg := getColorCode(bgColor)
if fgColor == "" {
fgColor = "white"
}
rgbFg := getColorCode(fgColor)
highlighted = fmt.Sprintf("\x1b[48;2;%d;%d;%dm\x1b[38;2;%d;%d;%dm\033[1m%s\x1b[0m", rgbBg.R, rgbBg.G, rgbBg.B, rgbFg.R, rgbFg.G, rgbFg.B, match)
return highlighted
}
func highlightMatchColorBox(line string, match string, bgColor string, fgColor string) string {
prev_lines := line[:strings.Index(line, match)]
post_lines := line[strings.Index(line, match)+len(match):]
// count the length of the line before the match
lineLenBeforeMatch := len(prev_lines)
padding := strings.Repeat(" ", lineLenBeforeMatch)
// Use red color if bgColor is empty
if bgColor == "" {
bgColor = "red"
}
if fgColor == "" {
fgColor = "white"
}
rgbBg := getColorCode(bgColor)
rgbFg := getColorCode(fgColor)
var highlighted strings.Builder
highlighted.WriteString(fmt.Sprintf("%s\033[38;2;%d;%d;%dm┏%s┓\033[0m\n", padding, rgbBg.R, rgbBg.G, rgbBg.B, strings.Repeat("━", len(match))))
highlighted.WriteString(fmt.Sprintf("%s\033[38;2;%d;%d;%dm┃\033[38;2;%d;%d;%dm%s\033[38;2;%d;%d;%dm┃\033[0m%s\n",
prev_lines, rgbBg.R, rgbBg.G, rgbBg.B,
rgbFg.R, rgbFg.G, rgbFg.B, match,
rgbBg.R, rgbBg.G, rgbBg.B, post_lines))
highlighted.WriteString(fmt.Sprintf("%s\033[38;2;%d;%d;%dm┗%s┛\033[0m", padding, rgbBg.R, rgbBg.G, rgbBg.B, strings.Repeat("━", len(match))))
return highlighted.String()
}
func contains(colors []string, color string) bool {
for _, c := range colors {
if strings.ToLower(c) == strings.ToLower(color) || color == "" {
return true
}
}
return false
}
//*Colors Code*//
func getInput(args []string) (string, error) {
if len(args) == 2 {
return args[1], nil
} else if !isPipe() {
return "", fmt.Errorf("No input specified")
} else {
return readPipe(), nil
}
}
func getRegexPattern(searchTerm string, insensitive bool) string {
if insensitive {
return "(?i)" + searchTerm
} else {
return searchTerm
}
}
func isPipe() bool {
stat, _ := os.Stdin.Stat()
return (stat.Mode() & os.ModeCharDevice) == 0
}
func readPipe() string {
var sb strings.Builder
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
sb.WriteString(scanner.Text())
sb.WriteString("\n")
}
return sb.String()
}
func getFileContent(input string) (string, error) {
if input == "" {
return "", fmt.Errorf("No file specified")
}
stat, err := os.Stat(input)
if err == nil && !stat.IsDir() {
bytes, err := ioutil.ReadFile(input)
if err == nil {
return string(bytes), nil
}
}
return input, nil
}