-
Notifications
You must be signed in to change notification settings - Fork 0
/
bfs.go
64 lines (51 loc) · 1.39 KB
/
bfs.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
package discovery
import (
"fmt"
"io"
"os"
"path/filepath"
)
type bfsDiscoverer struct {
State BfsState
}
type BfsState struct {
Queue []FileInformation
}
func MakeBfsDiscoverer(basePath string) (Discoverer, error) {
baseInfo, baseInfoErr := MakeFileInformation(basePath)
if baseInfoErr != nil {
return nil, baseInfoErr
}
initialState := BfsState{Queue: []FileInformation{baseInfo}}
if !baseInfo.Info.IsDir() && !baseInfo.Info.Mode().IsRegular() {
return nil, fmt.Errorf("%v is an unsupported file", basePath)
}
return &bfsDiscoverer{State: initialState}, nil
}
func (bfs *bfsDiscoverer) Next() (FileInformation, error) {
if len(bfs.State.Queue) == 0 {
return FileInformation{}, io.EOF
}
var resultItem *FileInformation
for resultItem == nil && len(bfs.State.Queue) > 0 {
currentItem := bfs.State.Queue[0]
canProcessItem := currentItem.Info.IsDir() || currentItem.Info.Mode().IsRegular()
bfs.State.Queue = bfs.State.Queue[1:]
if canProcessItem {
resultItem = ¤tItem
}
}
if resultItem == nil {
return FileInformation{}, io.EOF
}
if resultItem.Info.IsDir() {
childern, _ := os.ReadDir(resultItem.FullPath)
for _, child := range childern {
fInfo, fInfoErr := MakeFileInformationWithSymbolicLinks(filepath.Join(resultItem.FullPath, child.Name()))
if fInfoErr == nil {
bfs.State.Queue = append(bfs.State.Queue, fInfo)
}
}
}
return *resultItem, nil
}