-
Notifications
You must be signed in to change notification settings - Fork 2
/
watch.go
49 lines (43 loc) · 1.16 KB
/
watch.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
package main
import (
"gopkg.in/fsnotify.v1"
"log"
"strings"
"time"
)
// Returns the channel that'll send you file changes.
// Folder cannot use ~
// Won't include subfolders - linux doesn't allow for this.
func watch(folders []string) chan string {
changes := make(chan string)
// This won't recursively watch a folder; this can't be done by any library on linux anyway.
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Fatal("Error starting watcher: ", err)
}
// Watch all the folders.
for _, folder := range folders {
err = watcher.Add(folder)
if err != nil {
log.Fatal("Error adding watcher: ", err)
}
}
go func() {
for {
select {
case event := <-watcher.Events:
// Ignore changes to hidden/system/ds_store files.
if !strings.HasPrefix(event.Name, ".") {
log.Println("Event: ", event)
time.Sleep(time.Second) // Wait a bit before scanning the file, to give the transfer's write-lock a chance to take hold.
changes <- event.Name
} else {
log.Println("Ignoring event for hidden/system file: ", event.Name)
}
case err := <-watcher.Errors:
log.Println("Error: ", err)
}
}
}()
return changes
}