-
Notifications
You must be signed in to change notification settings - Fork 1
/
handlekeeper.go
74 lines (55 loc) · 1.11 KB
/
handlekeeper.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
package handlekeeper
import (
"os"
"path"
fse "github.com/tywkeene/go-fsevents"
)
type Handlekeeper struct {
Handle *os.File
}
func NewHandlekeeper(file string) (*Handlekeeper, error) {
hk := &Handlekeeper{}
if err := hk.openFile(file); err != nil {
return nil, err
}
if err := hk.startInotifyListener(file); err != nil {
return nil, err
}
return hk, nil
}
func (hk *Handlekeeper) openFile(file string) error {
fh, err := os.OpenFile(file, os.O_RDWR|os.O_CREATE, 0644)
if err == nil {
hk.Handle = fh
}
return err
}
func (hk *Handlekeeper) Close() error {
return hk.Handle.Close()
}
func (hk *Handlekeeper) startInotifyListener(file string) error {
w, err := fse.NewWatcher()
if err != nil {
return err
}
_, err = w.AddDescriptor(path.Dir(file), fse.FileRemovedEvent)
if err != nil {
return err
}
if err = w.StartAll(); err != nil {
return err
}
go w.Watch()
go func() {
defer w.StopAll() //nolint:errcheck
for {
event := <-w.Events
if event.IsFileRemoved() && event.Path == file {
if err = hk.openFile(file); err != nil {
break
}
}
}
}()
return nil
}