Created
February 26, 2016 12:52
-
-
Save bierbaum/65660bdc917eed1e7e6d to your computer and use it in GitHub Desktop.
A `gofmt` pre-commit hook that does what you want
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
test -z "$GIT_HOOK_NO_GOFMT" || exit 0 | |
function die { | |
echo "FATAL: $@" 1>&2 | |
exit 128 | |
} | |
files="" | |
hash gofmt 2>&- || { echo >&2 "gofmt not in PATH."; exit 1; } | |
IFS=' | |
' | |
for file in `git diff --cached --name-only --diff-filter=ACM | grep '\.go$'`; do | |
output=`git cat-file -p :$file | gofmt -l 2>&1` | |
if test $? -ne 0; then | |
output=`echo "$output" | sed "s,<standard input>,$file,"` | |
syntaxerrors="${list}${output}\n" | |
elif test -n "$output"; then | |
files+="$file" | |
list="${list}${file}\n" | |
fi | |
done | |
exitcode=0 | |
if test -n "$syntaxerrors"; then | |
echo >&2 "gofmt found syntax errors:" | |
printf "$syntaxerrors" | |
exitcode=1 | |
fi | |
if test -n "$list"; then | |
echo >&2 "gofmt will format these files: $files" | |
for f in "$files"; do | |
set -x | |
gofmt -w $f || die "gofmt $f failed" | |
git add $f || die "git add $f failed" | |
done | |
fi | |
exit $exitcode |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment