github.com/searKing/golang/go@v1.2.117/path/filepath/match.go (about) 1 // Copyright 2022 The searKing Author. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package filepath 6 7 import ( 8 "errors" 9 "path/filepath" 10 ) 11 12 // WalkGlobFunc is the type of the function called by WalkGlob to visit 13 // all files matching pattern. 14 // 15 // The error result returned by the function controls how WalkGlob 16 // continues. If the function returns the special value [filepath.SkipAll], 17 // WalkGlob skips all files matching pattern satisfying f(c). Otherwise, 18 // if the function returns a non-nil error, WalkGlob stops entirely and 19 // returns that error. 20 type WalkGlobFunc func(path string) error 21 22 // WalkGlob returns the names of all files matching pattern satisfying f(c) or nil 23 // if there is no matching file. The syntax of patterns is the same 24 // as in Match. The pattern may describe hierarchical names such as 25 // /usr/*/bin/ed (assuming the Separator is '/'). 26 // 27 // Glob ignores file system errors such as I/O errors reading directories. 28 // The only possible returned error is ErrBadPattern, when pattern 29 // is malformed. 30 func WalkGlob(pattern string, fn WalkGlobFunc) error { 31 matches, err := filepath.Glob(pattern) 32 if err != nil { 33 return err 34 } 35 36 for _, match := range matches { 37 err = fn(match) 38 if err != nil && errors.Is(err, filepath.SkipAll) { 39 // Successfully skipped all remaining files and directories. 40 err = nil 41 return nil 42 } 43 if err != nil { 44 return err 45 } 46 } 47 return nil 48 } 49 50 // GlobFunc returns the names of all files matching pattern satisfying f(c) or nil 51 // if there is no matching file. The syntax of patterns is the same 52 // as in Match. The pattern may describe hierarchical names such as 53 // /usr/*/bin/ed (assuming the Separator is '/'). 54 // 55 // Glob ignores file system errors such as I/O errors reading directories. 56 // The only possible returned error is ErrBadPattern, when pattern 57 // is malformed. 58 func GlobFunc(pattern string, handler func(name string) bool) (matches []string, err error) { 59 matches, err = filepath.Glob(pattern) 60 if err != nil { 61 return nil, err 62 } 63 if handler == nil { 64 return matches, err 65 } 66 67 var a []string 68 for _, match := range matches { 69 if handler(match) { 70 a = append(a, match) 71 } 72 } 73 return a, nil 74 }