Skip to content

Instantly share code, notes, and snippets.

@SpandanBG
Last active September 12, 2023 18:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SpandanBG/978f03d9d6a0197ebe51562d9ebf3cd7 to your computer and use it in GitHub Desktop.
Save SpandanBG/978f03d9d6a0197ebe51562d9ebf3cd7 to your computer and use it in GitHub Desktop.
golang fmt and test coverage git pre-commit hook
#!/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
@SpandanBG
Copy link
Author

Make sure you have awk present on your system

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment