We add Jira Issue # to the commit message to link the change with the Jira Issue. As the issue number is added manually, it is prone to human error. As we always have this number in the Git branch_, can the commit message have default value of this branch name? Can it be done with an vs code extension or git templates?
I created this file called prepare-commit-msg
that I copied inside the .git/hooks
folder
#!/bin/bash
# Get the current branch name
current_branch=`git rev-parse --abbrev-ref HEAD`
# Search Jira ID in a pattern such a "feature/ABCD-123-my-feature"
id=$(echo $current_branch | sed -nE 's,[a-z]+/([A-Z]+-[0-9]+)-.+,\1,p')
# Only prepend if an ID was found in the current branch
if [[ ! -z $id ]]; then
# $1 is the name of the file containing the commit message
# Prepend "ABCD-123: "
sed -i.bak -E "1s/^/${id}: /" $1
fi
Here's the gist: https://gist.github.com/raduchiriac/36b6269bebb75cfac7371acb1459fdcc
NOTE: you will find many solutions that use sed -nr
, unfortunately that doesn't work post-Sierra anymore. Use -E
Actually I've found Flow / Jira Commit Prefix
extension that does pretty much what I need. One can adjust the sources by it's need.
I advise you using a commit-msg
local hook and pre-receive
server hook for your purpose. Git hooks are scripts that validate and modify repository writing operations - you may get acquainted with them in the official documentation: https://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks
Local commit-msg
hook may extract the ticket name from the branch and append it to the message, if none has already been found there. It can even cancel the commit process, if the branch name does not satisfy naming requirements.
The prime disadvantage of this approach is that any developer should put the local hook manually due to security considerations, so one may also forget or ignore this. Therefore, you also need a server-side pre-receive
hook to decline pushed branches whether one of new commits contains an invalid message.
The suggested answer didn't work for me, so I modified it slightly and added a convenience script:
Note: This should be applied only once per git project.
- Install Husky in your project:
yarn add --dev husky
- Set up Husky to enable Git hooks:
npx husky init && rm -rf .husky/pre-commit
- Fetch my Gist and add it as a Husky hook in a single command:
curl -s https://gist.githubusercontent.com/tomerh2001/e3e96b8c3e48356b0a9be002d619887a/raw/prepare-commit-msg.bash > .husky/prepare-commit-msg && chmod +x .husky/prepare-commit-msg
This will ensure the script is embedded directly in the .husky/prepare-commit-msg
file, making it available for everyone who clones the repo without extra steps.
© 2022 - 2024 — McMap. All rights reserved.