Repository navigation
Expand file tree
/
Copy pathwatch.go
More file actions
328 lines (285 loc) · 7.95 KB
/
Copy pathwatch.go
File metadata and controls
328 lines (285 loc) · 7.95 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
package task
import (
"context"
"fmt"
"io/fs"
"os"
"os/signal"
"path/filepath"
"slices"
"strings"
"syscall"
"time"
"github.com/helshabini/fsbroker"
"github.com/puzpuzpuz/xsync/v4"
"github.com/go-task/task/v3/errors"
"github.com/go-task/task/v3/internal/fingerprint"
"github.com/go-task/task/v3/internal/logger"
"github.com/go-task/task/v3/internal/slicesext"
"github.com/go-task/task/v3/taskfile/ast"
)
const defaultWaitTime = 100 * time.Millisecond
// watchTasks start watching the given tasks
func (e *Executor) watchTasks(calls ...*Call) error {
tasks := make([]string, len(calls))
for i, c := range calls {
tasks[i] = c.Task
}
e.Logger.Errf(logger.Green, "task: Started watching for tasks: %s\n", strings.Join(tasks, ", "))
ctx, cancel := context.WithCancel(context.Background())
for _, c := range calls {
go func() {
err := e.RunTask(ctx, c)
if err == nil {
e.Logger.Errf(logger.Green, "task: task \"%s\" finished running\n", c.Task)
} else if !isContextError(err) {
e.Logger.Errf(logger.Red, "%v\n", err)
}
}()
}
var waitTime time.Duration
switch {
case e.Interval != 0:
waitTime = e.Interval
case e.Taskfile.Interval != 0:
waitTime = e.Taskfile.Interval
default:
waitTime = defaultWaitTime
}
config := fsbroker.DefaultFSConfig()
config.Timeout = waitTime
config.IgnoreHiddenFiles = false
broker, err := fsbroker.NewFSBroker(config)
if err != nil {
cancel()
return err
}
defer broker.Stop()
closeOnInterrupt(broker)
e.watchedDirs = xsync.NewMap[string, bool]()
broker.Start()
go func() {
for {
select {
case action, ok := <-broker.Next():
if !ok {
cancel()
return
}
actions := e.filterWatchActions(broker, drainActions(broker, action))
if len(actions) == 0 {
continue
}
files, err := e.collectSources(calls)
if err != nil {
e.Logger.Errf(logger.Red, "%v\n", err)
continue
}
if !slices.ContainsFunc(actions, func(a *fsbroker.FSAction) bool {
return isRelevantWatchAction(a, files)
}) {
for _, a := range actions {
relPath, _ := filepath.Rel(e.Dir, a.Subject.Path)
e.Logger.VerboseErrf(logger.Magenta, "task: skipped for file not in sources: %s\n", relPath)
}
continue
}
cancel()
ctx, cancel = context.WithCancel(context.Background())
e.Compiler.ResetCache()
for _, c := range calls {
go func(ctx context.Context, c *Call) {
err := e.RunTask(ctx, c)
if err == nil {
e.Logger.Errf(logger.Green, "task: task \"%s\" finished running\n", c.Task)
} else if !isContextError(err) {
e.Logger.Errf(logger.Red, "%v\n", err)
}
}(ctx, c)
}
case err, ok := <-broker.Error():
switch {
case !ok:
cancel()
return
default:
e.Logger.Errf(logger.Red, "%v\n", err)
}
}
}
}()
go func() {
// NOTE(@andreynering): New files can be created in directories
// that were previously empty, so we need to check for new dirs
// from time to time.
for {
if err := e.registerWatchedDirs(broker, calls...); err != nil {
e.Logger.Errf(logger.Red, "%v\n", err)
}
time.Sleep(5 * time.Second)
}
}()
<-make(chan struct{})
return nil
}
func isContextError(err error) bool {
if taskRunErr, ok := err.(*errors.TaskRunError); ok {
err = taskRunErr.Err
}
return errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded)
}
func closeOnInterrupt(broker *fsbroker.FSBroker) {
ch := make(chan os.Signal, 1)
signal.Notify(ch, os.Interrupt, syscall.SIGTERM)
go func() {
<-ch
broker.Stop()
os.Exit(0)
}()
}
// drainActions returns the given action along with any other action that is
// already available, so that a burst of changes (e.g. a git checkout) results
// in a single task run instead of one per changed file.
func drainActions(broker *fsbroker.FSBroker, action *fsbroker.FSAction) []*fsbroker.FSAction {
actions := []*fsbroker.FSAction{action}
for {
select {
case next, ok := <-broker.Next():
if !ok {
return actions
}
actions = append(actions, next)
default:
return actions
}
}
}
// filterWatchActions applies the side effects of the given actions and returns
// the ones that are candidates for triggering a task run.
func (e *Executor) filterWatchActions(broker *fsbroker.FSBroker, actions []*fsbroker.FSAction) []*fsbroker.FSAction {
filtered := make([]*fsbroker.FSAction, 0, len(actions))
for _, action := range actions {
if action.Subject == nil || action.Type == fsbroker.NoOp || action.Type == fsbroker.Chmod {
continue
}
e.Logger.VerboseErrf(logger.Magenta, "task: received watch event: %s: %s\n", action.Type, action.Subject.Path)
if action.Type == fsbroker.Remove || action.Type == fsbroker.Rename {
e.watchedDirs.Delete(action.Subject.Path)
if oldPath, ok := action.Properties["OldPath"].(string); ok {
e.watchedDirs.Delete(oldPath)
}
}
if ShouldIgnore(action.Subject.Path) {
e.Logger.VerboseErrf(logger.Magenta, "task: event skipped for being an ignored dir: %s\n", action.Subject.Path)
continue
}
if action.Subject.IsDir() && action.Type != fsbroker.Remove {
if err := e.registerWatchedTree(broker, action.Subject.Path); err != nil {
e.Logger.VerboseErrf(logger.Magenta, "task: failed to watch dir %s: %v\n", action.Subject.Path, err)
}
}
filtered = append(filtered, action)
}
return filtered
}
func isRelevantWatchAction(action *fsbroker.FSAction, files []string) bool {
if action.Subject.IsDir() || action.Type == fsbroker.Remove || action.Type == fsbroker.Rename {
return true
}
return slices.Contains(files, filepath.ToSlash(action.Subject.Path))
}
func (e *Executor) registerWatchedDirs(broker *fsbroker.FSBroker, calls ...*Call) error {
files, err := e.collectSources(calls)
if err != nil {
return err
}
for _, f := range files {
if err := e.registerWatchedDir(broker, filepath.Dir(f)); err != nil {
return err
}
}
return nil
}
func (e *Executor) registerWatchedTree(broker *fsbroker.FSBroker, dir string) error {
return filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error {
if err != nil {
e.Logger.VerboseErrf(logger.Magenta, "task: failed to walk dir %s: %v\n", path, err)
return filepath.SkipDir
}
if !d.IsDir() {
return nil
}
if ShouldIgnore(path) {
return filepath.SkipDir
}
return e.registerWatchedDir(broker, path)
})
}
func (e *Executor) registerWatchedDir(broker *fsbroker.FSBroker, d string) error {
if isSet, ok := e.watchedDirs.Load(d); ok && isSet {
return nil
}
if ShouldIgnore(d) {
return nil
}
if err := broker.AddWatch(d); err != nil {
return err
}
e.watchedDirs.Store(d, true)
relPath, _ := filepath.Rel(e.Dir, d)
e.Logger.VerboseOutf(logger.Green, "task: watching new dir: %v\n", relPath)
return nil
}
var ignorePaths = []string{
"/.task",
"/.git",
"/.hg",
"/node_modules",
}
func ShouldIgnore(path string) bool {
for _, p := range ignorePaths {
if strings.Contains(path, fmt.Sprintf("%s/", p)) || strings.HasSuffix(path, p) {
return true
}
}
return false
}
func (e *Executor) collectSources(calls []*Call) ([]string, error) {
var sources []string
err := e.traverse(calls, func(task *ast.Task) error {
files, err := fingerprint.Globs(task.Dir, task.Sources, task.ShouldUseGitignore())
if err != nil {
return err
}
sources = append(sources, files...)
return nil
})
return slicesext.UniqueJoin(sources), err
}
type traverseFunc func(*ast.Task) error
func (e *Executor) traverse(calls []*Call, yield traverseFunc) error {
for _, c := range calls {
task, err := e.CompiledTask(c)
if err != nil {
return err
}
for _, dep := range task.Deps {
if dep.Task != "" {
if err := e.traverse([]*Call{{Task: dep.Task, Vars: dep.Vars}}, yield); err != nil {
return err
}
}
}
for _, cmd := range task.Cmds {
if cmd.Task != "" {
if err := e.traverse([]*Call{{Task: cmd.Task, Vars: cmd.Vars}}, yield); err != nil {
return err
}
}
}
if err := yield(task); err != nil {
return err
}
}
return nil
}