forked from torbiak/gopl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
105 lines (91 loc) · 2.19 KB
/
main.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
101
102
103
104
105
// ex8.9 is a concurrent du clone.
package main
import (
"flag"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"sync"
"time"
)
var vFlag = flag.Bool("v", false, "show verbose progress messages")
type SizeResponse struct {
root int
size int64
}
func main() {
// ...determine roots...
flag.Parse()
// Determine the initial directories.
roots := flag.Args()
if len(roots) == 0 {
roots = []string{"."}
}
// Traverse each root of the file tree in parallel.
sizeResponses := make(chan SizeResponse)
var n sync.WaitGroup
for i, root := range roots {
n.Add(1)
go walkDir(root, &n, i, sizeResponses)
}
go func() {
n.Wait()
close(sizeResponses)
}()
// Print the results periodically.
var tick <-chan time.Time
if *vFlag {
tick = time.Tick(500 * time.Millisecond)
}
nfiles := make([]int64, len(roots))
nbytes := make([]int64, len(roots))
loop:
for {
select {
case sr, ok := <-sizeResponses:
if !ok {
break loop // sizeResponses was closed
}
nfiles[sr.root]++
nbytes[sr.root] += sr.size
case <-tick:
printDiskUsage(roots, nfiles, nbytes)
}
}
printDiskUsage(roots, nfiles, nbytes) // final totals
// ...select loop...
}
func printDiskUsage(roots []string, nfiles, nbytes []int64) {
for i, r := range roots {
fmt.Printf("%10d files %.3f GB under %s\n", nfiles[i], float64(nbytes[i])/1e9, r)
}
}
// walkDir recursively walks the file tree rooted at dir
// and sends the size of each found file on sizeResponses.
func walkDir(dir string, n *sync.WaitGroup, root int, sizeResponses chan<- SizeResponse) {
defer n.Done()
for _, entry := range dirents(dir) {
if entry.IsDir() {
n.Add(1)
subdir := filepath.Join(dir, entry.Name())
go walkDir(subdir, n, root, sizeResponses)
} else {
sizeResponses <- SizeResponse{root, entry.Size()}
}
}
}
// sema is a counting semaphore for limiting concurrency in dirents.
var sema = make(chan struct{}, 20)
// dirents returns the entries of directory dir.
func dirents(dir string) []os.FileInfo {
sema <- struct{}{} // acquire token
defer func() { <-sema }() // release token
// ...
entries, err := ioutil.ReadDir(dir)
if err != nil {
fmt.Fprintf(os.Stderr, "du: %v\n", err)
return nil
}
return entries
}