Skip to content

Instantly share code, notes, and snippets.

@dennisbyrne
Last active May 18, 2016 02:26
Show Gist options
  • Save dennisbyrne/1ce817818bfbb90b8b3441620c17fe8a to your computer and use it in GitHub Desktop.
Save dennisbyrne/1ce817818bfbb90b8b3441620c17fe8a to your computer and use it in GitHub Desktop.
This commit-msg hook will copy the ticket number from your branch name and prepend it to your commit msg.
#!/usr/bin/python
# 1) copy this file to your computer
# 2) make this file executable: $ chmod +x /path/to/commit_msg.py
# 3) from the root of your local repo: $ ln -s /path/to/commit_msg.py .git/hooks/commit-msg
import sys
import subprocess
import re
TICKET_PATTERN = '[A-Z]{3}-[\d]+'
POSTAMBLE = 'No commit msg was altered'
try:
current_ref = subprocess.check_output('git symbolic-ref HEAD', shell=True).decode()
branch_name = current_ref[len('refs/heads/'):]
except subprocess.CalledProcessError:
print "Are you in detached HEAD state? Could not determine a branch name. %s" % POSTAMBLE
sys.exit(0)
match = re.search(TICKET_PATTERN, branch_name)
if match:
ticket_id = match.group()
file_name = sys.argv[1]
with open(file_name, 'r') as f:
user_supplied_commit_msg = f.read()
if ticket_id not in user_supplied_commit_msg:
with open(file_name, 'w') as f:
f.write('%s %s' % (ticket_id, user_supplied_commit_msg))
print "JIRA ticket id %s has been prepended to commit msg" % ticket_id
else:
print "JIRA ticket id %s found in commit msg. %s" % (ticket_id, POSTAMBLE)
else:
args = (TICKET_PATTERN, branch_name, POSTAMBLE)
print 'Could not determine JIRA ticket id using pattern %s and branch name %s. %s' % args
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment