Skip to content

Instantly share code, notes, and snippets.

@lorin
Created December 1, 2014 15:38
Show Gist options
  • Save lorin/197cb2e1f59e5dcb7dd0 to your computer and use it in GitHub Desktop.
Save lorin/197cb2e1f59e5dcb7dd0 to your computer and use it in GitHub Desktop.
Prepend JIRA ticket name in commit message
#!/usr/bin/python
"""
This is a prepare-commit-msg hook for use with Jira
Copy this file to $GITREPOSITORY/.git/hooks/prepare-commit-msg
It will prepend PROJ-123 to your commit message, assuming your branch is
named proj-123.
"""
import re
import subprocess
import sys
def is_ticket(s):
regex = r"[a-zA-Z]+-\d+"
return re.match(regex, s)
def get_ticket():
"""Return the ticket id associated with the current feature branch"""
branchname = subprocess.check_output(["git", "rev-parse",
"--abbrev-ref", "HEAD"]).rstrip()
if not is_ticket(branchname):
raise ValueError("Branch name not in expected format")
return branchname.upper()
def prepend_commit_msg(text):
"""Prepend the commit message with `text`"""
msgfile = sys.argv[1]
with open(msgfile) as f:
contents = f.read()
with open(msgfile, 'w') as f:
# Don't append if it's already there
if not contents.startswith(text):
f.write(text)
f.write(contents)
def main():
# Fail silently
try:
ticket = get_ticket()
header = "{} ".format(ticket)
prepend_commit_msg(header)
except:
# Swallow exceptions to handle branches
# that don't follow the convention
pass
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment