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:

#!/bin/sh
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
    echo "$ret"
    echo
    exit 1
fi

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

This entry was posted in Uncategorized. Bookmark the permalink.

One Response to Making sure go source passes gofmt before committing

  1. Jeff Pedantry says:

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

Comments are closed.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>