Skip to content

Instantly share code, notes, and snippets.

@leucos
Forked from radlinskii/pre-commit.sh
Last active August 29, 2019 08:26
Show Gist options
  • Save leucos/fa7705f5494b356265360da2154f5200 to your computer and use it in GitHub Desktop.
Save leucos/fa7705f5494b356265360da2154f5200 to your computer and use it in GitHub Desktop.
This is a pre-commit hook file for working in Go. Be sure to save this file in your repository as `.git/hooks/pre-commit` and give it right to execute e.g. with command `chmod +x .git/hooks/pre-commit`
#!/bin/bash
STAGED_GO_FILES=$(git diff --cached --name-only -- "\.go$")
if [[ "$STAGED_GO_FILES" = "" ]]; then
exit 0
fi
GOLINT=$GOPATH/bin/golint
GOIMPORTS=$GOPATH/bin/goimports
GOERRCHECK=$GOPATH/bin/errcheck
# Check for golint
if [[ ! -x "$GOLINT" ]]; then
printf "\t\033[41mPlease install golint\033[0m (go get -u golang.org/x/lint/golint)"
exit 1
fi
# Check for goimports
if [[ ! -x "$GOIMPORTS" ]]; then
printf "\t\033[41mPlease install goimports\033[0m (go get golang.org/x/tools/cmd/goimports)"
exit 1
fi
# Check for errcheck
if [[ ! -x "$GOERRCHECK" ]]; then
printf "\t\033[41mPlease install errcheck\033[0m (go get github.com/kisielk/errcheck)"
exit 1
fi
PASS=true
go vet ./...
if [[ $? != 0 ]]; then
printf "\t\033[31mgo vet \033[0m \033[0;30m\033[41mFAILURE!\033[0m\n"
PASS=false
else
printf "\t\033[32mgo vet \033[0m \033[0;30m\033[42mpass\033[0m\n"
fi
for FILE in $STAGED_GO_FILES
do
# Run goimports on the staged file
$GOIMPORTS -w $FILE
# Run golint on the staged file and check the exit status
$GOLINT "-set_exit_status" $FILE
if [[ $? == 1 ]]; then
printf "\t\033[31mgolint $FILE\033[0m \033[0;30m\033[41mFAILURE!\033[0m\n"
PASS=false
else
printf "\t\033[32mgolint $FILE\033[0m \033[0;30m\033[42mpass\033[0m\n"
fi
# Run govet on the staged file and check the exit status
errcheck $FILE
if [[ $? != 0 ]]; then
printf "\t\033[31merrcheck $FILE\033[0m \033[0;30m\033[41mFAILURE!\033[0m\n"
PASS=false
else
printf "\t\033[32merrcheck $FILE\033[0m \033[0;30m\033[42mpass\033[0m\n"
fi
done
if ! $PASS; then
printf "\033[0;30m\033[41mCOMMIT FAILED\033[0m\n"
exit 1
else
printf "\033[0;30m\033[42mCOMMIT SUCCEEDED\033[0m\n"
fi
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment