forked from google/codesearch
/
cgrep.go
77 lines (66 loc) · 1.48 KB
/
cgrep.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
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"flag"
"fmt"
"log"
"os"
"runtime/pprof"
"github.com/google/codesearch/regexp"
)
var usageMessage = `usage: cgrep [-c] [-h] [-i] [-l] [-n] regexp [file...]
Cgrep behaves like grep, searching for regexp, an RE2 (nearly PCRE) regular expression.
The -c, -h, -i, -l, and -n flags are as in grep, although note that as per Go's
flag parsing convention, they cannot be combined: the option pair -i -n
cannot be abbreviated to -in.
`
func usage() {
fmt.Fprintf(os.Stderr, usageMessage)
os.Exit(2)
}
var (
iflag = flag.Bool("i", false, "case-insensitive match")
cpuProfile = flag.String("cpuprofile", "", "write cpu profile to this file")
)
func main() {
var g regexp.Grep
g.AddFlags()
g.Stdout = os.Stdout
g.Stderr = os.Stderr
flag.Usage = usage
flag.Parse()
args := flag.Args()
if len(args) == 0 {
flag.Usage()
}
if *cpuProfile != "" {
f, err := os.Create(*cpuProfile)
if err != nil {
log.Fatal(err)
}
defer f.Close()
pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile()
}
pat := "(?m)" + args[0]
if *iflag {
pat = "(?i)" + pat
}
re, err := regexp.Compile(pat)
if err != nil {
log.Fatal(err)
}
g.Regexp = re
if len(args) == 1 {
g.Reader(os.Stdin, "<standard input>")
} else {
for _, arg := range args[1:] {
g.File(arg)
}
}
if !g.Match {
os.Exit(1)
}
}