-
Notifications
You must be signed in to change notification settings - Fork 14
/
file_extractor.go
79 lines (68 loc) · 1.5 KB
/
file_extractor.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
79
package fileextractor
import (
"io/ioutil"
"log"
"os"
"path/filepath"
"regexp"
"strings"
)
type FileExtractor struct {
Founds []string
}
type ExtractParams struct {
SearchPath string
Excludes []string
Expression string
}
func (l *FileExtractor) Extract(params ExtractParams) ([]string, error) {
err := filepath.Walk(params.SearchPath,
func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if strings.HasSuffix(path, ".go") &&
!strings.HasSuffix(path, "_test.go") &&
!strings.HasSuffix(path, "_gen.go") &&
!strings.HasSuffix(path, "generated.go") {
l.ExtractFromFile(path, params.Expression)
}
return err
})
if err != nil {
return nil, err
}
return l.Founds, err
}
func (l *FileExtractor) ExtractFromFile(pathToread string, expression string) {
fileContent, err := l.readFile(pathToread)
if err != nil {
log.Fatal(err)
}
reg := *regexp.MustCompile(expression)
res := reg.FindAllStringSubmatch(fileContent, -1)
foundsMap := map[string]string{}
for i := range res {
foundsMap[res[i][1]] = ""
}
for key := range foundsMap {
l.Founds = append(l.Founds, key)
}
}
func (l *FileExtractor) readFile(pathToread string) (string, error) {
file, err := os.Open(pathToread)
if err != nil {
log.Fatal(err)
return "", err
}
defer file.Close()
srcbuf, err := ioutil.ReadAll(file)
if err != nil {
log.Fatal(err)
return "", err
}
return string(srcbuf), nil
}
func NewFileExtractor() *FileExtractor {
return &FileExtractor{}
}