Last active
September 12, 2023 18:50
-
-
Save SpandanBG/978f03d9d6a0197ebe51562d9ebf3cd7 to your computer and use it in GitHub Desktop.
golang fmt and test coverage git pre-commit hook
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
# Format Go code | |
gofiles=$(find . -name "*.go" | tr '\n' ' ') | |
[ -z "$gofiles" ] && exit 0 | |
unformatted=$(gofmt -l $gofiles) | |
if [ -z "$unformatted" ]; then | |
echo "All Go files are formatted correctly." | |
else | |
echo >&2 "Go files are not formatted:" | |
echo >&2 "$unformatted" | |
exit 1 | |
fi | |
# Run Go tests and check coverage | |
if ! go test -cover ./... ; then | |
echo "Go tests failed, aborting commit" | |
exit 1 | |
fi | |
# Check that coverage is above a certain threshold | |
COVERAGE=$(go test -cover ./... | grep -Eo 'coverage: [0-9]+\.[0-9]+' | sed 's/coverage: //g' | awk '{total+=$1; count+=1} END {print total/count}') | |
TARGET_COVERAGE=80.0 | |
if awk -v n1="$COVERAGE" -v n2="$TARGET_COVERAGE" 'BEGIN { exit !(n1 < n2) }'; then | |
echo "Code coverage is too low ($COVERAGE%). Target is $TARGET_COVERAGE%, aborting commit." | |
exit 1 | |
fi | |
# If we reached here, then all tests passed, code is formatted, and coverage is sufficient | |
exit 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Make sure you have
awk
present on your system