-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathfile.go
78 lines (64 loc) · 1.36 KB
/
file.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
package qry
import (
"bytes"
"io"
"os"
"path/filepath"
)
// File represents parsed file with .sql queries
type File struct {
Name string
Items []FileItem
}
// FileItem represents single query within a file
type FileItem struct {
Name string
Query Query
}
func readFiles(dir string) (out []File, err error) {
var (
buf = bytes.NewBuffer(nil)
one FileItem
)
err = filepath.Walk(dir, func(path string, finfo os.FileInfo, err error) error {
if finfo.IsDir() || filepath.Ext(finfo.Name()) != ext {
return nil
}
var f *os.File
if f, err = os.Open(filepath.Clean(path)); err != nil {
return err
}
// write file contents to buffer
buf.Reset()
buf.WriteString("\n")
io.Copy(buf, f)
f.Close()
if buf.Len() == 0 {
return nil
}
// look for queries
var (
raw = buf.Bytes()
str = rgxSearchQueries.FindAllSubmatch(raw, -1)
idx = rgxSearchQueries.FindAllSubmatchIndex(raw, -1)
fl = File{
Name: finfo.Name(),
Items: make([]FileItem, 0, len(str)),
}
)
// Capture all from current header until next header (or EOF)
for i := range idx {
one.Name = string(str[i][1])
if len(idx) > i+1 {
one.Query = normalize(raw[idx[i][1]:idx[i+1][0]])
} else {
one.Query = normalize(raw[idx[i][1]:])
}
fl.Items = append(fl.Items, one)
one = FileItem{}
}
out = append(out, fl)
return nil
})
return
}