#!/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[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()