forked from markbates/refresh
-
Notifications
You must be signed in to change notification settings - Fork 0
/
watcher.go
92 lines (79 loc) · 1.61 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
87
88
89
90
91
92
package refresh
import (
"context"
"errors"
"os"
"path/filepath"
"strings"
"time"
"github.com/volatiletech/refresh/v3/filenotify"
)
type Watcher struct {
filenotify.FileWatcher
*Manager
context context.Context
}
func NewWatcher(r *Manager) *Watcher {
var watcher filenotify.FileWatcher
if r.ForcePolling {
watcher = filenotify.NewPollingWatcher()
} else {
watcher, _ = filenotify.NewEventWatcher()
}
return &Watcher{
FileWatcher: watcher,
Manager: r,
context: r.context,
}
}
func (w *Watcher) Start() {
go func() {
for {
err := filepath.Walk(w.AppRoot, func(path string, info os.FileInfo, err error) error {
if info == nil {
w.cancelFunc()
return errors.New("nil directory")
}
if info.IsDir() {
if strings.HasPrefix(filepath.Base(path), "_") {
return filepath.SkipDir
}
if len(path) > 1 && strings.HasPrefix(filepath.Base(path), ".") || w.isIgnoredFolder(path) {
return filepath.SkipDir
}
}
if w.isWatchedFile(path) {
w.Add(path)
}
return nil
})
if err != nil {
w.context.Done()
break
}
// sweep for new files every 1 second
time.Sleep(1 * time.Second)
}
}()
}
func (w Watcher) isIgnoredFolder(path string) bool {
paths := strings.Split(path, "/")
if len(paths) <= 0 {
return false
}
for _, e := range w.IgnoredFolders {
if strings.TrimSpace(e) == paths[0] {
return true
}
}
return false
}
func (w Watcher) isWatchedFile(path string) bool {
ext := filepath.Ext(path)
for _, e := range w.IncludedExtensions {
if strings.TrimSpace(e) == ext {
return true
}
}
return false
}