forked from gaigepr/secureBox
/
setupWatch.go
65 lines (55 loc) · 1.29 KB
/
setupWatch.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
package main
import (
"fmt"
"os"
"path/filepath"
"code.google.com/p/go.exp/fsnotify"
)
func IndexOf(element string, array []string) int {
for i := 0; i < len(array); i++ {
if array[i] == element {
return i
}
}
return -1
}
func CollectPaths(paths []string) []string {
// paths to be returned
collectedPaths := make([]string, 1, 1)
for _, thisPath := range paths {
err := filepath.Walk(thisPath,
// Function arg for filepath.Walk
func(path string, info os.FileInfo, err error) error {
if info == nil {
fmt.Println("File or directory does not exist.", path)
} else if info.IsDir() {
collectedPaths = append(collectedPaths, path)
}
return nil
})
if err != nil {
fmt.Println(err)
}
}
return collectedPaths
}
func SetupWatch(paths []string, excludes []string) (int, *fsnotify.Watcher) {
var watchedCount int
paths = CollectPaths(paths)
excludes = CollectPaths(excludes)
watcher, err := fsnotify.NewWatcher()
if err != nil {
fmt.Println("Error establishing watcher: ", err)
}
// establish watches
for _, path := range paths {
if IndexOf(path, excludes) == -1 {
err = watcher.Watch(path)
if err != nil {
fmt.Println("Error: ", err, " establishing watch on: ", path)
}
watchedCount++
}
}
return watchedCount, watcher
}