If you follow gitflow or github-flow you will have branch names like this: feature/JIRA-1234-My-Feature
or bugfix/ABC-121-Issue
. And most of the times your commit messages will start the same: JIRA-1234 Created the button
or ABC-121 Reverted Refactoring
.
The Hook
#!/bin/sh
if [ -z "$BRANCHES_TO_SKIP" ]; then
BRANCHES_TO_SKIP=(main develop)
fi
BRANCH_NAME=$(git symbolic-ref --short HEAD)
TICKET_NAME=$(echo $BRANCH_NAME | grep -Poi '\w*/\K([0-9]+)')
BRANCH_EXCLUDED=$(printf "%s\n" "${BRANCHES_TO_SKIP[@]}" | grep -c "^$BRANCH_NAME$")
ALREADY_IN_MSG=$(grep -ci "$TICKET_NAME" $1)
if [ -n "$BRANCH_NAME" ] && ! [[ "$BRANCH_EXCLUDED" -eq 1 ]] && ! [[ "$ALREADY_IN_MSG" -eq 1 ]]; then
sed -i.bak -e "1s/^/AB#${TICKET_NAME^^} /" "$1"
fi
Now if you are on your feature/JIRA-1234-Something
branch and created a commit message without your ticket it will automatically prefix your ticket, so:
git commit -m "Test"
Will result in
JIRA-1234 Test
If you still prefix your ticket with this, don't worry, this will not prefix your message a second time. And the git hook works in all GUI's (Visual Studio, Rider, Source-Tree) or via the CLI.
How to install?
To use it you have to go into the .git
folder of your repository. There you find a hooks
folder with a lot of sample files.
The hook we have written is called prepare-commit-msg
. So create a new file called prepare-commit-msg
. There is no extension and copy the content et voilà: You save about 0.52 seconds per commit message 😉