Skip to content

Commit

Permalink
fix: Allow add/remove watcher dirs before start
Browse files Browse the repository at this point in the history
  • Loading branch information
romshark committed Aug 6, 2024
1 parent 56795fc commit 9faba74
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
17 changes: 15 additions & 2 deletions internal/watcher/watcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,12 +69,26 @@ var (
ErrRunning = errors.New("watcher is already running")
)

// WaitRunning blocks and returns once the watcher is running.
// Returns immediately if the watcher is closed or running.
func (w *Watcher) WaitRunning() {
w.lock.Lock()
state := w.state
w.lock.Unlock()

if state == stateClosed {
return
}

w.runnerStart.Wait()
}

// RangeWatchedDirs calls fn for every currently watched directory.
// Noop if the watcher is closed.
func (w *Watcher) RangeWatchedDirs(fn func(path string) (continueIter bool)) {
w.lock.Lock()
defer w.lock.Unlock()
if w.state != stateRunning || w.state == stateClosed {
if w.state == stateClosed {
return
}
for p := range w.watchedDirs {
Expand Down Expand Up @@ -285,7 +299,6 @@ var errStopTraversal = errors.New("stop recursive traversal")
// Remove stops watching the directory and all of its subdirectories recursively.
// Returns ErrClosed if the watcher is already closed or not running.
func (w *Watcher) Remove(dir string) error {
w.runnerStart.Wait() // Wait for the runner to start
w.lock.Lock()
defer w.lock.Unlock()
if w.state == stateClosed {
Expand Down
4 changes: 3 additions & 1 deletion internal/watcher/watcher_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,7 @@ func TestWatcherRunCancelContext(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
go func() { chErr <- w.Run(ctx) }()
require.NoError(t, w.Add(base))
w.WaitRunning()

ExpectWatched(t, w, []string{base})

Expand Down Expand Up @@ -337,7 +338,7 @@ func runNewWatcher(
wg.Add(1)
t.Cleanup(func() {
require.NoError(t, w.Close())
wg.Wait()
wg.Wait() // Wait until the runner stops
})
go func() {
defer wg.Done()
Expand All @@ -347,6 +348,7 @@ func runNewWatcher(
}
panic(err)
}()
w.WaitRunning()
return w
}

Expand Down

0 comments on commit 9faba74

Please sign in to comment.