fix search paths for root+

This commit is contained in:
Bel LaPointe
2019-12-17 16:14:32 -07:00
parent 4a7efd4016
commit a7df97aae5
3 changed files with 53 additions and 6 deletions

View File

@@ -2,16 +2,52 @@ package notes
import (
"bufio"
"errors"
"local/notes-server/filetree"
"log"
"os"
"path"
"path/filepath"
"regexp"
"strings"
)
type searcher struct {
patterns []*regexp.Regexp
}
func newSearcher(phrase string) (*searcher, error) {
phrases := strings.Split(phrase, " ")
patterns := make([]*regexp.Regexp, 0)
for _, phrase := range phrases {
if len(phrase) == 0 {
continue
}
pattern, err := regexp.Compile("(?i)" + phrase)
if err != nil {
return nil, err
}
patterns = append(patterns, pattern)
}
if len(patterns) < 1 {
return nil, errors.New("no search specified")
}
return &searcher{
patterns: patterns,
}, nil
}
func (s *searcher) matches(input []byte) bool {
for _, pattern := range s.patterns {
if !pattern.Match(input) {
return false
}
}
return true
}
func (n *Notes) Search(phrase string) (string, error) {
pattern, err := regexp.Compile("(?i)" + phrase)
searcher, err := newSearcher(phrase)
if err != nil {
return "", err
}
@@ -27,7 +63,7 @@ func (n *Notes) Search(phrase string) (string, error) {
if size := info.Size(); size < 1 || size > (5*1024*1024) {
return nil
}
ok, err := grepFile(walked, pattern)
ok, err := grepFile(walked, searcher)
if err != nil && err.Error() == "bufio.Scanner: token too long" {
err = nil
}
@@ -44,7 +80,7 @@ func (n *Notes) Search(phrase string) (string, error) {
return filetree.Paths(*files).List(true), err
}
func grepFile(file string, pattern *regexp.Regexp) (bool, error) {
func grepFile(file string, searcher *searcher) (bool, error) {
f, err := os.Open(file)
if err != nil {
return false, err
@@ -52,7 +88,7 @@ func grepFile(file string, pattern *regexp.Regexp) (bool, error) {
defer f.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
if pattern.Match(scanner.Bytes()) {
if searcher.matches(scanner.Bytes()) {
return true, scanner.Err()
}
}