Precommit Hook
Automatically prefix JIRA issue numbers to Git commit messages
When we are lazy, you know it can get a little annoying having to type the issue number in every commit message. We can easily automate this using the git prepare-commit-message hook which can prepend commit messages with JIRA issue number to the commit message extracted from the git branch name (and get the benefits of Smart Commits). You can use this trick for any issue tracker you might use. Read more to know how to do this.
TICKET-123 — a useful commit message
Naming your git branches
For this technique to work, you need to make sure that you include the issue number in the name of the git branch. You can use the git flow naming convention as long as the ticket number is in the branch name. Here are some examples:
AWESOME-1234
THING-4456
feature/PANTS-1234
fix/LOL-1567
JavaScript Projects (Cross Platform)
The bash script solution will still work for JavaScript projects. But if you want to stay away from bash scripts there is an alternative solution we can use.
We will use husky
and jira-prepare-commit-msg
as dev dependencies to help us achieve our goal.
husky is a handy tool to manage git hooks for JavaScript projects from package.json file (or a config file)
jira-prepare-commit-msg is an npm CLI module which does exactly what we want
Step1: Install the dependencies
or
Step 2: Prepare Commit Message hook
Add the following configuration to your package.json
file to invoke jira-prepare-commit-msg
when the prepare-commit-message is triggered
Configuration
You can configure jira-prepare-commit-message
to use custom message pattern or ticket number pattern. You can also set a comment character and specify if you use conventional commit (which you should!).
You can also see package’s readme here to know more configuration details.
NVM Users Please Note
If you use Node Version Manager (NVM), husky will automatically use the node version that is set by nvm on your shell. If you use a git GUI client like GitKraken or Source Tree, they may fall back to using the default node version. So, you may have to set your default node version to your most used project’s node version. If you know any other solution, I would love to know it in the comments below. Also, if you’re tired of typing nvm use
each time you open a terminal in a JavaScript project, this article will show you how to never have to do this again!
Conclusion
Having issue numbers in commit messages can be very useful for tracking commits in your issue tracker. However, manually adding the issue number takes time and is easy to forget. In this article, we learnt how to automate this using prepare-commit-message git hooks.
Many issue trackers like JIRA, GitHub, Azure DevOps support smart commits which automatically associate commit messages or Pull Requests with issue numbers to the appropriate issue. If you want to learn and understand git better, check this book out
Last updated