-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdfs.go
100 lines (89 loc) · 2.23 KB
/
dfs.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
100
package main
import (
"errors"
"io/fs"
"log"
"os"
)
func FilesystemDFS(root string, path string, parentId uint32, idChan chan uint32, reducerChan chan *FSNodeStat, returnChan chan *FSNodeStat, sem *Semaphore, isAsync bool) *FSNodeStat {
if isAsync {
sem.Acquire()
defer sem.Release()
}
stat, err := os.Lstat(path)
if errors.Is(err, fs.ErrNotExist) {
log.Printf("DFS ERROR: Path not found: %s", path)
if isAsync {
returnChan <- nil
}
return nil
}
if err != nil {
log.Printf("DFS ERROR: Error while getting stats for %s: %s", path, err)
if isAsync {
returnChan <- nil
}
return nil
}
if stat.Mode().IsRegular() {
size := stat.Size()
data := CreateFSNodeStat(root, path, parentId, size, false, idChan)
reducerChan <- data
if isAsync {
returnChan <- data
}
return data
}
if stat.Mode()&fs.ModeSymlink != 0 {
target, err := os.Readlink(path)
if err != nil {
log.Println("DFS ERROR: Symbolic link read error:", err)
}
data := CreateFSLinkStat(root, path, parentId, target, idChan)
reducerChan <- data
if isAsync {
returnChan <- data
}
return data
}
if stat.IsDir() {
var childrenPaths []string
children, err := os.ReadDir(path)
if err != nil {
log.Printf("DFS ERROR: Error while reading directory %s: %s", path, err)
}
childrenPaths = []string{}
for _, child := range children {
childrenPaths = append(childrenPaths, path+"/"+child.Name())
}
size := stat.Size()
data := CreateFSNodeStat(root, path, parentId, size, true, idChan)
if len(childrenPaths) > 0 {
if len(sem.semC) < sem.maxConcurrency {
childReturnChan := make(chan *FSNodeStat)
for _, childPath := range childrenPaths {
go FilesystemDFS(root, childPath, data.Id, idChan, reducerChan, childReturnChan, sem, true)
}
sem.Release()
for i := 0; i < len(childrenPaths); i++ {
data.Update(<-childReturnChan)
}
sem.Acquire()
} else {
for _, childPath := range childrenPaths {
data.Update(FilesystemDFS(root, childPath, data.Id, idChan, reducerChan, nil, sem, false))
}
}
}
reducerChan <- data
if isAsync {
returnChan <- data
}
return data
}
log.Println("ERROR: Unsupported file type:", path)
if isAsync {
returnChan <- nil
}
return nil
}