Debian Codegraph @

filter.go

raw symbols SCIP
1 package fsutil
2
3 import (
4 "context"
5 "io"
6 gofs "io/fs"
7 "os"
8 "path/filepath"
9 "strings"
10 "syscall"
11
12 "github.com/moby/patternmatcher"
13 "github.com/pkg/errors"
14 "github.com/tonistiigi/fsutil/types"
15 )
16
17 type FilterOpt struct {
18 // IncludePatterns requires that the path matches at least one of the
19 // specified patterns.
20 IncludePatterns []string
21
22 // ExcludePatterns requires that the path does not match any of the
23 // specified patterns.
24 ExcludePatterns []string
25
26 // FollowPaths contains symlinks that are resolved into IncludePatterns
27 // at the time of the call to NewFilterFS.
28 FollowPaths []string
29
30 // Map is called for each path that is included in the result.
31 // The function can modify the stat info for each element, while the result
32 // of the function controls both how Walk continues.
33 Map MapFunc
34 }
35
36 type MapFunc func(string, *types.Stat) MapResult
37
38 // The result of the walk function controls
39 // both how WalkDir continues and whether the path is kept.
40 type MapResult int
41
42 const (
43 // Keep the current path and continue.
44 MapResultKeep MapResult = iota
45
46 // Exclude the current path and continue.
47 MapResultExclude
48
49 // Exclude the current path, and skip the rest of the dir.
50 // If path is a dir, skip the current directory.
51 // If path is a file, skip the rest of the parent directory.
52 // (This matches the semantics of fs.SkipDir.)
53 MapResultSkipDir
54 )
55
56 type filterFS struct {
57 fs FS
58
59 includeMatcher *patternmatcher.PatternMatcher
60 excludeMatcher *patternmatcher.PatternMatcher
61 onlyPrefixIncludes bool
62 onlyPrefixExcludeExceptions bool
63
64 mapFn MapFunc
65 }
66
67 // NewFilterFS creates a new FS that filters the given FS using the given
68 // FilterOpt.
69 //
70 // The returned FS will not contain any paths that do not match the provided
71 // include and exclude patterns, or that are are excluded using the mapping
72 // function.
73 //
74 // The FS is assumed to be a snapshot of the filesystem at the time of the
75 // call to NewFilterFS. If the underlying filesystem changes, calls to the
76 // underlying FS may be inconsistent.
77 func NewFilterFS(fs FS, opt *FilterOpt) (FS, error) {
78 if opt == nil {
79 return fs, nil
80 }
81
82 var includePatterns []string
83 if opt.IncludePatterns != nil {
84 includePatterns = make([]string, len(opt.IncludePatterns))
85 copy(includePatterns, opt.IncludePatterns)
86 }
87 if opt.FollowPaths != nil {
88 targets, err := FollowLinks(fs, opt.FollowPaths)
89 if err != nil {
90 return nil, err
91 }
92 if targets != nil {
93 includePatterns = append(includePatterns, targets...)
94 includePatterns = dedupePaths(includePatterns)
95 }
96 }
97
98 patternChars := "*[]?^"
99 if filepath.Separator != '\\' {
100 patternChars += `\`
101 }
102
103 var (
104 includeMatcher *patternmatcher.PatternMatcher
105 excludeMatcher *patternmatcher.PatternMatcher
106 err error
107 onlyPrefixIncludes = true
108 onlyPrefixExcludeExceptions = true
109 )
110
111 if len(includePatterns) > 0 {
112 includeMatcher, err = patternmatcher.New(includePatterns)
113 if err != nil {
114 return nil, errors.Wrapf(err, "invalid includepatterns: %s", includePatterns)
115 }
116
117 for _, p := range includeMatcher.Patterns() {
118 if !p.Exclusion() && strings.ContainsAny(patternWithoutTrailingGlob(p), patternChars) {
119 onlyPrefixIncludes = false
120 break
121 }
122 }
123
124 }
125
126 if len(opt.ExcludePatterns) > 0 {
127 excludeMatcher, err = patternmatcher.New(opt.ExcludePatterns)
128 if err != nil {
129 return nil, errors.Wrapf(err, "invalid excludepatterns: %s", opt.ExcludePatterns)
130 }
131
132 for _, p := range excludeMatcher.Patterns() {
133 if p.Exclusion() && strings.ContainsAny(patternWithoutTrailingGlob(p), patternChars) {
134 onlyPrefixExcludeExceptions = false
135 break
136 }
137 }
138 }
139
140 return &filterFS{
141 fs: fs,
142 includeMatcher: includeMatcher,
143 excludeMatcher: excludeMatcher,
144 onlyPrefixIncludes: onlyPrefixIncludes,
145 onlyPrefixExcludeExceptions: onlyPrefixExcludeExceptions,
146 mapFn: opt.Map,
147 }, nil
148 }
149
150 func (fs *filterFS) Open(p string) (io.ReadCloser, error) {
151 if fs.includeMatcher != nil {
152 m, err := fs.includeMatcher.MatchesOrParentMatches(p)
153 if err != nil {
154 return nil, err
155 }
156 if !m {
157 return nil, errors.Wrapf(os.ErrNotExist, "open %s", p)
158 }
159 }
160 if fs.excludeMatcher != nil {
161 m, err := fs.excludeMatcher.MatchesOrParentMatches(p)
162 if err != nil {
163 return nil, err
164 }
165 if m {
166 return nil, errors.Wrapf(os.ErrNotExist, "open %s", p)
167 }
168 }
169 return fs.fs.Open(p)
170 }
171
172 func (fs *filterFS) Walk(ctx context.Context, target string, fn gofs.WalkDirFunc) error {
173 type visitedDir struct {
174 entry gofs.DirEntry
175 pathWithSep string
176 includeMatchInfo patternmatcher.MatchInfo
177 excludeMatchInfo patternmatcher.MatchInfo
178 calledFn bool
179 skipFn bool
180 }
181
182 // used only for include/exclude handling
183 var parentDirs []visitedDir
184
185 return fs.fs.Walk(ctx, target, func(path string, dirEntry gofs.DirEntry, walkErr error) (retErr error) {
186 defer func() {
187 if retErr != nil && isNotExist(retErr) {
188 retErr = filepath.SkipDir
189 }
190 }()
191
192 var (
193 dir visitedDir
194 isDir bool
195 )
196 if dirEntry != nil {
197 isDir = dirEntry.IsDir()
198 }
199
200 if fs.includeMatcher != nil || fs.excludeMatcher != nil {
201 for len(parentDirs) != 0 {
202 lastParentDir := parentDirs[len(parentDirs)-1].pathWithSep
203 if strings.HasPrefix(path, lastParentDir) {
204 break
205 }
206 parentDirs = parentDirs[:len(parentDirs)-1]
207 }
208
209 if isDir {
210 dir = visitedDir{
211 entry: dirEntry,
212 pathWithSep: path + string(filepath.Separator),
213 }
214 }
215 }
216
217 skip := false
218
219 if fs.includeMatcher != nil {
220 var parentIncludeMatchInfo patternmatcher.MatchInfo
221 if len(parentDirs) != 0 {
222 parentIncludeMatchInfo = parentDirs[len(parentDirs)-1].includeMatchInfo
223 }
224 m, matchInfo, err := fs.includeMatcher.MatchesUsingParentResults(path, parentIncludeMatchInfo)
225 if err != nil {
226 return errors.Wrap(err, "failed to match includepatterns")
227 }
228
229 if isDir {
230 dir.includeMatchInfo = matchInfo
231 }
232
233 if !m {
234 if isDir && fs.onlyPrefixIncludes {
235 // Optimization: we can skip walking this dir if no include
236 // patterns could match anything inside it.
237 dirSlash := path + string(filepath.Separator)
238 for _, pat := range fs.includeMatcher.Patterns() {
239 if pat.Exclusion() {
240 continue
241 }
242 patStr := patternWithoutTrailingGlob(pat) + string(filepath.Separator)
243 if strings.HasPrefix(patStr, dirSlash) {
244 goto passedIncludeFilter
245 }
246 }
247 return filepath.SkipDir
248 }
249 passedIncludeFilter:
250 skip = true
251 }
252 }
253
254 if fs.excludeMatcher != nil {
255 var parentExcludeMatchInfo patternmatcher.MatchInfo
256 if len(parentDirs) != 0 {
257 parentExcludeMatchInfo = parentDirs[len(parentDirs)-1].excludeMatchInfo
258 }
259 m, matchInfo, err := fs.excludeMatcher.MatchesUsingParentResults(path, parentExcludeMatchInfo)
260 if err != nil {
261 return errors.Wrap(err, "failed to match excludepatterns")
262 }
263
264 if isDir {
265 dir.excludeMatchInfo = matchInfo
266 }
267
268 if m {
269 if isDir && fs.onlyPrefixExcludeExceptions {
270 // Optimization: we can skip walking this dir if no
271 // exceptions to exclude patterns could match anything
272 // inside it.
273 if !fs.excludeMatcher.Exclusions() {
274 return filepath.SkipDir
275 }
276
277 dirSlash := path + string(filepath.Separator)
278 for _, pat := range fs.excludeMatcher.Patterns() {
279 if !pat.Exclusion() {
280 continue
281 }
282 patStr := patternWithoutTrailingGlob(pat) + string(filepath.Separator)
283 if strings.HasPrefix(patStr, dirSlash) {
284 goto passedExcludeFilter
285 }
286 }
287 return filepath.SkipDir
288 }
289 passedExcludeFilter:
290 skip = true
291 }
292 }
293
294 if walkErr != nil {
295 if skip && errors.Is(walkErr, os.ErrPermission) {
296 return nil
297 }
298 return walkErr
299 }
300
301 if fs.includeMatcher != nil || fs.excludeMatcher != nil {
302 defer func() {
303 if isDir {
304 parentDirs = append(parentDirs, dir)
305 }
306 }()
307 }
308
309 if skip {
310 return nil
311 }
312
313 dir.calledFn = true
314
315 fi, err := dirEntry.Info()
316 if err != nil {
317 return err
318 }
319 stat, ok := fi.Sys().(*types.Stat)
320 if !ok {
321 return errors.WithStack(&os.PathError{Path: path, Err: syscall.EBADMSG, Op: "fileinfo without stat info"})
322 }
323
324 select {
325 case <-ctx.Done():
326 return ctx.Err()
327 default:
328 if fs.mapFn != nil {
329 result := fs.mapFn(stat.Path, stat)
330 if result == MapResultSkipDir {
331 return filepath.SkipDir
332 } else if result == MapResultExclude {
333 return nil
334 }
335 }
336 for i, parentDir := range parentDirs {
337 if parentDir.skipFn {
338 return filepath.SkipDir
339 }
340 if parentDir.calledFn {
341 continue
342 }
343 parentFi, err := parentDir.entry.Info()
344 if err != nil {
345 return err
346 }
347 parentStat, ok := parentFi.Sys().(*types.Stat)
348 if !ok {
349 return errors.WithStack(&os.PathError{Path: path, Err: syscall.EBADMSG, Op: "fileinfo without stat info"})
350 }
351
352 select {
353 case <-ctx.Done():
354 return ctx.Err()
355 default:
356 }
357 if fs.mapFn != nil {
358 result := fs.mapFn(parentStat.Path, parentStat)
359 if result == MapResultExclude {
360 continue
361 } else if result == MapResultSkipDir {
362 parentDirs[i].skipFn = true
363 return filepath.SkipDir
364 }
365 }
366
367 parentDirs[i].calledFn = true
368 if err := fn(parentStat.Path, &DirEntryInfo{Stat: parentStat}, nil); err == filepath.SkipDir {
369 parentDirs[i].skipFn = true
370 return filepath.SkipDir
371 } else if err != nil {
372 return err
373 }
374 }
375 if err := fn(stat.Path, &DirEntryInfo{Stat: stat}, nil); err != nil {
376 return err
377 }
378 }
379 return nil
380 })
381 }
382
383 func Walk(ctx context.Context, p string, opt *FilterOpt, fn filepath.WalkFunc) error {
384 f, err := NewFS(p)
385 if err != nil {
386 return err
387 }
388 f, err = NewFilterFS(f, opt)
389 if err != nil {
390 return err
391 }
392 return f.Walk(ctx, "/", func(path string, d gofs.DirEntry, err error) error {
393 var info gofs.FileInfo
394 if d != nil {
395 var err2 error
396 info, err2 = d.Info()
397 if err == nil {
398 err = err2
399 }
400 }
401 return fn(path, info, err)
402 })
403 }
404
405 func WalkDir(ctx context.Context, p string, opt *FilterOpt, fn gofs.WalkDirFunc) error {
406 f, err := NewFS(p)
407 if err != nil {
408 return err
409 }
410 f, err = NewFilterFS(f, opt)
411 if err != nil {
412 return err
413 }
414 return f.Walk(ctx, "/", fn)
415 }
416
417 func patternWithoutTrailingGlob(p *patternmatcher.Pattern) string {
418 patStr := p.String()
419 // We use filepath.Separator here because patternmatcher.Pattern patterns
420 // get transformed to use the native path separator:
421 // https://github.com/moby/patternmatcher/blob/130b41bafc16209dc1b52a103fdac1decad04f1a/patternmatcher.go#L52
422 patStr = strings.TrimSuffix(patStr, string(filepath.Separator)+"**")
423 patStr = strings.TrimSuffix(patStr, string(filepath.Separator)+"*")
424 return patStr
425 }
426
427 func isNotExist(err error) bool {
428 return errors.Is(err, os.ErrNotExist) || errors.Is(err, syscall.ENOTDIR)
429 }