-
Notifications
You must be signed in to change notification settings - Fork 0
/
grop.go
73 lines (63 loc) · 1.21 KB
/
grop.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
package grop
import (
"bufio"
"io"
"os"
"regexp"
)
type Options struct {
IgnoreCase bool
WhenHighlight string // TODO: Use enum
isStdout bool // Needed to determine if colors should print
}
func Search(w io.Writer, r io.Reader, term string, o Options) error {
if term == "" {
return nil
}
m := "(?)" + term
if o.IgnoreCase {
m = "(?i)" + term
}
reg, err := regexp.Compile(m)
if err != nil {
return err
}
sc := bufio.NewScanner(r)
for sc.Scan() {
line := sc.Text()
matches := reg.FindAllString(line, -1)
if matches == nil {
continue
}
// Handle color option
res := colorize(line, matches, o.WhenHighlight, o.isStdout)
_, err := io.WriteString(w, res+"\n")
if err != nil {
return err
}
}
return nil
}
func Run(args []string, w io.Writer, r io.Reader, opts Options) error {
term := args[0]
if len(args) == 1 {
// Use stdin
err := Search(os.Stdout, os.Stdin, term, opts)
if err != nil {
return err
}
return nil
}
// More than one arg, assume last arg is path to file
fp := args[len(args)-1]
file, err := os.Open(fp)
if err != nil {
return err
}
defer file.Close()
err = Search(os.Stdout, file, term, opts)
if err != nil {
return err
}
return nil
}