Debian Codegraph @

util/walk.go

raw symbols SCIP
1 package util
2
3 import (
4 "errors"
5 "os"
6 "path/filepath"
7
8 "github.com/go-git/go-billy/v6"
9 )
10
11 // walk recursively descends path, calling walkFn
12 // adapted from https://golang.org/src/path/filepath/path.go
13 func walk(fs billy.Filesystem, path string, info os.FileInfo, walkFn filepath.WalkFunc) error {
14 if !info.IsDir() {
15 return walkFn(path, info, nil)
16 }
17
18 names, err := readdirnames(fs, path)
19 err1 := walkFn(path, info, err)
20 // If err != nil, walk can't walk into this directory.
21 // err1 != nil means walkFn want walk to skip this directory or stop walking.
22 // Therefore, if one of err and err1 isn't nil, walk will return.
23 if err != nil || err1 != nil {
24 // The caller's behavior is controlled by the return value, which is decided
25 // by walkFn. walkFn may ignore err and return nil.
26 // If walkFn returns SkipDir, it will be handled by the caller.
27 // So walk should return whatever walkFn returns.
28 return err1
29 }
30
31 for _, name := range names {
32 filename := filepath.Join(path, name)
33 fileInfo, err := fs.Lstat(filename)
34 if err != nil {
35 if err := walkFn(filename, fileInfo, err); err != nil && !errors.Is(err, filepath.SkipDir) {
36 return err
37 }
38 } else {
39 err = walk(fs, filename, fileInfo, walkFn)
40 if err != nil {
41 if !fileInfo.IsDir() || !errors.Is(err, filepath.SkipDir) {
42 return err
43 }
44 }
45 }
46 }
47 return nil
48 }
49
50 // Walk walks the file tree rooted at root, calling fn for each file or
51 // directory in the tree, including root. All errors that arise visiting files
52 // and directories are filtered by fn: see the WalkFunc documentation for
53 // details.
54 //
55 // The files are walked in lexical order, which makes the output deterministic
56 // but requires Walk to read an entire directory into memory before proceeding
57 // to walk that directory. Walk does not follow symbolic links.
58 //
59 // Function adapted from https://github.com/golang/go/blob/3b770f2ccb1fa6fecc22ea822a19447b10b70c5c/src/path/filepath/path.go#L500
60 func Walk(fs billy.Filesystem, root string, walkFn filepath.WalkFunc) error {
61 info, err := fs.Lstat(root)
62 if err != nil {
63 err = walkFn(root, nil, err)
64 } else {
65 err = walk(fs, root, info, walkFn)
66 }
67
68 if errors.Is(err, filepath.SkipDir) {
69 return nil
70 }
71
72 return err
73 }