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

Perceive how you can setup Git hooks

Picture by Megan Lord on Unsplash
cd <your_git_folder>/.git/hooks
mv pre-commit.pattern pre-commit
chmod +x pre-commit
#!/bin/sh# 1
department=`git department --show-current`
RED='33[0;31m'
NC='33[0m' # No Color
# 2
if [[ "$branch" =~ (master|main) ]]; then
echo "$REDERROR: Commits to $department usually are not allowed$NC" >&2
echo "Please, create a brand new department" >&2
exit 1
else
exit 0
fi
git checkout grasp
git pull
echo "Check pre-commit hook" > check.txt
git add -A
git commit -am "This commit will fail"
cd <your_git_folder>/.git/hooks
mv pre-push.pattern 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 | reduce -d ' ' -f 1 | sed 's/refs/tags///g')
if [ ! -z $tag_name ]; then
# A tag is being pushed, no have to make any checks
exit 0
fi
# 2
main_branch_name=`git symbolic-ref refs/remotes/$distant/HEAD | sed "s@^refs/remotes/$distant/@@"`
# 3
current_branch_name=`git department --show-current`
# 4
commit_log=`git log --format=%B $distant/$main_branch_name..$current_branch_name`
# 5
regex="(PROJ|proj)-[0-9]+"
if [[ ! $commit_log =~ $regex ]]; then
echo "$REDERROR: No JIRA ticket ID was discovered$NC" >&2
echo "Please, embrace a ticket ID in one in all your commits" >&2
exit 1
fi
exit 0
$ git push
ERROR: No JIRA ticket ID was discovered
Please, embrace a ticket ID in one in all your commits

More Posts