From 9b6ca677bd5bcce1c456f759556ae106400e7cbf Mon Sep 17 00:00:00 2001 From: Martin Gignac Date: Sat, 21 Sep 2024 01:10:44 -0400 Subject: [PATCH] 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. --- watch.go | 19 ++++++++++++++++--- watch_test.go | 7 +++++++ 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/watch.go b/watch.go index 5ce5f7ee37..db4db5903b 100644 --- a/watch.go +++ b/watch.go @@ -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) } } diff --git a/watch_test.go b/watch_test.go index f1fb6a218d..a5e482f529 100644 --- a/watch_test.go +++ b/watch_test.go @@ -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()