-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmatcher.go
113 lines (100 loc) · 2.48 KB
/
matcher.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
package xignore
import (
"os"
"sort"
"github.com/spf13/afero"
)
// Matcher xignore matcher
type Matcher struct {
fs afero.Fs
}
// NewMatcher create matcher from custom filesystem
func NewMatcher(fs afero.Fs) *Matcher {
return &Matcher{afero.NewReadOnlyFs(fs)}
}
// NewSystemMatcher create matcher for system filesystem
func NewSystemMatcher() *Matcher {
return &Matcher{afero.NewReadOnlyFs(afero.NewOsFs())}
}
// Matches returns matched files from dir files, basedir not support relative path, eg './foo/bar'.
func (m *Matcher) Matches(basedir string, options *MatchesOptions) (*MatchesResult, error) {
vfs := afero.NewBasePathFs(m.fs, basedir)
ignorefile := options.Ignorefile
if ok, err := afero.DirExists(vfs, "/"); !ok || err != nil {
if err == nil {
return nil, os.ErrNotExist
}
return nil, err
}
// Root filemap
rootMap := stateMap{}
files, err := collectFiles(vfs)
if err != nil {
return nil, err
}
// Init all files state
rootMap.mergeFiles(files, false)
// Apply before patterns
beforePatterns, err := makePatterns(options.BeforePatterns)
if err != nil {
return nil, err
}
err = rootMap.applyPatterns(vfs, files, beforePatterns)
if err != nil {
return nil, err
}
// Apply ignorefile patterns
err = rootMap.applyIgnorefile(vfs, ignorefile, options.Nested)
if err != nil {
return nil, err
}
// Apply after patterns
afterPatterns, err := makePatterns(options.AfterPatterns)
if err != nil {
return nil, err
}
err = rootMap.applyPatterns(vfs, files, afterPatterns)
if err != nil {
return nil, err
}
return makeResult(vfs, basedir, rootMap)
}
func makeResult(vfs afero.Fs, basedir string, fileMap stateMap) (*MatchesResult, error) {
matchedFiles := []string{}
unmatchedFiles := []string{}
matchedDirs := []string{}
unmatchedDirs := []string{}
for f, matched := range fileMap {
if f == "" {
continue
}
isDir, err := afero.IsDir(vfs, f)
if err != nil {
return nil, err
}
if isDir {
if matched {
matchedDirs = append(matchedDirs, f)
} else {
unmatchedDirs = append(unmatchedDirs, f)
}
} else {
if matched {
matchedFiles = append(matchedFiles, f)
} else {
unmatchedFiles = append(unmatchedFiles, f)
}
}
}
sort.Strings(matchedFiles)
sort.Strings(unmatchedFiles)
sort.Strings(matchedDirs)
sort.Strings(unmatchedDirs)
return &MatchesResult{
BaseDir: basedir,
MatchedFiles: matchedFiles,
UnmatchedFiles: unmatchedFiles,
MatchedDirs: matchedDirs,
UnmatchedDirs: unmatchedDirs,
}, nil
}