-
Notifications
You must be signed in to change notification settings - Fork 0
/
symwalk.go
61 lines (50 loc) · 1.44 KB
/
symwalk.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
// Package symwalk provide a walk function similar to filepath.Walk but follow symbolic links
// but avoid visiting directories more than once even if there is a symbolic link loop
package symwalk
import (
"os"
"path/filepath"
)
// Walk is similar to filepath.Walk (https://golang.org/pkg/path/filepath/#Walk) except it follows
// the symbolic links it finds. The walk function keeps a list of all visited directories to avoid
// endless loop resulted from symbolic loops
func Walk(root string, fn filepath.WalkFunc) error {
rr, err := filepath.EvalSymlinks(root) // Find real base if there is any symlinks in the path
if err != nil {
return err
}
visitedDirs := make(map[string]struct{})
return filepath.Walk(rr, getWalkFn(visitedDirs, fn))
}
func getWalkFn(visitedDirs map[string]struct{}, fn filepath.WalkFunc) filepath.WalkFunc {
return func(path string, info os.FileInfo, err error) error {
if err != nil {
return fn(path, info, err)
}
if info.IsDir() {
if _, ok := visitedDirs[path]; ok {
return filepath.SkipDir
}
visitedDirs[path] = struct{}{}
}
if err := fn(path, info, err); err != nil {
return err
}
if info.Mode()&os.ModeSymlink == 0 {
return nil
}
// path is a symlink
rp, err := filepath.EvalSymlinks(path)
if err != nil {
return err
}
ri, err := os.Stat(rp)
if err != nil {
return err
}
if ri.IsDir() {
return filepath.Walk(rp, getWalkFn(visitedDirs, fn))
}
return nil
}
}