Ejemplo n.º 1
0
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)
	}
}
Ejemplo n.º 2
0
func searchPattern(idx *index.Index, pattern string, options *SearchOptions, w flushWriter) ([]*SearchResult, error) {
	var results []*SearchResult
	var stdout, stderr bytes.Buffer
	bStdout := bufio.NewWriter(&stdout)
	bStderr := bufio.NewWriter(&stderr)

	grep := regexp.Grep{
		Stdout: bStdout,
		Stderr: bStderr,
		N:      true,
	}

	// grep.AddFlags()
	re, err := regexp.Compile(pattern)
	if err != nil {
		return nil, err
	}
	grep.Regexp = re
	q := index.RegexpQuery(re.Syntax)
	var post []uint32
	post = idx.PostingQuery(q)

	w.Write([]byte("\"results\": [\n"))

	// This is needed to check whether we need to print a "," to respect JSON
	// syntax
	isFirst := true

	for _, fileid := range post {
		name := idx.Name(fileid)
		grep.File(name)
		bStdout.Flush()
		bStderr.Flush()

		for {
			line, err := stdout.ReadString('\n')
			if err == io.EOF {
				break
			} else if err != nil {
				log.Printf("Error from ReadString: %s", err.Error())
				return nil, err
			}
			// log.Printf("LINE: %s", line)

			fields := strings.SplitN(line, ":", 3)
			ln, err := strconv.ParseUint(fields[1], 10, 64)
			if err != nil {
				log.Printf("Error converting line number: %s", err.Error())
				return nil, err
			}
			sr := &SearchResult{
				Filename: fields[0],
				Line:     ln,
				Match:    html.EscapeString(fields[2]),
			}
			results = append(results, sr)
			jr, err := json.Marshal(sr)
			if err != nil {
				log.Printf("JSON error: %s", err.Error())
				return nil, err
			}
			if !isFirst {
				w.Write([]byte(",\n"))
			} else {
				isFirst = false
			}
			w.Write(jr)
		}
	}

	w.Write([]byte("]\n"))

	return results, nil
}