-
Notifications
You must be signed in to change notification settings - Fork 0
/
watch.go
84 lines (75 loc) · 1.75 KB
/
watch.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
package main
import (
"context"
"fmt"
"log"
"os"
"path/filepath"
"strings"
"gopkg.in/fsnotify.v1"
)
// watch watches for changes starting at the root directory. Changes are passed to
// the returned channel.
func watch(ctx context.Context, root string) (<-chan string, error) {
if root == "" {
root = "."
}
watcher, err := fsnotify.NewWatcher()
if err != nil {
return nil, fmt.Errorf("watcher: %w", err)
}
ch := make(chan string, 1)
go func() {
defer watcher.Close()
for {
select {
case event := <-watcher.Events:
switch {
case event.Op&fsnotify.Create == fsnotify.Create:
if err := watchAll(watcher, event.Name); err != nil {
log.Print(err)
}
case event.Op&fsnotify.Remove == fsnotify.Remove:
case event.Op&fsnotify.Write == fsnotify.Write:
case event.Op&fsnotify.Rename == fsnotify.Rename:
default:
// Ignore other events.
continue
}
if !strings.HasSuffix(event.Name, ".go") {
break
}
ch <- event.Name
case err := <-watcher.Errors:
log.Print(err)
case <-ctx.Done():
return
}
}
}()
err = watchAll(watcher, root)
return ch, err
}
// watchAll adds path and all of its child directories to the watch list.
func watchAll(watcher *fsnotify.Watcher, path string) error {
return filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
// Apply filters.
// TODO: Make this configurable.
if info.IsDir() {
if filepath.Base(path) == "node_modules" {
return filepath.SkipDir
}
if filepath.Base(path) == ".git" {
return filepath.SkipDir
}
if err := watcher.Add(path); err != nil {
return fmt.Errorf("watcher: %w", err)
}
fmt.Println("Watching:", path)
}
return nil
})
}