Skip to content

Instantly share code, notes, and snippets.

@dzwarg
Created June 17, 2021 18:34
Show Gist options
  • Save dzwarg/8e3774a0c0fa729ad7be4cd2fed9dd58 to your computer and use it in GitHub Desktop.
Save dzwarg/8e3774a0c0fa729ad7be4cd2fed9dd58 to your computer and use it in GitHub Desktop.
JIRA commit-msg git hook
#!/usr/bin/env python
import re
import sys
COMMENT_RE = re.compile(r'^#.*$')
STORY_RE = re.compile(r'\b[A-Za-z]+-\d+\b')
BRANCH_RE = re.compile(r'^# On branch (?P<ticket>[A-Za-z]+-\d+)(-.*)?$')
def main ():
numlines = 0
msgfile = sys.argv[1]
with open(msgfile, 'r') as msg:
for line in msg:
if re.search(COMMENT_RE, line) is None and line.strip() != '':
numlines += 1
if re.search(STORY_RE, line):
# Content, and a matching story? WIN!
exit(0)
if numlines == 0:
# Empty commit message, abort
exit(1)
# Try to recover by finding the comment line that tells us what branch we're on.
"""# On branch ABC-6"""
ticket = None
with open(msgfile, 'r') as msg:
for line in msg:
m = re.match(BRANCH_RE, line)
if m:
ticket = m.group('ticket')
# If a ticketed branch was detected, automatically append the ticket to the foot of the commit message.
if ticket:
with open(msgfile, 'a') as msg:
msg.write('\n{0}\n'.format(ticket))
exit(0)
print """
\033[31mCommit aborted.\033[0m
Please include the story ID in your commit message.
"""
# No content in message? FAIL!
exit(1)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment