/
walker.go
99 lines (89 loc) · 2.21 KB
/
walker.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
// Copyright 2017 GRAIL, Inc. All rights reserved.
// Use of this source code is governed by the Apache 2.0
// license that can be found in the LICENSE file.
package walker
import (
"os"
"path/filepath"
"sort"
)
// Walker walks a recursive directory hierarchy, exposing a scanner-like interface.
type Walker struct {
root string
err error
path string
info os.FileInfo
todo []string
}
// Init initializes a walker to walk from a root path.
func (w *Walker) Init(root string) {
w.root = root
w.todo = append(w.todo, w.root)
}
// Scan advances the walker to the next entry in the hierarchy.
// It returns false either when the scan stops because we have
// reached the end of the input or else because there was error.
// After Scan returns, the Err method returns any error that occurred
// during scanning.
func (w *Walker) Scan() bool {
again:
if len(w.todo) == 0 || w.err != nil {
return false
}
w.path, w.todo = w.todo[0], w.todo[1:]
w.info, w.err = os.Stat(w.path)
if os.IsNotExist(w.err) {
w.err = nil
goto again
} else if w.err != nil {
return false
}
if w.info.IsDir() {
var paths []string
paths, w.err = readDirNames(w.path)
if w.err != nil {
return false
}
for i := range paths {
paths[i] = filepath.Join(w.path, paths[i])
}
w.todo = append(paths, w.todo...)
}
return true
}
// Path returns the most recent path that was scanned.
func (w *Walker) Path() string {
return w.path
}
// Relpath returns the most recent path that was scanned, relative to
// the scan root directory.
func (w *Walker) Relpath() string {
path, err := filepath.Rel(w.root, w.Path())
if err != nil {
panic("bad path")
}
return path
}
// Info returns the os.FileInfo for the most recent path scanned.
func (w *Walker) Info() os.FileInfo {
return w.info
}
// Err returns the first error that occurred while scanning.
func (w *Walker) Err() error {
return w.err
}
// readDirNames reads the directory named by dirname and returns
// a sorted list of directory entries.
func readDirNames(dirname string) ([]string, error) {
f, err := os.Open(dirname)
if err != nil {
return nil, err
}
names, err := f.Readdirnames(-1)
f.Close()
if err != nil {
return nil, err
}
sort.Strings(names)
return names, nil
}