Verifying a commit message

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


1) Create commit-msg file

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

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

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/commit-msg

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"


# Checks if the commit is in the format:
#  "[JIRA_TICKET] commit message..."
check_commit_msg(commit_msg) {
if ! [[ "${commit_msg}" =~ ^[a-zA-Z]{2,4}-[0-9]{1,5}[[:space:]][A-Za-z0-9]+ ]]; then
  echo -e "\033[0;31m[Error] Commit message does not include Jira ticket at start\033[0m"
  echo -e "\033[1;30m[Debug] Commit must be in format 'XYZ-1234 commit message'\033[0m"
  exit 1

main() {
 commit_msg=$(sed '/^#/ d' .git/COMMIT_EDITMSG)
 check_commit_msg "${commit_msg}"

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] Commit message does not include Jira ticket at start
[Debug] Commit must be in format 'XYZ-1234 commit message