/
walk.go
115 lines (108 loc) · 2.68 KB
/
walk.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package utils
import (
"fmt"
"os"
"path/filepath"
"strings"
)
// files that must be ignored
var blacklist = map[string]bool{
".git": true,
"android": true,
"deploy": true,
"ios": true,
"ios-simulator": true,
"node_modules": true,
"qml": true,
"rpi1": true,
"rpi2": true,
"rpi3": true,
"sailfish": true,
"sailfish-emulator": true,
"vendor": true,
}
// WalkFilterBlacklist filter out blacklisted file
func WalkFilterBlacklist(root string, f filepath.WalkFunc) filepath.WalkFunc {
return func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
relPath, relErr := filepath.Rel(root, path)
if relErr != nil {
return relErr
}
if blacklist[relPath] {
// as the directory is blacklisted, just ignore everything under it
if info.IsDir() {
return filepath.SkipDir
}
return nil
}
return f(path, info, err)
}
}
// WalkFilterDirectory only allow directory
func WalkOnlyDirectory(f filepath.WalkFunc) filepath.WalkFunc {
return func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
return f(path, info, err)
}
return nil
}
}
// WalkOnlyFile is opposite of WalkFilterDirectory, it only allow file
func WalkOnlyFile(f filepath.WalkFunc) filepath.WalkFunc {
return func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() {
return f(path, info, err)
}
return nil
}
}
// WalkFilterPrefix only process file that do not have specified prefix
func WalkFilterPrefix(f filepath.WalkFunc, prefixes ...string) filepath.WalkFunc {
return func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
name := info.Name()
for index := range prefixes {
if strings.HasPrefix(name, prefixes[index]) {
if info.IsDir() {
return filepath.SkipDir
}
return nil
}
}
return f(path, info, err)
}
}
// WalkOnlyExtension only process file (not directory) that their extension is
// specified, without the `.` such as `go` or `html`.
func WalkOnlyExtension(f filepath.WalkFunc, extensions ...string) filepath.WalkFunc {
compiled := make([]string, len(extensions))
for index := range extensions {
compiled[index] = fmt.Sprintf(".%s", extensions[index])
}
return func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
return f(path, info, err)
}
extension := filepath.Ext(info.Name())
for index := range compiled {
if extension == compiled[index] {
return f(path, info, err)
}
}
return nil
}
}