Automatically run your package’s tests with inotifywait

This is a short post to illustrate how I use the inotifywait command as a cheap and cheerful way to run my tests automatically on save.

Note: inotify is only available on linux, sorry OS X users.

Step 1. Install inotify-tools

On Debian/Ubuntu, inotifywait and friends live in the inotify-tools package.

% sudo apt-get install inotify-tools

If you live in an RPM universe the package name will hopefully be similar.

Step 2. Create a helper function

Remembering the full inotifywait incantation can be taxing, so save yourself some effort and define a function in .bashrc (or your shell of choice’s startup script).

watch() { while inotifywait --exclude .swp -e modify -r .; do $@; done; }

If you use /usr/bin/watch frequently, you might want to pick another name for this function.

Step 3. Run a command on save

Using tmux (you do use tmux, right?), split the window and run

% watch go test .

Any time that a file in the current working directory is modified, inotifywait will return, which runs the command you provided, then loops back around.

watch will trigger on a modification to anything in the current working directory or below it. The command that runs when inotifywait detects a modification can be anything you like. For example you could be working in one package inside your project, and have watch rebuild all the commands any time you save, like this:

% cd $GOPATH/src/github.com/you/yourproject/pkg/pkg/pkg
% watch go install -v github/com/you/yourproject/cmd/...