The project on which I am currently working requires by convention that all commits associated with a specific JIRA issue have messages that begin with the issue number, followed by a colon and the rest of the commit message.
Over time, I’ve grown tired of typing (and mistyping) the issue number for each commit message, and I’ve decided to automate the process with a script.
The obvious place to add this functionality is in a git hook. Git hooks are scripts that are called by git at specific times, and they allow the user to customize the behavior of git. Learn more about git hooks specifically here.
Due to integration between JIRA and Bitbucket on my project, each git branch already includes the issue number of the related JIRA issue. Thus, my git hook runs at commit time and checks the branch name for a JIRA issue number. If present, it makes sure my commit message begins with the issue number.
I’ve used PowerShell as a cross-platform scripting environment, so the script should work on Windows, OSX, and Linux with minimal modifications.
After a bit of experimentation, I settled on the following core script:
Due to a recent change in PowerShell, this script cannot be directly used as the commit hook, so I placed this core script in a central directory for Git hooks scripts, in C:\Tools\git-hooks\
.
I created a second, wrapper script as follows:
I placed the script in the git hooks directory for my project, and it ran on my next commit.
To use with your project, place the core script in C:\Tools\git-hooks\
and the wrapper script in <project_directory>\.git\hooks\
and ensure it has execute permissions. You may also need to update the wrapper script with the correct path to your PowerShell executable (you can find this by executing Get-Command pwsh | Select-Object Source
).
Update 11/27/2023: Added workaround to support newer versions of PowerShell.