/
file_walker.go
55 lines (44 loc) · 1.28 KB
/
file_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
package mapping
import (
"fmt"
"io/ioutil"
"path"
"sync"
)
func walkDirectories(directories []string, callback func(string, bool)) {
var wg sync.WaitGroup
var callbackLock sync.Mutex
wg.Add(len(directories))
directoriesToVisit := make(chan string, 1000000)
for _, dir := range directories {
directoriesToVisit <- dir
}
for i := 0; i < 5; i++ {
go readDirectories(directoriesToVisit, &wg, &callbackLock, callback)
}
wg.Wait()
close(directoriesToVisit)
}
func readDirectories(directoriesToVisit chan string, wg *sync.WaitGroup, callbackLock *sync.Mutex, callback func(string, bool)) {
for dirToRead := range directoriesToVisit {
readDirectory(dirToRead, directoriesToVisit, wg, callbackLock, callback)
}
}
func readDirectory(dirToRead string, directoriesToVisit chan string, wg *sync.WaitGroup, callbackLock *sync.Mutex, callback func(string, bool)) {
defer wg.Done()
files, readDirErr := ioutil.ReadDir(dirToRead)
if readDirErr != nil {
fmt.Printf("Error while reading directory: %s\n%s\n", dirToRead, readDirErr.Error())
return
}
for _, file := range files {
pathToFile := path.Join(dirToRead, file.Name())
if file.IsDir() {
wg.Add(1)
directoriesToVisit <- pathToFile
}
callbackLock.Lock()
callback(pathToFile, file.IsDir())
callbackLock.Unlock()
}
}