Skip to content

Instantly share code, notes, and snippets.

@apaatsio
Created May 6, 2022 11:06
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 apaatsio/d70710d076bb65dfdac7fc69bf574037 to your computer and use it in GitHub Desktop.
Save apaatsio/d70710d076bb65dfdac7fc69bf574037 to your computer and use it in GitHub Desktop.
git pre-commit hook for go projects
#!/bin/sh
echo "ℹ️ Running pre-commit hook"
# go to git root
pushd `git rev-parse --show-toplevel` > /dev/null
STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep ".go$")
if [[ "$STAGED_FILES" = "" ]]; then
popd > /dev/null
exit 0
fi
GOFUMPTD_FILES=$(gofumpt -l -w $STAGED_FILES)
if [ -n "$GOFUMPTD_FILES" ];then
echo "⛔️ \x1b[31mFollowing files were gofumpt'd. Please review the changes and stage the files again.\x1b[0m"
echo "$GOFUMPTD_FILES"
else
echo "👌 \x1b[32mAll files are gofumpt'd.\x1b[0m"
fi
echo "ℹ️ Linting..."
LINT_ERRORS_1=$(golangci-lint run --tests=true --fix=true --config .golangci.yaml --build-tags="tags" --new-from-rev="$(git rev-parse HEAD)")
LINT_ERRORS_2=$(golangci-lint run --tests=true --fix=true --config .golangci.yaml --build-tags="tags" --new-from-rev="$(git rev-parse HEAD)")
if [ -n "${LINT_ERRORS_1}" ] || [ -n "${LINT_ERRORS_2}" ]; then
echo "⛔️ \x1b[31mLint errors:\x1b[0m"
echo "${LINT_ERRORS_1}"
echo "${LINT_ERRORS_2}"
popd > /dev/null
exit 1
else
echo "👌 \x1b[32mLint passed.\x1b[0m"
fi
if [ -n "$GOFUMPTD_FILES" ];then
popd > /dev/null
exit 1
fi
popd > /dev/null
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment