-
Notifications
You must be signed in to change notification settings - Fork 0
/
watcher.go
96 lines (81 loc) · 2.45 KB
/
watcher.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
// Package watcher monitors a data folder and performs automatic reloading of data
// including updating the datasource cache in memory for deleted and edited data files
package watcher
import (
"fmt"
"path/filepath"
"strings"
"sync"
"github.com/spoonboy-io/dujour/internal/file"
"github.com/spoonboy-io/dujour/internal"
"github.com/fsnotify/fsnotify"
"github.com/spoonboy-io/koan"
)
// Monitor creates a file watcher for the data directory
func Monitor(datasources map[string]internal.Datasource, logger *koan.Logger, mtx *sync.Mutex) error {
watchPath := filepath.Join(".", internal.DATA_FOLDER)
logger.Info(fmt.Sprintf("Creating Watcher for '%s' folder", watchPath))
watcher, err := fsnotify.NewWatcher()
if err != nil {
return fmt.Errorf("Could not create watcher; %v", err)
}
defer watcher.Close()
done := make(chan bool)
go func() {
defer close(done)
var processAdd = func(event fsnotify.Event) {
extension := strings.ToLower(filepath.Ext(event.Name))
if (extension != ".csv") && (extension != ".json") {
if extension != "" {
logger.Warn(fmt.Sprintf("Hotloader skipping file '%s', file extension is '%s'", event.Name, extension))
return
}
}
// init & validate the file
var hlds internal.Datasource
var err error
if hlds, err = file.LoadAndValidate(file.InitDatasource(event.Name), logger); err != nil {
logger.Error(fmt.Sprintf("Could not hotload datasource '%s'", event.Name), err)
}
// add the datasource
mtx.Lock()
datasources[event.Name] = hlds
mtx.Unlock()
}
for {
select {
case event, ok := <-watcher.Events:
if !ok {
return
}
switch event.Op {
case fsnotify.Create:
logger.Info(fmt.Sprintf("Hotloader file added '%s'", event.Name))
processAdd(event)
case fsnotify.Write:
logger.Info(fmt.Sprintf("Hotloader file written '%s'", event.Name))
processAdd(event)
case fsnotify.Chmod:
logger.Info(fmt.Sprintf("Hotloader file written '%s'", event.Name))
processAdd(event)
case fsnotify.Remove, fsnotify.Rename:
logger.Info(fmt.Sprintf("Hotloader file removed '%s'", event.Name))
// remove
mtx.Lock()
delete(datasources, event.Name)
mtx.Unlock()
}
case err, ok := <-watcher.Errors:
if !ok {
return
}
logger.Error("Watcher unexpected error:", err)
}
}
}()
if err := watcher.Add(watchPath); err != nil {
return fmt.Errorf("Adding file failed; %v", err)
}
<-done
return nil
}