Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: trigger watched task on new file #1828

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 16 additions & 3 deletions watch.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}()

Expand All @@ -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
Expand Down Expand Up @@ -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)
}
}
Expand Down
7 changes: 7 additions & 0 deletions watch_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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!
`)

Expand Down Expand Up @@ -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()
Expand Down