-
Notifications
You must be signed in to change notification settings - Fork 240
/
helpers.go
89 lines (76 loc) · 1.92 KB
/
helpers.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
80
81
82
83
84
85
86
87
88
89
package scanner
import (
"bufio"
"os"
"path/filepath"
"regexp"
"strings"
"github.com/samber/lo"
)
func absFileExists(filenames ...string) bool {
for _, filename := range filenames {
info, err := os.Stat(filename)
if err != nil {
continue
}
if !info.IsDir() {
return true
}
}
return false
}
func fileExists(filenames ...string) checkFn {
return func(dir string) bool {
return absFileExists(lo.Map(filenames, func(filename string, _ int) string {
return filepath.Join(dir, filename)
})...)
}
}
func fileContains(path string, pattern string) bool {
file, err := os.Open(path)
if err != nil {
return false
}
defer file.Close() //skipcq: GO-S2307
scanner := bufio.NewScanner(file)
// Unicode is a complex subject, but if we assume that the pattern is only
// looking for strings expressible in ASCII, a lot of simplifications can
// be made. Most encodings express strings containing only valid ASCII
// characters the same. The only encodings that matter that don't are
// UTF-16, which will add null bytes, either before or after each
// character. Since UTF-16 is rare except on Windows, we do a scan to see
// if we need to allocate a new string.
re := regexp.MustCompile(pattern)
for scanner.Scan() {
text := scanner.Text()
if strings.Contains(text, "\u0000") {
text = strings.ReplaceAll(text, "\u0000", "")
}
if re.MatchString(text) {
return true
}
}
return false
}
func dirContains(glob string, patterns ...string) checkFn {
return func(dir string) bool {
for _, pattern := range patterns {
filenames, _ := filepath.Glob(filepath.Join(dir, glob))
for _, filename := range filenames {
if fileContains(filename, pattern) {
return true
}
}
}
return false
}
}
type checkFn func(dir string) bool
func checksPass(sourceDir string, checks ...checkFn) bool {
for _, check := range checks {
if check(sourceDir) {
return true
}
}
return false
}