https://www.biosugar0.com/posts/2019/12/pre-commit/
Execute go vet and goimports in git pre-commit
The article describes a script to apply `go vet` which is a static analysis and `goimports` (go fmt) in git's pre-commit hook. When we use the script, we can prevent committing unexpected code.
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.
A script for git pre-commit hook
Edit .git/hooks/pre-commit
in your Golang project as following:
#!/bin/sh
gopackages=$(git diff --cached --name-only --diff-filter=ACM | grep '.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 0
After you completed to edit, grant execute permission to .git/hooks/pre-commit
.
chmod +x .git/hooks/pre-commit
Reference