-
Notifications
You must be signed in to change notification settings - Fork 14
/
file_walker.go
61 lines (57 loc) · 1.36 KB
/
file_walker.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
package main
import (
"fmt"
"os"
"path/filepath"
"regexp"
"strings"
gitignore "github.com/iriri/minimal/gitignore"
)
// WalkMatchOptions match options for WalkMatch
type WalkMatchOptions struct {
ignores []string
patterns []string
unrestricted bool
}
// WalkMatch walk and match files, default match files not gitignored, can be customized by options
func WalkMatch(root string, options WalkMatchOptions) ([]string, error) {
var matches []string
ignores := options.ignores
from, ignoreListErr := gitignore.From(fmt.Sprintf("%s/.gitignore", root))
if options.unrestricted {
from, ignoreListErr = gitignore.New()
}
reg := regexp.MustCompile(strings.Join(ignores, "|"))
err := from.Walk(root, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
return nil
}
if len(options.ignores) > 0 && len(reg.FindStringSubmatch(path)) > 0 {
return nil
}
if !options.unrestricted && ignoreListErr == nil {
if from.Match(path) {
if info.IsDir() {
return filepath.SkipDir
}
return nil
}
}
for _, pattern := range options.patterns {
if matched, err := filepath.Match(pattern, filepath.Base(path)); err != nil {
return err
} else if matched {
matches = append(matches, path)
break
}
}
return nil
})
if err != nil {
return nil, err
}
return matches, nil
}