/
fsmonitor.go
105 lines (91 loc) · 2.57 KB
/
fsmonitor.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
package main
import (
"code.google.com/p/go.exp/fsnotify"
"fmt"
"os"
"path/filepath"
)
func StartWatch(paths []string, recursive bool, excludes []string) (*fsnotify.Watcher, int, error) {
// TODO: Check and handle a non-recursive watch request
watched := 0
watcher, err := fsnotify.NewWatcher()
if err != nil {
fmt.Println("Error with establishing watcher, fsmonitor.go line 17:", err)
}
for _, path := range paths {
err = filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
if info.IsDir() && !(IsSubDir(excludes, path)) {
func(path string) (err error) {
err = watcher.Watch(path)
watched++
if err != nil {
fmt.Printf("fsmonitor.go line 25\terror: %v: %v\n", err, path)
return err
}
return nil
// TODO: try to find out why the number of directories
// watched seems to be different between executions
}(path)
}
return err
})
if err != nil {
fmt.Println("Error with walking filepath, fsmonitor.go line 36:", err)
}
}
return watcher, watched, err
}
func logEvent(name string, eventType string) {
// after deletion (and potentially rename) we cannot ascertain
// if the thing renamed or deleted was a file or directory. This
// more or may not be a problem.
info, err := os.Lstat(name)
if err != nil {
fmt.Printf("File or directory %s: %v\n", eventType, name)
return
}
if info.IsDir() {
fmt.Printf("Directory %s: %v\n", eventType, name)
} else if !(info.IsDir()) {
fmt.Printf("File %s: %v\n", eventType, name)
}
return
}
func EventHandler(watcher *fsnotify.Watcher, manager chan *Command) {
for {
select {
case ev := <-watcher.Event:
//encrypt() upload()
switch {
case ev.IsCreate():
watcher.Watch(ev.Name)
logEvent(ev.Name, "create")
case ev.IsDelete():
watcher.RemoveWatch(ev.Name)
logEvent(ev.Name, "delete")
case ev.IsModify():
logEvent(ev.Name, "modify")
case ev.IsAttrib():
logEvent(ev.Name, "modify attrib")
case ev.IsRename():
watcher.RemoveWatch(ev.Name)
logEvent(ev.Name, "rename")
default:
fmt.Println("Something is weird. Event but not type?")
}
case err := <-watcher.Error:
// TODO: handle errors and see why reading from this can cause a block.
fmt.Println("error reading error in fsmonitor: ", err)
case com := <-manager:
// TODO: Add in ability to add/remove watches from a recieved command
if com.exitP {
err := watcher.Close()
fmt.Println("Returning EventHandler")
if err != nil {
fmt.Println("Error on close of watch: ", err)
}
return
}
}
}
}