package watcher
import "github.com/amonks/run/internal/watcher"
Package watcher provides file system watching with debouncing and glob matching. It also provides mock support for testing.
Index
- Variables
- func Debounce(dur time.Duration, c <-chan EventInfo) <-chan []EventInfo
- func Dispatch(path string, evs ...EventInfo)
- func Mock() func()
- func Split(input string) (string, glob.Glob)
- type EventInfo
Variables
var Watch = func(inputPath string) (<-chan []EventInfo, func(), error) { var stopped bool cwd, err := os.Getwd() if err != nil { return nil, nil, err } watchPath, globToMatch := Split(inputPath) c := make(chan notify.EventInfo, 1) out := make(chan EventInfo) go func() { for ev := range c { p := strings.TrimPrefix(ev.Path(), cwd+"/") if globToMatch == nil || globToMatch.Match(p) { out <- EventInfo{ Path: p, Event: strings.TrimPrefix(ev.Event().String(), "notify."), } } } close(out) }() stop := func() { if stopped { return } stopped = true notify.Stop(c) close(c) } if err := notify.Watch(watchPath, c, notify.All); err != nil { stop() } return Debounce(500*time.Millisecond, out), stop, nil }
Watch observes the file system at inputPath and returns a channel of debounced events, a stop function, and any error. The inputPath may contain glob patterns (e.g., "src/website/**/*.js").
Watch is a package-level function variable to allow replacement for testing via Mock.
Functions
func Debounce
func Debounce(dur time.Duration, c <-chan EventInfo) <-chan []EventInfo
Debounce collects events from c and emits them as batches after dur of inactivity.
func Dispatch
func Dispatch(path string, evs ...EventInfo)
Dispatch sends synthetic events to the mock watcher for the given path. The path must match the inputPath previously passed to Watch.
func Mock
func Mock() func()
Mock replaces Watch with an implementation that captures calls and allows synthetic events via Dispatch. It returns a restore function that must be called to reinstate the real Watch.
func Split
func Split(input string) (string, glob.Glob)
Split breaks a given input path (which may contain a glob) into two parts: a watch path suitable for the file system watcher and an optional glob for filtering events.
For example, given the input "src/website/**/*.js",
- we will set up a recursive watch at src/website
- we will match events against the glob "src/website/**/*.js"
so the values returned are ("src/website/...", Glob["src/website/**/*.js"]).
Types
type EventInfo
type EventInfo struct { Path string Event string }
EventInfo describes a single file system event.