1
0
mirror of https://github.com/go-task/task.git synced 2025-01-20 04:59:37 +02:00

feat: trigger watched task on new file

Currently, if a task is being watched and a file matching the source glob gets
added, the task is NOT run; the file needs to be *subsequently* modified to
trigger an actual task run. This PR changes this behavior so that the simple act
of adding a file will trigger a task run.
This commit is contained in:
Martin Gignac 2024-09-21 01:10:44 -04:00
parent 96a690ac2f
commit 9b6ca677bd
2 changed files with 23 additions and 3 deletions

View File

@ -90,12 +90,18 @@ func (e *Executor) watchTasks(calls ...*ast.Call) error {
}()
go func() {
// re-register every 5 seconds because we can have new files, but this process is expensive to run
// re-register every "watchInterval" duration because we can have new files, but this process is expensive to run
// need to differentiate between the first scan of the sources and any
// subsequent ones used to catch added files
initialScan := true
for {
if err := e.registerWatchedFiles(w, calls...); err != nil {
if err := e.registerWatchedFiles(w, initialScan, calls...); err != nil {
e.Logger.Errf(logger.Red, "%v\n", err)
}
time.Sleep(watchInterval)
initialScan = false
}
}()
@ -119,7 +125,7 @@ func closeOnInterrupt(w *watcher.Watcher) {
}()
}
func (e *Executor) registerWatchedFiles(w *watcher.Watcher, calls ...*ast.Call) error {
func (e *Executor) registerWatchedFiles(w *watcher.Watcher, initialScan bool, calls ...*ast.Call) error {
watchedFiles := w.WatchedFiles()
var registerTaskFiles func(*ast.Call) error
@ -166,6 +172,13 @@ func (e *Executor) registerWatchedFiles(w *watcher.Watcher, calls ...*ast.Call)
if err := w.Add(absFile); err != nil {
return err
}
if !initialScan {
fileInfo, err := os.Stat(absFile)
if err != nil {
return err
}
w.TriggerEvent(watcher.Create, fileInfo)
}
e.Logger.VerboseOutf(logger.Green, "task: watching new file: %v\n", absFile)
}
}

View File

@ -27,6 +27,8 @@ task: Started watching for tasks: default
task: [default] echo "Hello, World!"
Hello, World!
task: [default] echo "Hello, World!"
Hello, World!
task: [default] echo "Hello, World!"
Hello, World!
`)
@ -72,6 +74,11 @@ Hello, World!
t.Fatal(err)
}
time.Sleep(700 * time.Millisecond)
err = os.WriteFile(filepathext.SmartJoin(dir, "src/b"), []byte("test"), 0644)
if err != nil {
t.Fatal(err)
}
time.Sleep(700 * time.Millisecond)
cancel()
assert.Equal(t, expectedOutput, strings.TrimSpace(buff.String()))
buff.Reset()