Skip to content

Instantly share code, notes, and snippets.

@illia-danko
Last active March 6, 2019 00:29
Show Gist options
  • Save illia-danko/dcd8d0b8e1f686860c7b9f9a081bf422 to your computer and use it in GitHub Desktop.
Save illia-danko/dcd8d0b8e1f686860c7b9f9a081bf422 to your computer and use it in GitHub Desktop.
golang pre-commit hook
#!/bin/sh
#
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
#
# To use, store as .git/hooks/pre-commit inside your repository and make sure
# it has execute permissions.
#
# This script does not handle file names that contain spaces.
# The script is adopted version of
# https://gist.github.com/tamas-molnar/b76f7cc64902dbcf10f2
# The main aim is to use docker for CI/CD by running go test inside a docker.
# In addition, this script triggers gofmt and golint tools to make the Gowish
# flow.
# go-commit.sh script builds and runs project inside a docker container.
if [ -f ./go-commit.sh ] ; then
run_result=$(sh ./go-commit.sh)
run_rc=$?
if [ $run_rc -ne 0 ] ; then
echo "git pre-commit check failed: ./go-commit.sh has been failed:\n$run_result"
exit 1
fi
else
# build project
build_result=$(go build)
build_rc=$?
if [ $build_rc -ne 0 ] ; then
echo "git pre-commit check failed: build failed."
exit 1
fi
# run tests
failed_tests="$(go test ./... | grep "FAIL:" | awk '{print $3}')"
if test -n "$failed_tests" ; then
for failed in $failed_tests; do
echo "git pre-commit check failed: test failed: $failed"
done
exit 1
fi
fi
# golint
lint_results="$(golint)"
if test -n "$lint_results" ; then
echo "Lint: \n$lint_results"
exit 1
fi
# gofmt
gofiles=$(git diff --cached --name-only --diff-filter=ACM | grep '.go$')
[ -z "$gofiles" ] && exit 0
unformatted=$(gofmt -l $gofiles)
[ -z "$unformatted" ] && exit 0
# Some files are not gofmt'd. Print message and fail.
echo >&2 "Go files must be formatted with gofmt. Please run:"
for fn in $unformatted; do
echo >&2 " gofmt -w $PWD/$fn"
done
exit 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment