HOME ABOUT CONTACT ARTICLES

Preventing commits to specific branches


Often you want to standerize commit messages, making sure they follow some strucutre.
A classic example is enforcing all commits to contain a Jira ticket. This demo will show
how to enforce a rule where a commit must begin with a Jira Ticket

Steps

1) Create pre-commit file

Create a file named pre-commit in the directory ${repo_folder}/.git/hooks/ like such:

touch ${repo_folder}/.git/hooks/pre-commit


2) Grant execution on the file

To allow Git to be able to execute the script post commit, it will need execution permissions:

chmod +x ${repo_folder}/.git/hooks/pre-commit


3) Write the bash script

This bash script gets the commit from the .git/COMMIT_MSG file and verifies it follows the structure:
[Jira_ticket] [Comment]
Etc, "DevOps-123 This is a test"

#!/bin/sh

check_commit_branch() {
 restricted_braches=(
  "master",
  "develop"
 )
for branch in "${controlled_branches[@]}"; do
  if [[ $(git rev-parse --abbrev-ref HEAD) == "${branch}" ]]; then
   echo -e "\033[0;31m[Error] Can not commit to branch '${branch}'\033[0m"
   echo -e "\033[1;30m[Debug] The branch is a controlled branch, please change branches\033[0m"
   exit 1
  fi
done
}

main() {
 check_commit_branch ""
}

main "$@"


4) Make a test commit

You can verify the image built by running the following command:

luke@nebulae:~$ git commit -m "This is a test with no ticket"
luke@nebulae:~$ git push
Error] Can not commit to branch master
[Debug] The branch is a controlled branch, please change branches