forked from tomnomnom/gf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
208 lines (168 loc) · 4.22 KB
/
main.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
package main
import (
"encoding/json"
"errors"
"flag"
"fmt"
"os"
"os/exec"
"os/user"
"path/filepath"
"strings"
)
type pattern struct {
Flags string `json:"flags,omitempty"`
Pattern string `json:"pattern,omitempty"`
Patterns []string `json:"patterns,omitempty"`
Engine string `json:"engine,omitempty"`
}
const patternDirEnvVar = "GF_PATTERN_DIR"
func main() {
var saveMode bool
flag.BoolVar(&saveMode, "save", false, "save a pattern (e.g: gf -save pat-name -Hnri 'search-pattern')")
var listMode bool
flag.BoolVar(&listMode, "list", false, "list available patterns")
var dumpMode bool
flag.BoolVar(&dumpMode, "dump", false, "prints the grep command rather than executing it")
var customPatternDir string
flag.StringVar(&customPatternDir, "pattern-dir", "", "specify custom pattern directory")
flag.Parse()
if listMode {
pats, err := getPatterns(customPatternDir)
if err != nil {
fmt.Fprintf(os.Stderr, "%s\n", err)
return
}
fmt.Println(strings.Join(pats, "\n"))
return
}
if saveMode {
name := flag.Arg(0)
flags := flag.Arg(1)
pattern := flag.Arg(2)
err := savePattern(name, flags, pattern, customPatternDir)
if err != nil {
fmt.Fprintf(os.Stderr, "%s\n", err)
}
return
}
patName := flag.Arg(0)
files := flag.Arg(1)
if files == "" {
files = "."
}
patDir, err := getPatternDir(customPatternDir)
if err != nil {
fmt.Fprintln(os.Stderr, "unable to open user's pattern directory")
return
}
filename := filepath.Join(patDir, patName+".json")
f, err := os.Open(filename)
if err != nil {
fmt.Fprintln(os.Stderr, "no such pattern")
return
}
defer f.Close()
pat := pattern{}
dec := json.NewDecoder(f)
err = dec.Decode(&pat)
if err != nil {
fmt.Fprintf(os.Stderr, "pattern file '%s' is malformed: %s\n", filename, err)
return
}
if pat.Pattern == "" {
// check for multiple patterns
if len(pat.Patterns) == 0 {
fmt.Fprintf(os.Stderr, "pattern file '%s' contains no pattern(s)\n", filename)
return
}
pat.Pattern = "(" + strings.Join(pat.Patterns, "|") + ")"
}
if dumpMode {
fmt.Printf("grep %v %q %v\n", pat.Flags, pat.Pattern, files)
} else {
var cmd *exec.Cmd
operator := "grep"
if pat.Engine != "" {
operator = pat.Engine
}
if stdinIsPipe() {
cmd = exec.Command(operator, pat.Flags, pat.Pattern)
} else {
cmd = exec.Command(operator, pat.Flags, pat.Pattern, files)
}
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Run()
}
}
func getPatternDir(customPatternDir string) (string, error) {
if customPatternDir != "" {
return customPatternDir, nil
}
envPatternDir := os.Getenv(patternDirEnvVar)
if envPatternDir != "" {
return envPatternDir, nil
}
usr, err := user.Current()
if err != nil {
return "", err
}
path := filepath.Join(usr.HomeDir, ".config/gf")
if _, err := os.Stat(path); !os.IsNotExist(err) {
// .config/gf exists
return path, nil
}
return filepath.Join(usr.HomeDir, ".gf"), nil
}
func savePattern(name, flags, pat, customPatternDir string) error {
if name == "" {
return errors.New("name cannot be empty")
}
if pat == "" {
return errors.New("pattern cannot be empty")
}
p := &pattern{
Flags: flags,
Pattern: pat,
}
patDir, err := getPatternDir(customPatternDir)
if err != nil {
return fmt.Errorf("failed to determine pattern directory: %s", err)
}
path := filepath.Join(patDir, name+".json")
f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0666)
if err != nil {
return fmt.Errorf("failed to create pattern file: %s", err)
}
defer f.Close()
enc := json.NewEncoder(f)
enc.SetIndent("", " ")
err = enc.Encode(p)
if err != nil {
return fmt.Errorf("failed to write pattern file: %s", err)
}
return nil
}
func getPatterns(customPatternDir string) ([]string, error) {
out := []string{}
patDir, err := getPatternDir(customPatternDir)
if err != nil {
return out, fmt.Errorf("failed to determine pattern directory: %s", err)
}
_ = patDir
files, err := filepath.Glob(patDir + "/*.json")
if err != nil {
return out, err
}
for _, f := range files {
f = f[len(patDir)+1 : len(f)-5]
out = append(out, f)
}
return out, nil
}
func stdinIsPipe() bool {
stat, _ := os.Stdin.Stat()
return (stat.Mode() & os.ModeCharDevice) == 0
}