-
Notifications
You must be signed in to change notification settings - Fork 0
/
inotify.go
136 lines (112 loc) · 2.6 KB
/
inotify.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
// Copyright (c) 2013 ActiveState Software Inc. All rights reserved.
package watch
import (
"fmt"
"github.com/ActiveState/tail/util"
"github.com/howeyc/fsnotify"
"gopkg.in/tomb.v1"
"os"
"path/filepath"
)
var inotifyTracker *InotifyTracker
// InotifyFileWatcher uses inotify to monitor file changes.
type InotifyFileWatcher struct {
Filename string
Size int64
}
func NewInotifyFileWatcher(filename string) *InotifyFileWatcher {
fw := &InotifyFileWatcher{filename, 0}
return fw
}
func (fw *InotifyFileWatcher) BlockUntilExists(t *tomb.Tomb) error {
w, err := inotifyTracker.NewWatcher()
if err != nil {
return err
}
defer inotifyTracker.CloseWatcher(w)
dirname := filepath.Dir(fw.Filename)
// Watch for new files to be created in the parent directory.
err = w.WatchFlags(dirname, fsnotify.FSN_CREATE)
if err != nil {
return err
}
// Do a real check now as the file might have been created before
// calling `WatchFlags` above.
if _, err = os.Stat(fw.Filename); !os.IsNotExist(err) {
// file exists, or stat returned an error.
return err
}
for {
select {
case evt, ok := <-w.Event:
if !ok {
return fmt.Errorf("inotify watcher has been closed")
} else if evt.Name == fw.Filename {
return nil
}
case <-t.Dying():
return tomb.ErrDying
}
}
panic("unreachable")
}
func (fw *InotifyFileWatcher) ChangeEvents(t *tomb.Tomb, fi os.FileInfo) *FileChanges {
changes := NewFileChanges()
w, err := inotifyTracker.NewWatcher()
if err != nil {
util.Fatal("Error creating fsnotify watcher: %v", err)
}
err = w.Watch(fw.Filename)
if err != nil {
util.Fatal("Error watching %v: %v", fw.Filename, err)
}
fw.Size = fi.Size()
go func() {
defer inotifyTracker.CloseWatcher(w)
defer changes.Close()
for {
prevSize := fw.Size
var evt *fsnotify.FileEvent
var ok bool
select {
case evt, ok = <-w.Event:
if !ok {
return
}
case <-t.Dying():
return
}
switch {
case evt.IsDelete():
fallthrough
case evt.IsRename():
changes.NotifyDeleted()
return
case evt.IsModify():
fi, err := os.Stat(fw.Filename)
if err != nil {
if os.IsNotExist(err) {
changes.NotifyDeleted()
return
}
// XXX: report this error back to the user
util.Fatal("Failed to stat file %v: %v", fw.Filename, err)
}
fw.Size = fi.Size()
if prevSize > 0 && prevSize > fw.Size {
changes.NotifyTruncated()
} else {
changes.NotifyModified()
}
prevSize = fw.Size
}
}
}()
return changes
}
func Cleanup() {
inotifyTracker.CloseAll()
}
func init() {
inotifyTracker = NewInotifyTracker()
}