Skip to content

Commit

Permalink
watch: move timer into filewatcher
Browse files Browse the repository at this point in the history
So that it can be reset when an event is handled
  • Loading branch information
dnephin committed Oct 17, 2020
1 parent 8cd442a commit 1c19d1b
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 14 deletions.
6 changes: 1 addition & 5 deletions cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
"os/exec"
"os/signal"
"strings"
"time"

"github.com/fatih/color"
"github.com/pkg/errors"
Expand Down Expand Up @@ -43,9 +42,6 @@ func Run(name string, args []string) error {
}

func runWatcher(opts *options) error {
ctx, cancel := context.WithTimeout(context.Background(), time.Hour)
defer cancel()

fn := func(pkg string) error {
opts := *opts
opts.packages = []string{pkg}
Expand All @@ -55,7 +51,7 @@ func runWatcher(opts *options) error {
}
return nil
}
return filewatcher.Watch(ctx, opts.packages, fn)
return filewatcher.Watch(opts.packages, fn)
}

func setupFlags(name string) (*pflag.FlagSet, *options) {
Expand Down
20 changes: 11 additions & 9 deletions internal/filewatcher/watch.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package filewatcher

import (
"context"
"fmt"
"io"
"os"
Expand All @@ -13,7 +12,9 @@ import (
"gotest.tools/gotestsum/log"
)

func Watch(ctx context.Context, dirs []string, run func(pkg string) error) error {
const maxDepth = 7

func Watch(dirs []string, run func(pkg string) error) error {
toWatch := findAllDirs(dirs, maxDepth)
watcher, err := fsnotify.NewWatcher()
if err != nil {
Expand All @@ -28,13 +29,16 @@ func Watch(ctx context.Context, dirs []string, run func(pkg string) error) error
}
}

timer := time.NewTimer(time.Hour)
defer timer.Stop()

h := &handler{last: time.Now(), fn: run}
for {
select {
case <-ctx.Done():
case <-timer.C:
return fmt.Errorf("exceeded idle timeout while watching files")
case event := <-watcher.Events:
log.Debugf("handling event %v", event.String())
log.Debugf("handling event %v", event)

if handleDirCreated(watcher, event) {
continue
Expand All @@ -43,17 +47,13 @@ func Watch(ctx context.Context, dirs []string, run func(pkg string) error) error
if err := h.handleEvent(event); err != nil {
return fmt.Errorf("failed to run tests for %v: %v", event.Name, err)
}
timer.Reset(time.Hour)
case err := <-watcher.Errors:
return fmt.Errorf("failed while watching files: %v", err)
}
}
}

const (
maxDepth = 7
floodThreshold = 250 * time.Millisecond
)

func findAllDirs(dirs []string, depth int) []string {
var output []string

Expand Down Expand Up @@ -155,6 +155,8 @@ type handler struct {
fn func(pkg string) error
}

const floodThreshold = 250 * time.Millisecond

func (h *handler) handleEvent(event fsnotify.Event) error {
if event.Op&fsnotify.Write|fsnotify.Create == 0 {
return nil
Expand Down

0 comments on commit 1c19d1b

Please sign in to comment.