-
Notifications
You must be signed in to change notification settings - Fork 2
/
git_search.go
74 lines (69 loc) · 1.64 KB
/
git_search.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
package main
import (
"bufio"
"bytes"
"errors"
"io/fs"
"os"
"path/filepath"
"strings"
)
func (g *GitBackend) SearchWiki(pattern string) []SearchResult {
trimPrefix := filepath.Clean(g.dir) + string(filepath.Separator)
patternBytes := bytes.ToLower([]byte(pattern))
results := searchDirectory(g.dir, patternBytes)
var output []SearchResult
for index := range results {
output = append(output, SearchResult{
Filename: strings.TrimSuffix(strings.TrimPrefix(results[index].Filename, trimPrefix), ".md"),
FoundLines: results[index].FoundLines,
})
}
return output
}
type SearchResult struct {
Filename string
FoundLines []string
}
func searchDirectory(path string, pattern []byte) []SearchResult {
results := make([]SearchResult, 0)
_ = filepath.WalkDir(path, func(path string, d fs.DirEntry, err error) error {
if d.IsDir() ||
strings.HasPrefix(path, ".git") ||
strings.HasPrefix(path, ".wiki") ||
!strings.HasSuffix(path, ".md") {
return nil
}
result, err := searchFile(path, pattern)
if err == nil {
results = append(results, result)
}
return nil
})
return results
}
func searchFile(file string, pattern []byte) (SearchResult, error) {
f, err := os.Open(file)
if err != nil {
return SearchResult{}, err
}
defer func() {
_ = f.Close()
}()
result := SearchResult{
Filename: file,
FoundLines: nil,
}
found := false
scanner := bufio.NewScanner(f)
for scanner.Scan() {
if bytes.Contains(bytes.ToLower(scanner.Bytes()), pattern) {
found = true
result.FoundLines = append(result.FoundLines, scanner.Text())
}
}
if found {
return result, nil
}
return SearchResult{}, errors.New("no result")
}