Use for whatever you like: http://gist.github.com/260411
AFAIK, the codereview extension in the Go tree already has the
functionality of guaranteeing all CL sources to be gofmt'ed prior to
upload.
Looks like it does. Hadn't noticed that before. And now I know that
the idiomatic way of checking if a file needs gofmt is running "gofmt -
l" instead of diffing the gofmt output with the original file like my
script does. Still, the codereview extension seems pretty Mercurial-
centric, while my script has some Git-specific logic, so mine may
still be useful for people who have Go stuff in Git.
To use this, put this in the file .git/hooks/pre-commit and make it executable.
#!/bin/sh
status=0
for file in $(git diff --cached --name-only | grep -e '\.go$'); do
badfile=$(gofmt -l $file)
if test -n "$badfile" ; then
echo "git pre-commit check failed: file needs gofmt: $badfile"
status=1
fi
done
exit $status
Excellent tip (your suspicion was correct). For the sake of internet
posterity, here's the corrected script. To use this, put this in the
file .git/hooks/pre-commit and make it executable.
#!/bin/sh
status=0
IFS=$'\n'
Doesn't this check the working directory instead of the staging area?
Meaning that if you gofmt a file going in the commit in the working
dir but don't "git add" it after the formatting, the check will pass,
but an un-goformatted file from the staging area will be committed?
Having found this useful little script, I thought I would just post
back the slightly tweaked version that I am actually using which also
checks the initial commit:
#!/bin/sh
status=0
IFS=$'\n'
if git rev-parse HEAD >/dev/null 2>&1; then
FILES=$(git diff --cached --name-only | grep -e '\.go$');
else
FILES=$(git ls-files -c | grep -e '\.go$');
fi
for file in $FILES; do