forked from xiam/luminos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
90 lines (78 loc) · 1.47 KB
/
main.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
package watcher
import (
"os"
"time"
)
/*
This is a stupid file modification watcher, I expect to use fsnotify once it
becomes consistent among all platforms.
*/
type Event struct {
Name string
// I don't really need any other event besides modification.
isModify bool
}
type Watcher struct {
Files map[string]*WatcherFile
Event chan (*Event)
t time.Duration
watching bool
}
type WatcherFile struct {
Filemtime time.Time
}
func (self *Event) IsModify() bool {
if self.isModify == true {
self.isModify = false
return true
}
return false
}
func (self *Watcher) RemoveWatch(file string) error {
delete(self.Files, file)
return nil
}
func (self *Watcher) Watch(file string) error {
stat, err := os.Stat(file)
if err != nil {
return err
}
wf := &WatcherFile{
Filemtime: stat.ModTime(),
}
self.Files[file] = wf
return nil
}
func (self *Watcher) check() {
for name, w := range self.Files {
stat, err := os.Stat(name)
if err == nil {
mtime := stat.ModTime()
if mtime != w.Filemtime {
ev := &Event{
Name: name,
isModify: true,
}
w.Filemtime = mtime
self.Event <- ev
}
}
}
}
func (self *Watcher) Close() {
self.watching = false
}
func New() (*Watcher, error) {
self := &Watcher{}
self.t = time.Millisecond * 500
self.Event = make(chan *Event)
self.watching = true
self.Files = make(map[string]*WatcherFile)
go func() {
for self.watching {
self.check()
time.Sleep(self.t)
}
}()
return self, nil
}