Writing a pre-commit git hook for Go files.

Ignacy Radliński
Sep 27, 2018 · 8 min read

TL;DR you can check out my pre-commit hook for go files here.

Getting started

$ mkdir $GOPATH/src/precommit
$ cd $GOPATH/src/precommit
$ git init

git hooks

$ touch .git/hooks/pre-commit
$ chmod +x .git/hooks/pre-commit
#!/bin/sh
STAGED_GO_FILES=$(git diff --cached --name-only | grep ".go$")
STAGED_GO_FILES=$(git diff --cached --name-only | grep ".go$")if [[ "$STAGED_GO_FILES" = "" ]]; then
exit 0
fi

Quick test

#!/bin/shSTAGED_GO_FILES=$(git diff --cached --name-only | grep ".go$")if [[ "$STAGED_GO_FILES" = "" ]]; then
echo "no go files were stashed"
exit 0
fi
echo "found some interesting files!"
exit 1
$ touch test.go
$ git add test.go

Finding the right tools

gofmt and goimports

golint

go vet

Implementing the solution

PASS=truefor FILE in $STAGED_GO_FILES
do
# This is where we will be testing each of our files.
doneif ! PASS; then
printf "COMMIT FAILED\n"
exit 1
else
printf "COMMIT SUCCEEDED\n"
fi
exit 0

goimports

$ go get golang.org/x/tools/cmd/goimports
goimports -w $FILE

golint

go get -u golang.org/x/lint/golint
golint "-set_exit_status" $FILE
if [[ $? == 1 ]]; then
PASS=false
fi

govet

go vet $FILE
if [[ $? != 0]]; then
PASS=false
fi

Conclusion

pre-commit hook for go files using goimports, golint, and go vet

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade