Enforce Your Team’s Code-style With Git Hooks | by Fernando Moya de Rivas | Mar, 2022

Understand how to setup Git hooks

Fernando Moya de Rivas
Photo by Megan Lord on Unsplash
cd <your_git_folder>/.git/hooks
mv pre-commit.sample pre-commit
chmod +x pre-commit
#!/bin/sh# 1
branch=`git branch --show-current`
RED='33[0;31m'
NC='33[0m' # No Color
# 2
if [[ "$branch" =~ (master|main) ]]; then
echo "${RED}ERROR: Commits to $branch are not allowed${NC}" >&2
echo "Please, create a new branch" >&2
exit 1
else
exit 0
fi
git checkout master
git pull
echo "Test pre-commit hook" > test.txt
git add -A
git commit -am "This commit will fail"
cd <your_git_folder>/.git/hooks
mv pre-push.sample pre-push
chmod +x pre-push
#!/bin/shRED='33[0;31m'
NC='33[0m' # No Color
remote=$1# 1
tag_name=$(grep -E 'refs/tags/([^ ]*) ' </dev/stdin | cut -d ' ' -f 1 | sed 's/refs/tags///g')
if [ ! -z $tag_name ]; then
# A tag is being pushed, no need to make any checks
exit 0
fi
# 2
main_branch_name=`git symbolic-ref refs/remotes/$remote/HEAD | sed "s@^refs/remotes/$remote/@@"`
# 3
current_branch_name=`git branch --show-current`
# 4
commit_log=`git log --format=%B $remote/$main_branch_name..$current_branch_name`
# 5
regex="(PROJ|proj)-[0-9]+"
if [[ ! $commit_log =~ $regex ]]; then
echo "${RED}ERROR: No JIRA ticket ID was found${NC}" >&2
echo "Please, include a ticket ID in one of your commits" >&2
exit 1
fi
exit 0
$ git push
ERROR: No JIRA ticket ID was found
Please, include a ticket ID in one of your commits

Leave a Comment