Repository navigation
Expand file tree
/
Copy pathwatch.go
More file actions
86 lines (71 loc) · 1.83 KB
/
Copy pathwatch.go
File metadata and controls
86 lines (71 loc) · 1.83 KB
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 watch provides verless' ability to watch a project
// and react to changes in a verless project.
package core
import (
"path/filepath"
"strings"
"time"
"github.com/radovskyb/watcher"
"github.com/verless/verless/out"
"github.com/verless/verless/out/style"
)
// watchContext provides all components required for serving an already built project.
type watchContext struct {
Path string
IgnorePaths []string
ChangedCh chan<- string
StopCh <-chan bool
}
// watch watches a verless project for changes and writes the changed
// files to the passed watchContext.ChangedCh channel.
// To stop the watcher just close the watchContext.StopCh channel.
// watchContext.IgnorePath can be used to ignore a path inside the given watchContext.Path.
func watch(ctx watchContext) error {
w := watcher.New()
w.FilterOps(watcher.Write, watcher.Create, watcher.Move, watcher.Remove, watcher.Rename)
go func() {
watcherLoop:
for {
select {
case event, ok := <-w.Event:
if !ok {
return
}
if filepath.Ext(event.Path) == "" {
continue
}
for _, ignorePath := range ctx.IgnorePaths {
p, err := filepath.Abs(ignorePath)
if err != nil {
out.Err(style.Exclamation, "failed to read ignored filepath: %s", err.Error())
continue
}
if strings.HasPrefix(event.Path, p) {
continue watcherLoop
}
}
ctx.ChangedCh <- event.Path
case err, ok := <-w.Error:
if !ok {
return
}
out.Err(style.Exclamation, "failed to watch project files: %s", err.Error())
case _, ok := <-ctx.StopCh:
if !ok {
w.Close()
}
}
}
}()
if err := w.AddRecursive(ctx.Path); err != nil {
return err
}
if err := w.Ignore(ctx.IgnorePaths...); err != nil {
return err
}
var err error
go func() {
err = w.Start(time.Millisecond * 100)
}()
return err
}