Skip to content

Instantly share code, notes, and snippets.

@EmileSonneveld
Last active June 5, 2023 07:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EmileSonneveld/787b8b51e55027cf848223bc30546dd8 to your computer and use it in GitHub Desktop.
Save EmileSonneveld/787b8b51e55027cf848223bc30546dd8 to your computer and use it in GitHub Desktop.
#!/bin/sh
# Prevent a commit when no ticket reference is in the message.
# By hooking in just before an actual commit
# To install:
# cd path/to/repo/
# wget --no-clobber https://gist.githubusercontent.com/EmileSonneveld/787b8b51e55027cf848223bc30546dd8/raw -O .git/hooks/commit-msg && chmod +x .git/hooks/commit-msg
check=$(grep -E 'Merge (branch|remote-tracking branch|pull request|tag) ' "$1")
if [ "" != "$check" ]; then
echo "Not checking ticket reference in merge commit"
exit 0
fi
echo "Running $0"
# Test the regex here: https://regex101.com/r/J2qFLO/4
check=$(grep -E '((^|[ \n\(])((([a-zA-Z0-9_\-]+\/)?([a-zA-Z0-9_\-]+))?#[0-9]{1,9})|([A-Z]+-[0-9]+)|(https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)))' "$1")
if [ "" = "$check" ]; then
echo " Commit message should refer to a ticket!"
echo ""
echo "Possible references:"
echo " Simple hash with number: #123"
echo " Prefix repo: test#123"
echo " Prefix organisation/user and repo: test_user-0/test_repo-42#123"
echo " GL-... syntax: GL-123"
echo " GitLab URL: https://gitlab.com/test_user-0/test_repo-42/-/issues/123"
echo " GitHub URL: https://github.com/test_user-0/test_repo-42/issues/123"
echo " Jira URL: https://jira.example.com/browse/EP-123"
echo " Any URL: https://any-url-actually.org/"
echo ""
echo "Blocked:"
echo " Double hashtag: ##123 GitHub recognizes this, while it could be unintentional."
echo ""
message=$(cat $1)
echo "Ignore check with:"
echo -n " git commit --no-verify -m \"" && printf "%s" "$message" && echo "\""
echo ""
exit 1
else
echo " Reference found in commit message."
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment