-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
walk.go
84 lines (74 loc) · 1.84 KB
/
walk.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
package fsext
import (
"os"
"path/filepath"
"sort"
"github.com/spf13/afero"
)
// Walk implements afero.Walk, but in a way that it doesn't loop to infinity and doesn't have
// problems if a given path part looks like a windows volume name
func Walk(fs afero.Fs, root string, walkFn filepath.WalkFunc) error {
info, err := fs.Stat(root)
if err != nil {
return walkFn(root, nil, err)
}
return walk(fs, root, info, walkFn)
}
// readDirNames reads the directory named by dirname and returns
// a sorted list of directory entries.
// adapted from https://github.com/spf13/afero/blob/master/path.go#L27
func readDirNames(fs afero.Fs, dirname string) ([]string, error) {
f, err := fs.Open(dirname)
if err != nil {
return nil, err
}
infos, err := f.Readdir(-1)
if err != nil {
return nil, err
}
err = f.Close()
if err != nil {
return nil, err
}
var names = make([]string, len(infos))
for i, info := range infos {
names[i] = info.Name()
}
sort.Strings(names)
return names, nil
}
// walk recursively descends path, calling walkFn
// adapted from https://github.com/spf13/afero/blob/master/path.go#L27
func walk(fs afero.Fs, path string, info os.FileInfo, walkFn filepath.WalkFunc) error {
err := walkFn(path, info, nil)
if err != nil {
if info.IsDir() && err == filepath.SkipDir {
return nil
}
return err
}
if !info.IsDir() {
return nil
}
names, err := readDirNames(fs, path)
if err != nil {
return walkFn(path, info, err)
}
for _, name := range names {
filename := filepath.Join(path, name)
fileInfo, err := fs.Stat(filename)
if err != nil {
if err = walkFn(filename, fileInfo, err); err != nil && err != filepath.SkipDir {
return err
}
} else {
err = walk(fs, filename, fileInfo, walkFn)
if err != nil {
if !fileInfo.IsDir() || err != filepath.SkipDir {
return err
}
}
}
}
return nil
}