forked from tonistiigi/fsutil
-
Notifications
You must be signed in to change notification settings - Fork 0
/
walker.go
357 lines (313 loc) · 8.54 KB
/
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
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
package fsutil
import (
"context"
"os"
"path/filepath"
"strings"
"syscall"
"time"
"github.com/moby/patternmatcher"
"github.com/pkg/errors"
"github.com/tonistiigi/fsutil/types"
)
type WalkOpt struct {
IncludePatterns []string
ExcludePatterns []string
// FollowPaths contains symlinks that are resolved into include patterns
// before performing the fs walk
FollowPaths []string
Map MapFunc
}
type MapFunc func(string, *types.Stat) MapResult
// The result of the walk function controls
// both how WalkDir continues and whether the path is kept.
type MapResult int
const (
// Keep the current path and continue.
MapResultKeep MapResult = iota
// Exclude the current path and continue.
MapResultExclude
// Exclude the current path, and skip the rest of the dir.
// If path is a dir, skip the current directory.
// If path is a file, skip the rest of the parent directory.
// (This matches the semantics of fs.SkipDir.)
MapResultSkipDir
)
func Walk(ctx context.Context, p string, opt *WalkOpt, fn filepath.WalkFunc) error {
root, err := filepath.EvalSymlinks(p)
if err != nil {
return errors.WithStack(&os.PathError{Op: "resolve", Path: root, Err: err})
}
fi, err := os.Stat(root)
if err != nil {
return errors.WithStack(err)
}
if !fi.IsDir() {
return errors.WithStack(&os.PathError{Op: "walk", Path: root, Err: syscall.ENOTDIR})
}
var (
includePatterns []string
includeMatcher *patternmatcher.PatternMatcher
excludeMatcher *patternmatcher.PatternMatcher
)
if opt != nil && opt.IncludePatterns != nil {
includePatterns = make([]string, len(opt.IncludePatterns))
copy(includePatterns, opt.IncludePatterns)
}
if opt != nil && opt.FollowPaths != nil {
targets, err := FollowLinks(p, opt.FollowPaths)
if err != nil {
return err
}
if targets != nil {
includePatterns = append(includePatterns, targets...)
includePatterns = dedupePaths(includePatterns)
}
}
patternChars := "*[]?^"
if os.PathSeparator != '\\' {
patternChars += `\`
}
onlyPrefixIncludes := true
if len(includePatterns) != 0 {
includeMatcher, err = patternmatcher.New(includePatterns)
if err != nil {
return errors.Wrapf(err, "invalid includepatterns: %s", opt.IncludePatterns)
}
for _, p := range includeMatcher.Patterns() {
if !p.Exclusion() && strings.ContainsAny(patternWithoutTrailingGlob(p), patternChars) {
onlyPrefixIncludes = false
break
}
}
}
onlyPrefixExcludeExceptions := true
if opt != nil && opt.ExcludePatterns != nil {
excludeMatcher, err = patternmatcher.New(opt.ExcludePatterns)
if err != nil {
return errors.Wrapf(err, "invalid excludepatterns: %s", opt.ExcludePatterns)
}
for _, p := range excludeMatcher.Patterns() {
if p.Exclusion() && strings.ContainsAny(patternWithoutTrailingGlob(p), patternChars) {
onlyPrefixExcludeExceptions = false
break
}
}
}
type visitedDir struct {
fi os.FileInfo
path string
origpath string
pathWithSep string
includeMatchInfo patternmatcher.MatchInfo
excludeMatchInfo patternmatcher.MatchInfo
calledFn bool
}
// used only for include/exclude handling
var parentDirs []visitedDir
seenFiles := make(map[uint64]string)
return filepath.Walk(root, func(path string, fi os.FileInfo, walkErr error) (retErr error) {
defer func() {
if retErr != nil && isNotExist(retErr) {
retErr = filepath.SkipDir
}
}()
origpath := path
path, err = filepath.Rel(root, path)
if err != nil {
return err
}
// Skip root
if path == "." {
return nil
}
var (
dir visitedDir
isDir bool
)
if fi != nil {
isDir = fi.IsDir()
}
if includeMatcher != nil || excludeMatcher != nil {
for len(parentDirs) != 0 {
lastParentDir := parentDirs[len(parentDirs)-1].pathWithSep
if strings.HasPrefix(path, lastParentDir) {
break
}
parentDirs = parentDirs[:len(parentDirs)-1]
}
if isDir {
dir = visitedDir{
fi: fi,
path: path,
origpath: origpath,
pathWithSep: path + string(filepath.Separator),
}
}
}
skip := false
if includeMatcher != nil {
var parentIncludeMatchInfo patternmatcher.MatchInfo
if len(parentDirs) != 0 {
parentIncludeMatchInfo = parentDirs[len(parentDirs)-1].includeMatchInfo
}
m, matchInfo, err := includeMatcher.MatchesUsingParentResults(path, parentIncludeMatchInfo)
if err != nil {
return errors.Wrap(err, "failed to match includepatterns")
}
if isDir {
dir.includeMatchInfo = matchInfo
}
if !m {
if isDir && onlyPrefixIncludes {
// Optimization: we can skip walking this dir if no include
// patterns could match anything inside it.
dirSlash := path + string(filepath.Separator)
for _, pat := range includeMatcher.Patterns() {
if pat.Exclusion() {
continue
}
patStr := patternWithoutTrailingGlob(pat) + string(filepath.Separator)
if strings.HasPrefix(patStr, dirSlash) {
goto passedIncludeFilter
}
}
return filepath.SkipDir
}
passedIncludeFilter:
skip = true
}
}
if excludeMatcher != nil {
var parentExcludeMatchInfo patternmatcher.MatchInfo
if len(parentDirs) != 0 {
parentExcludeMatchInfo = parentDirs[len(parentDirs)-1].excludeMatchInfo
}
m, matchInfo, err := excludeMatcher.MatchesUsingParentResults(path, parentExcludeMatchInfo)
if err != nil {
return errors.Wrap(err, "failed to match excludepatterns")
}
if isDir {
dir.excludeMatchInfo = matchInfo
}
if m {
if isDir && onlyPrefixExcludeExceptions {
// Optimization: we can skip walking this dir if no
// exceptions to exclude patterns could match anything
// inside it.
if !excludeMatcher.Exclusions() {
return filepath.SkipDir
}
dirSlash := path + string(filepath.Separator)
for _, pat := range excludeMatcher.Patterns() {
if !pat.Exclusion() {
continue
}
patStr := patternWithoutTrailingGlob(pat) + string(filepath.Separator)
if strings.HasPrefix(patStr, dirSlash) {
goto passedExcludeFilter
}
}
return filepath.SkipDir
}
passedExcludeFilter:
skip = true
}
}
if walkErr != nil {
if skip && errors.Is(walkErr, os.ErrPermission) {
return nil
}
return walkErr
}
if includeMatcher != nil || excludeMatcher != nil {
defer func() {
if isDir {
parentDirs = append(parentDirs, dir)
}
}()
}
if skip {
return nil
}
dir.calledFn = true
stat, err := mkstat(origpath, path, fi, seenFiles)
if err != nil {
return err
}
select {
case <-ctx.Done():
return ctx.Err()
default:
if opt != nil && opt.Map != nil {
result := opt.Map(stat.Path, stat)
if result == MapResultSkipDir {
return filepath.SkipDir
} else if result == MapResultExclude {
return nil
}
}
for i, parentDir := range parentDirs {
if parentDir.calledFn {
continue
}
parentStat, err := mkstat(parentDir.origpath, parentDir.path, parentDir.fi, seenFiles)
if err != nil {
return err
}
select {
case <-ctx.Done():
return ctx.Err()
default:
}
if opt != nil && opt.Map != nil {
result := opt.Map(parentStat.Path, parentStat)
if result == MapResultSkipDir || result == MapResultExclude {
continue
}
}
if err := fn(parentStat.Path, &StatInfo{parentStat}, nil); err != nil {
return err
}
parentDirs[i].calledFn = true
}
if err := fn(stat.Path, &StatInfo{stat}, nil); err != nil {
return err
}
}
return nil
})
}
func patternWithoutTrailingGlob(p *patternmatcher.Pattern) string {
patStr := p.String()
// We use filepath.Separator here because patternmatcher.Pattern patterns
// get transformed to use the native path separator:
// https://github.com/moby/patternmatcher/blob/130b41bafc16209dc1b52a103fdac1decad04f1a/patternmatcher.go#L52
patStr = strings.TrimSuffix(patStr, string(filepath.Separator)+"**")
patStr = strings.TrimSuffix(patStr, string(filepath.Separator)+"*")
return patStr
}
type StatInfo struct {
*types.Stat
}
func (s *StatInfo) Name() string {
return filepath.Base(s.Stat.Path)
}
func (s *StatInfo) Size() int64 {
return s.Stat.Size_
}
func (s *StatInfo) Mode() os.FileMode {
return os.FileMode(s.Stat.Mode)
}
func (s *StatInfo) ModTime() time.Time {
return time.Unix(s.Stat.ModTime/1e9, s.Stat.ModTime%1e9)
}
func (s *StatInfo) IsDir() bool {
return s.Mode().IsDir()
}
func (s *StatInfo) Sys() interface{} {
return s.Stat
}
func isNotExist(err error) bool {
return errors.Is(err, os.ErrNotExist) || errors.Is(err, syscall.ENOTDIR)
}