go-watchexec is a simple command-line tool that watches a directory for file changes and executes a command in response.
go install github.com/myaaaaaaaaa/go-watchexec/watchexec@latest- Command Execution: Execute a given command whenever a file is changed.
- Unix-style Modularity: Streams modified filenames (line-by-line) to
stdoutwhen the output is piped or redirected. This allowsgo-watchexecto be used as a file change event source in a command-line pipeline.
go-watchexec has two main modes of operation.
Pass a command as an argument to have it automatically re-run on any file change.
Syntax:
watchexec [command]Examples:
# Re-run Go tests on any file change
watchexec go test ./...If you pipe or redirect the output, go-watchexec enters streaming mode. Instead of running a command, it prints the path of each modified file to stdout on a new line. This allows you to compose go-watchexec with other command-line tools for more complex workflows.
Example:
A common use case is to pipe the stream of changed files to xargs to perform an action on each file. The following example reports the line count of only the Go files that have changed:
# Get the line count of each changed Go file
watchexec | grep '\.go$' | xargs -n1 wc -lIn this pipeline:
watchexecprints every modified file path to standard output.grep '\.go$'filters this stream to only include files ending in.go.xargs -n1 wc -lreceives the filtered paths and runswc -lon each one individually.
This tool uses a polling-based mechanism to watch for file changes, as opposed to relying on OS-specific filesystem notification events (like Linux's inotify).
- The watcher periodically scans the directory tree to get a list of all files.
- It then iterates through the files, checking the "last modified" timestamp of each one.
- If a timestamp is newer than the last one seen, it triggers the specified command.
Benefits of this approach:
- Portability: It works on any operating system that Go supports without any extra dependencies. It does not rely on OS-specific APIs, making it universally compatible.
- Filesystem Support: It functions reliably across a wide variety of filesystems, including network filesystems (NFS, Samba), where event-based watchers can be unreliable.
- Simplicity: The polling approach provides robust and straightforward recursive directory monitoring. It automatically handles newly created directories without the complexity of adding new filesystem-level watches.
This design choice prioritizes portability and simplicity, ensuring that go-watchexec works consistently everywhere.
To improve responsiveness, especially in large projects, the poller prioritizes files that have been modified recently. It maintains a short list of these "likely editing" files, which are checked for changes on every polling cycle. This ensures that modifications to files you are actively working on are detected almost instantly, avoiding the potential lag of a full scan across the entire directory.