Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save publicJorn/b5fffad95dc322bd1f511d97fb470e0d to your computer and use it in GitHub Desktop.
Save publicJorn/b5fffad95dc322bd1f511d97fb470e0d to your computer and use it in GitHub Desktop.

Automatically add issue number to git commit message

When working with issues/tickets in gitlab, -hub, Jira, etc. It's a good practise to add the issue number to the branch name and commit message.
This way you basically generate a documented history.

But adding the issue number manually to a git message is tedious. This git hook manages it for you.

prepare-commit-msg hook

Let's say your team has agreed on the branch name format: review/123_short-description

The following hook extracts the issue number and adds it to the commit message body.

#!/bin/sh

MSG_FILE=$1

branchName=`git rev-parse --abbrev-ref HEAD`

# review/1234_my-branch

issueNr=$(echo $branchName | sed -nE 's,[a-z]+\/?([0-9]+).*,\1,p')

if [[ ! -z $issueNr ]]; then
  echo "$(cat $MSG_FILE)\n\nissue: #$issueNr" > "$MSG_FILE"
fi

Save it to <your_project>/.git/hooks/prepare-commit-msg

With the above code, The issue number will be matched for the following branch names:

  • whatever/123_whatever
  • whatever/123-whatever
  • 123_-whatever

If it doesn't match, nothing will be added to the commit message.

Example

git checkout -b feature/1234_test-branch
echo "test" > test.txt
git add test.txt
git commit -m"feat: test"

result:

feat: test

issue: #1234

Credits: https://serebrov.github.io/html/2019-06-16-git-hook-to-add-issue-number-to-commit-message.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment