-
Notifications
You must be signed in to change notification settings - Fork 103
/
watcher.go
86 lines (74 loc) · 2.33 KB
/
watcher.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
package server
import (
"fmt"
"os"
"path/filepath"
"github.com/fsnotify/fsnotify"
)
// Watcher is a structure to watch a file for changes and notify a channel.
type Watcher struct {
path string
fileChanges chan bool
}
// NewWatcher instantiates a new watcher with the provided filename and changes
// channel.
func NewWatcher(filename string, fileChanges chan bool) *Watcher {
return &Watcher{
path: filepath.FromSlash(filename),
fileChanges: fileChanges,
}
}
// Run starts the file watcher in a blocking fashion. This watches an entire
// directory and only notifies the channel when the specified file is changed.
// If there is an error, it's returned. It's up to the caller to respawn the
// watcher if it's desireable to keep watching.
//
// The reason it watches a directory is becausde some editors like VIM write
// to a swap file and recreate the original file. So we can't simply watch the
// original file, we have to watch the directory. This is also why we check both
// the WRITE and CREATE events since VIM will write to a swap and then create
// the file on save. VSCode does a WRITE and then a CHMOD, so tracking WRITE
// catches the changes for VSCode exactly once.
func (w *Watcher) Run() error {
// check if path exists, and whether it is a directory or a file
info, err := os.Stat(w.path)
if err != nil {
return fmt.Errorf("stat'ing %s: %w", w.path, err)
}
isDir := info.IsDir()
watcher, err := fsnotify.NewWatcher()
if err != nil {
return fmt.Errorf("watching for changes: %w", err)
}
defer watcher.Close()
if isDir {
watcher.Add(w.path)
} else {
watcher.Add(filepath.Dir(w.path))
}
for {
select {
case event, ok := <-watcher.Events:
if !ok {
return fmt.Errorf("watcher events channel closed unexpectedly")
}
if !isDir && event.Name != w.path {
// if we're watching a single file, ignore changes to other files
continue
}
if shouldNotify(event.Op) {
w.fileChanges <- true
}
case err, ok := <-watcher.Errors:
if !ok {
return fmt.Errorf("watcher errors channel closed unexpectedly")
}
return fmt.Errorf("watcher: %w", err)
}
}
}
func shouldNotify(op fsnotify.Op) bool {
// notify on all ops except for chmod, since that is discouraged
// in the fsnotify docs.
return op.Has(fsnotify.Write | fsnotify.Create | fsnotify.Remove | fsnotify.Rename)
}