Last active
September 8, 2021 22:59
-
-
Save bujiie/e73441253e8b49e22b0ac476e7ff8131 to your computer and use it in GitHub Desktop.
git precommit hook checking for JIRA in commit message.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Place in project's .git/hooks directory. File must be called "prepare-commit-msg". | |
# i.e. <project root>/.git/hooks/prepare-commit-msg | |
FILE=$1 | |
MESSAGE=$(cat $FILE) | |
current_branch="$(git rev-parse --abbrev-ref HEAD)" | |
jira_regex='^[[:upper:]]{2,}-[[:digit:]]+[[:space:]]' | |
merge_regex='^Merge branch' | |
no_jira_error_msg="Aborting commit. Your commit message needs to start with a JIRA-1234 followed by a space." | |
jira_from_branch=$(echo $current_branch | grep -Eo '^(\w+/)?(\w+[-_])?[0-9]+' | grep -Eo '(\w+[-])?[0-9]+' | tr "[:lower:]" "[:upper:]") | |
# If there is already a JIRA at the beginning of the commit message | |
# continue with commit action. | |
if [[ $MESSAGE =~ $jira_regex || "$MESSAGE" == "${jira_from_branch} *" || $MESSAGE =~ $merge_regex ]]; then | |
exit 0; | |
fi | |
# If we successfully pulled something from the branch name, lets | |
# assume it is a JIRA and prepend it to the commit message then proceed | |
# with the commit action. | |
if [[ -n "${jira_from_branch}" ]]; then | |
echo "$jira_from_branch $MESSAGE" > $FILE | |
exit 0; | |
fi | |
# If we cannot detect a JIRA in the commit message, abort commit. | |
if ! grep -iqE "$jira_regex" "$FILE"; then | |
echo "$no_jira_error_msg" >&2 | |
exit 1 | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment