-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFileWatcher.go
86 lines (78 loc) · 2.08 KB
/
FileWatcher.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
package main
import (
"PikaFileService/connectors"
"log"
"os"
"path/filepath"
"regexp"
"strings"
"time"
"github.com/radovskyb/watcher"
)
//TODO: Log to file
func StartFWatch(folders []string, dstPath string) {
w := watcher.New()
w.SetMaxEvents(2)
w.FilterOps(watcher.Rename, watcher.Move, watcher.Remove, watcher.Create, watcher.Write)
r := regexp.MustCompile("(\\w|[-.])+$")
w.AddFilterHook(watcher.RegexFilterHook(r, false))
go func() {
for {
select {
case event := <-w.Event:
executeFilesystemOperation(event, dstPath)
case err := <-w.Error:
log.Fatalln(err)
case <-w.Closed:
return
}
}
}()
for _, file := range folders {
if err := w.AddRecursive(file); err != nil {
log.Fatalln(err)
}
}
if err := w.Start(time.Millisecond * 500); err != nil {
log.Fatalln(err)
}
}
func executeFilesystemOperation(event watcher.Event, dstPath string) {
switch {
case event.Op == watcher.Create:
dstPath = createDestinationPath(event.Path, dstPath)
if !event.IsDir() {
if err := connectors.CopyFile(event.Path, dstPath); err != nil {
log.Println(err.Error())
}
} else {
if cwd, _ := os.Getwd(); cwd != dstPath {
if err := connectors.Mkdir(dstPath, event.Mode()); err != nil {
log.Println(err.Error())
}
}
}
case event.Op == watcher.Rename:
dstBeforeRename := createDestinationPath(event.OldPath, dstPath)
dstPath = createDestinationPath(event.Path, dstPath)
if err := connectors.RenameFile(dstPath, event.Path, dstBeforeRename); err != nil {
log.Println(err.Error())
}
case event.Op == watcher.Remove:
dstPath = createDestinationPath(event.OldPath, dstPath)
if err := connectors.RemoveFile(dstPath); err != nil {
log.Println(err.Error())
}
case event.Op == watcher.Write:
dstPath = createDestinationPath(event.Path, dstPath)
if !event.IsDir() {
if err := connectors.CopyFile(event.Path, dstPath); err != nil {
log.Println(err.Error())
}
}
}
}
func createDestinationPath(path string, dstPath string) string {
cwd, _ := os.Getwd()
return filepath.Join(dstPath, strings.Replace(path, cwd, "", -1))
}