Skip to content

Instantly share code, notes, and snippets.

@MateusTymoniuk
Last active July 29, 2024 09:05
Show Gist options
  • Save MateusTymoniuk/72502734762d50f5a81b72e3a1285e6e to your computer and use it in GitHub Desktop.
Save MateusTymoniuk/72502734762d50f5a81b72e3a1285e6e to your computer and use it in GitHub Desktop.
prepare-commit-msg git hook to add jira ticket number to beginning of the commit msg
#!/bin/bash
# Hook based on this article: https://andy-carter.com/blog/automating-git-commit-messages-with-git-hooks
COMMIT_MSG_FILE=$1
COMMIT_SOURCE=$2
SHA1=$3
branch=$(git branch --show-current)
# Link to regex matches: https://regex101.com/r/6X9gfO/1
regex="[A-Z]{3,10}-[0-9]{1,5}"
# checking for message as source to skip changing the commit message
# when it's a --amend
if [[ $COMMIT_SOURCE == "message" ]] &&
[[ $branch =~ $regex ]]; then
echo "Adding ticket number to commit"
ticket_number=$BASH_REMATCH
commit_message=$( < $COMMIT_MSG_FILE)
# Use printf to preserve the formatting of the commit message
printf "%s %s" "$ticket_number" "$commit_message" > "$COMMIT_MSG_FILE"
fi
@MateusTymoniuk
Copy link
Author

When using the script, make sure your file is executable. For example, my file was under ~/.config/global-git-hooks, so the command will be:

chmod +x ~/.config/global-git-hooks/prepare-commit-msg

If you would like to, you can add it to global hooks, to be applied to every commit, instead of locally on the project (which would require to be done in every project .git folder). For using it globally, add the path of the folder containing your hook to the git core.hooksPath configuration. Still on the folder from before, the command will be:

git config --global core.hooksPath ~/.config/global-git-hooks

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