forked from gcla/termshark
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfwatcher.go
97 lines (77 loc) · 2.16 KB
/
confwatcher.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
// Copyright 2019-2020 Graham Clark. All rights reserved. Use of this source
// code is governed by the MIT license that can be found in the LICENSE
// file.
package termshark
import (
"os"
"sync"
log "github.com/sirupsen/logrus"
fsnotify "gopkg.in/fsnotify/fsnotify.v1"
)
//======================================================================
var Goroutinewg *sync.WaitGroup
type ConfigWatcher struct {
watcher *fsnotify.Watcher
change chan struct{}
closech chan struct{}
closeWait sync.WaitGroup
}
func NewConfigWatcher() (*ConfigWatcher, error) {
watcher, err := fsnotify.NewWatcher()
if err != nil {
panic(err)
}
change := make(chan struct{})
closech := make(chan struct{})
res := &ConfigWatcher{
change: change,
closech: closech,
}
res.closeWait.Add(1)
TrackedGo(func() {
defer func() {
res.watcher.Close()
close(change)
res.closeWait.Done()
}()
Loop:
for {
select {
case <-watcher.Events:
res.change <- struct{}{}
case err := <-watcher.Errors:
log.Debugf("Error from config watcher: %v", err)
case <-closech:
break Loop
}
}
}, Goroutinewg)
if err := watcher.Add(ConfFile("termshark.toml")); err != nil && !os.IsNotExist(err) {
return nil, err
}
res.watcher = watcher
return res, nil
}
func (c *ConfigWatcher) Close() {
// drain the change channel to ensure the goroutine above can process the close. This
// is safe because I know, at this point, there are no other readers because termshark
// has exited its select loop.
TrackedGo(func() {
// This might block because the goroutine above might not be blocked sending
// to c.change. But then that means the goroutine's for loop above will terminate,
// c.change will be closed, and then this goroutine will end. If the above
// goroutine is blocked sending to c.change, then this will drain that value,
// and again the goroutine above will end.
<-c.change
}, Goroutinewg)
c.closech <- struct{}{}
c.closeWait.Wait()
}
func (c *ConfigWatcher) ConfigChanged() <-chan struct{} {
return c.change
}
//======================================================================
// Local Variables:
// mode: Go
// fill-column: 78
// End: