-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
262 lines (235 loc) · 5.81 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
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
package main
import (
"fmt"
"html/template"
"io"
"os"
"runtime"
"runtime/debug"
"strings"
"unicode"
"github.com/dmgk/getopt"
"github.com/dmgk/portgrep/formatter"
"github.com/dmgk/portgrep/grep"
"github.com/mattn/go-isatty"
)
var usageTmpl = template.Must(template.New("usage").Parse(`
usage: {{.progname}} [options] [query ...]
General options:
-h show help and exit
-V show version and exit
-R path ports tree root (default: {{.portsRoot}})
-M mode colorized output mode: [auto|never|always] (default: {{.colorMode}})
-G colors set colors (default: "{{.colors}}")
the order is query,match,path,separator; see ls(1) for color codes
Search options:
-c name,... limit search to only these categories
-O multiple searches are OR-ed (default: AND-ed)
-F interpret query as a plain text, not regular expression
-j jobs number of parallel jobs (default: {{.maxJobs}})
Formatting options:
-1 output origins in a single line (implies -o)
-A count show count lines of context after match
-B count show count lines of context before match
-C count show count lines of context around match
-o output origins only
-s sort results by origin
-T do not indent results
Predefined searches:{{range .patterns}}
{{.Description}}{{end}}
`[1:]))
var (
progname string
version = "devel"
portsRoot = "/usr/ports"
colorMode = "auto"
colors = formatter.DefaultColors
categories []string
ored bool
plainText bool
maxJobs = runtime.NumCPU()
originsSingleLine bool
contextAfter int
contextBefore int
originsOnly bool
noIndent bool
)
const (
colorModeAuto = "auto"
colorModeAlways = "always"
colorModeNever = "never"
)
func showUsage() {
err := usageTmpl.Execute(os.Stdout, map[string]interface{}{
"progname": progname,
"colorMode": colorMode,
"colors": colors,
"maxJobs": maxJobs,
"patterns": grep.Patterns,
})
if err != nil {
panic(fmt.Sprintf("error executing template %s: %v", usageTmpl.Name(), err))
}
}
func showVersion() {
fmt.Printf("%s %s\n", progname, version)
}
func errExit(format string, v ...interface{}) {
fmt.Fprint(os.Stderr, progname, ": ")
fmt.Fprintf(os.Stderr, format, v...)
fmt.Fprintln(os.Stderr)
os.Exit(1)
}
func main() {
// disable GC, this is short-running utility and performance is more
// important than memory consumption
debug.SetGCPercent(-1)
if v, ok := os.LookupEnv("PORTSDIR"); ok && v != "" {
portsRoot = v
}
if v, ok := os.LookupEnv("PORTGREP_COLORS"); ok && v != "" {
colors = v
}
opts, err := getopt.NewArgv("hVR:M:G:c:OFj:1A:B:C:osT"+grep.Patterns.OptionString(), argsWithDefaults(os.Args, "PORTGREP_OPTS"))
if err != nil {
panic(fmt.Sprintf("error creating options parser: %s", err))
}
progname = opts.ProgramName()
var pts []grep.Pattern
for opts.Scan() {
opt, err := opts.Option()
if err != nil {
errExit(err.Error())
}
switch opt.Opt {
case 'h':
showUsage()
os.Exit(0)
case 'V':
showVersion()
os.Exit(0)
case 'R':
portsRoot = opt.String()
case 'M':
switch opt.String() {
case colorModeAuto, colorModeNever, colorModeAlways:
colorMode = opt.String()
default:
errExit("-M: invalid color mode: %s", opt.String())
}
case 'G':
colors = opt.String()
case 'c':
categories = splitOptions(opt.String())
case 'O':
ored = true
case 'F':
plainText = true
case 'j':
v, err := opt.Int()
if err != nil {
errExit("-j: %s", err.Error())
}
if v <= 0 {
v = 1
}
maxJobs = v
case '1':
originsSingleLine = true
case 'A':
v, err := opt.Int()
if err != nil {
errExit("-A: %s", err)
}
contextAfter = v
case 'B':
v, err := opt.Int()
if err != nil {
errExit("-B: %s", err)
}
contextBefore = v
case 'C':
v, err := opt.Int()
if err != nil {
errExit("-C: %s", err)
}
contextBefore = v
contextAfter = v
case 'o':
originsOnly = true
case 's':
maxJobs = 1
case 'T':
noIndent = true
default:
p := grep.Patterns.Get(opt.Opt, opt.String())
if p == nil {
panic("unhandled option: -" + string(opt.Opt))
}
pts = append(pts, p)
}
}
var rxs []*grep.Regexp
for _, p := range pts {
rx, err := p.Compile(contextBefore, contextAfter, plainText)
if err != nil {
errExit("-%c: %s", p.Option(), err)
}
rxs = append(rxs, rx)
}
for _, q := range opts.Args() {
rx, err := grep.Compile(q, contextBefore, contextAfter, plainText)
if err != nil {
errExit("query %q: %s", q, err)
}
rxs = append(rxs, rx)
}
if len(rxs) == 0 {
showUsage()
os.Exit(0)
}
f := initFormatter()
gfn := func(path string, results grep.Results, err error) error {
if err != nil {
return err
}
return f.Format(path, results)
}
if err := grep.Grep(portsRoot, categories, rxs, ored, gfn, maxJobs); err != nil {
errExit(err.Error())
}
}
func initFormatter() formatter.Formatter {
var w io.Writer = os.Stdout
flags := formatter.Fdefaults
term := isatty.IsTerminal(os.Stdout.Fd())
if colorMode == colorModeAlways || (term && colorMode == colorModeAuto) {
flags |= formatter.Fcolor
if colors != "" {
formatter.SetColors(colors)
}
}
if originsSingleLine {
flags |= formatter.ForiginsSingleLine
}
if originsOnly {
flags |= formatter.ForiginsOnly
}
f := formatter.NewText(w, portsRoot, flags)
if !noIndent {
f.SetIndent("\t")
}
return f
}
func argsWithDefaults(argv []string, env string) []string {
args := argv[1:]
if v, ok := os.LookupEnv(env); ok && v != "" {
args = append(splitOptions(v), args...)
}
return append([]string{argv[0]}, args...)
}
func splitOptions(s string) []string {
return strings.FieldsFunc(s, func(r rune) bool {
return unicode.IsSpace(r) || r == ','
})
}