-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwatcher.go
More file actions
78 lines (69 loc) · 1.43 KB
/
watcher.go
File metadata and controls
78 lines (69 loc) · 1.43 KB
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
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"sync"
"github.com/fsnotify/fsnotify"
)
type clockConf struct {
SEC string `json:"sec"`
MIN string `json:"min"`
HR string `json:"hr"`
}
func readConf(fname string) clockConf {
// json data
var obj clockConf
// read file
data, err := ioutil.ReadFile(fname)
if err != nil {
fmt.Print(err)
return obj
}
// Unmarshal json.
// NOTE: When we edit clock.json with VsCode we get a json error, but the Unmarshal is successful.
// ALSO NOTE: Some editors do not write to the real file until you exit.
// For best results use VI to edit the clock.json file.
err = json.Unmarshal(data, &obj)
if err != nil {
fmt.Println("error:", err)
return obj
}
return obj
}
func watcher(wg *sync.WaitGroup, dir string, fname string, done <-chan bool, chg chan bool) {
defer wg.Done()
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Fatal(err)
}
defer watcher.Close()
go func() {
for {
select {
case event, ok := <-watcher.Events:
if !ok {
return
}
if event.Op&fsnotify.Write == fsnotify.Write {
if fname == event.Name {
chg <- true
}
}
case err, ok := <-watcher.Errors:
if !ok {
return
}
log.Println("watcher error:", err)
}
}
}()
err = watcher.Add(dir)
if err != nil {
log.Fatal(err)
}
log.Printf("watcher has started watching %s.\n", dir)
<-done
log.Println("watcher is shuting down.")
}