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
|
package main
// File watching.
//
// We watch the *directory*, not the file. Editors save by writing a temporary
// file and renaming it over the target, which replaces the inode; a watch on the
// file itself follows the old inode and goes silent after the first save.
//
// Changes are debounced because a single save can produce several events
// (CREATE + WRITE + RENAME + CHMOD), and re-solving on each would start work we
// immediately throw away.
import (
"log"
"path/filepath"
"time"
"github.com/fsnotify/fsnotify"
)
// debounceInterval is how long to wait for the event storm of one save to
// settle. Long enough to coalesce an editor's write+rename, short enough to feel
// immediate.
const debounceInterval = 150 * time.Millisecond
// watchFile calls onChange after the file at path (or its theme sibling) is
// modified. It blocks until the watcher fails.
func watchFile(path string, onChange func()) error {
w, err := fsnotify.NewWatcher()
if err != nil {
return err
}
defer w.Close()
dir := filepath.Dir(path)
if err := w.Add(dir); err != nil {
return err
}
log.Printf("watching %s", dir)
// Editing the theme should re-render too, and it is a sibling of the model.
stem := path[:len(path)-len(filepath.Ext(path))]
themePath := stem + ".thm"
var timer *time.Timer
for {
select {
case ev, ok := <-w.Events:
if !ok {
return nil
}
// Ignore CHMOD-only events: some editors touch permissions without
// changing content, and re-solving on that is pure waste.
if ev.Op == fsnotify.Chmod {
continue
}
if ev.Name != path && ev.Name != themePath {
continue
}
if timer != nil {
timer.Stop()
}
timer = time.AfterFunc(debounceInterval, onChange)
case err, ok := <-w.Errors:
if !ok {
return nil
}
log.Printf("watcher: %v", err)
}
}
}
|