-
Notifications
You must be signed in to change notification settings - Fork 8
/
fs.go
59 lines (55 loc) · 1.55 KB
/
fs.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
package docsite
import (
"fmt"
"net/http"
"os"
"path/filepath"
"sort"
"strings"
"github.com/pkg/errors"
)
// WalkFileSystem walks a file system and calls walkFn for each file that passes filterFn.
func WalkFileSystem(fs http.FileSystem, filterFn func(path string) bool, walkFn func(path string) error) error {
path := "/"
root, err := fs.Open(path)
if err != nil {
return errors.WithMessage(err, fmt.Sprintf("open walk root %s", path))
}
defer root.Close()
fi, err := root.Stat()
if err != nil {
return errors.WithMessage(err, fmt.Sprintf("stat walk root %s", path))
}
type queueItem struct {
path string
fi os.FileInfo
}
queue := []queueItem{{path: path, fi: fi}}
for len(queue) > 0 {
item := queue[0]
queue = queue[1:]
if item.fi.Mode().IsDir() {
if strings.HasPrefix(item.fi.Name(), ".") && item.fi.Name() != "." {
continue // skip dot-dirs
}
dir, err := fs.Open(item.path)
if err != nil {
return errors.WithMessage(err, fmt.Sprintf("open %s", item.path))
}
entries, err := dir.Readdir(-1)
dir.Close()
if err != nil {
return errors.WithMessage(err, fmt.Sprintf("readdir %s", item.path))
}
sort.Slice(entries, func(i, j int) bool { return entries[i].Name() < entries[j].Name() })
for _, e := range entries {
queue = append(queue, queueItem{path: filepath.Join(item.path, e.Name()), fi: e})
}
} else if filterFn(item.path) {
if err := walkFn(strings.TrimPrefix(item.path, "/")); err != nil {
return errors.WithMessage(err, fmt.Sprintf("walk %s", item.path))
}
}
}
return nil
}