Git Hook – Commit message

Within my company there is a rule to always make sure you have the story number of Jira in the commit message. I forgot to do this so many times… and it’s a tedious job to do every single time. Surely there must be a automatic way to do this…. and then it hit me… git hooks!

I never used any git hooks before, so this was all new for me. So let me show you what I did to make this work!

1. I needed to know my own requirements.

  • For every commit message take the branch name, take out the ticket number and prefix it for the commit message.
  • If there is no ticket number in the branch name then just commit the orginal message

Branch: Feature/STRY-098-testing
Commit message: Yay I made something work
Commit message on git: [STRY-098] Yay I made something work

Branch: Feature/develop
Commit message: Yay I made something work
Commit message on git: Yay I made something work

2. Show hidden files on Mac by doing the following statement in the terminal:

defaults write com.apple.finder AppleShowAllFiles YES

Relaunch the Finder to let it take affect.

3.  Go to the directory where your repository is located. Go to .git/hooks/ here you will see sample hooks that git provides.

The one I need to have for my requirements is prepare-commit-msg.sample. Open this one with a text editor.

Tip: hard lesson I learned is that you cannot change the file names! 

Remove everything inside this file and copy/paste the following inside the file:

More information about this code here.

Save and exit the text editor.

4. We need to remove the extention. Right click on prepare-commit-msg.sample and click Get Info. Here remove the .sample from the file name and save.

5. The file needs to be executable on the machine. To do this enter the following command in the terminal:

chmod +x .git/hooks/prepare-commit-msg

Now try it out!

 

Add a Comment

Your email address will not be published. Required fields are marked *