forked from bastengao/gncdu
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscan.go
79 lines (63 loc) · 1.27 KB
/
scan.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
package scan
import (
"io/ioutil"
"runtime"
"sync"
)
func ScanDirConcurrent(dir string, concurrency int) ([]*FileData, error) {
root := newRootFileData(dir)
if concurrency == 0 {
concurrency = DefaultConcurrency()
}
ch := make(chan *FileData)
closeWait := &sync.WaitGroup{}
var wait sync.WaitGroup
wait.Add(concurrency)
for i := 0; i < concurrency; i++ {
go func() {
for file := range ch {
scanDir(file, ch, closeWait)
closeWait.Done()
}
wait.Done()
}()
}
err := scanDir(root, ch, closeWait)
if err != nil {
return nil, err
}
go func() {
closeWait.Wait()
close(ch)
}()
wait.Wait()
return root.Children, nil
}
func DefaultConcurrency() int {
maxProcs := runtime.GOMAXPROCS(0)
numCPU := runtime.NumCPU()
if maxProcs < numCPU {
return maxProcs
}
return numCPU
}
func scanDir(parent *FileData, ch chan *FileData, closeWait *sync.WaitGroup) error {
if !parent.Root() && (parent.size != -1 || !parent.Info.IsDir()) {
return nil
}
files, err := ioutil.ReadDir(parent.Path())
if err != nil {
return err
}
children := []*FileData{}
closeWait.Add(len(files))
for _, file := range files {
f := newFileData(parent, file)
go func() {
ch <- f
}()
children = append(children, f)
}
parent.Children = children
return nil
}