Making sure go source passes gofmt before committing

Here is a nice little snippet to make sure your go code passes gofmt before committing. Put this in .git/hooks/pre-commit:

set -e
d=`mktemp -d --tmpdir gofmtcheck-XXXXXX`
git checkout-index --prefix "$d/" -a
ret=`find . -regex '.*\.go$' -exec gofmt -d '{}' \;`
if [ ! -z "$ret" ]; then
    echo "Not all go files are well formatted:"
    echo "$ret"
    exit 1

Extra points for the person who extends this to stage the suggestions from gofmt in the index on request!

One Response to “Making sure go source passes gofmt before committing”

  1. Jeff Pedantry Says:

    ret=$(git ls-files ‘*.go’ | xargs gofmt -d)