When team members wrote Golang code, they would commit corrupted formatting or with code mixed in that was deemed undesirable by static analysis.
So we should use a script to apply
go vet which is static analysis and
goimports (go fmt) in git pre-commit hook.
.git/hooks/pre-commit in your Golang project as following:
'.go$'| xargs -n1 dirname| sort -u| sed 's/^/.\//' ) [ -z "$gopackages" ] && exit 0 echo "Info: git diff (go packages)" echo $gopackages echo "Info: Runnning go vet" linterr="$(go vet $gopackages 2>&1 )" if [ -n "$linterr" ] ; then echo "fatal:" echo $linterr exit 1 fi echo "Info: go vet -> OK" unformatted=$(goimports -l $gopackages 2>&1 ) if [ -n "$unformatted" ] ; then echo "Info: unformatted file: $unformatted" echo "Info: Running goimports" for fn in $unformatted; do goimports -w $fn echo >&2 "goimports -w $fn" git add $fn done fi echo "Info: goinports -> OK" exit 0gopackages=$(git diff --cached --name-only --diff-filter=ACM | grep
After you completed to edit, grant execute permission to
chmod +x .git/hooks/pre-commit