Skip to content

Instantly share code, notes, and snippets.

@DoonDoony
Created October 11, 2019 06:04
Show Gist options
  • Save DoonDoony/df60f0138007493e714367a7eccce841 to your computer and use it in GitHub Desktop.
Save DoonDoony/df60f0138007493e714367a7eccce841 to your computer and use it in GitHub Desktop.
prepare-commit-msg hook for jira id prefixed commit message
#!/usr/bin/env python
from __future__ import print_function
import re
import sys
GIT_HEAD_REF = '.git/HEAD'
ticket_number = re.compile(r'\b[A-Z]{2,}-[0-9]+')
branch_ticket_number = re.compile(r'\b[a-z]{2,}-[0-9]+')
def get_commit_msg(ref_path):
with open(ref_path) as commit_msg_object:
return commit_msg_object.read()
def get_branch_name():
with open(GIT_HEAD_REF) as git_object:
ref = git_object.read()
branch_name = ref.rsplit('/')[-1]
return branch_name
def get_ticket_number(branch_name):
matched = branch_ticket_number.match(branch_name)
return matched.group().upper()
def add_ticket_number(ref_path, ticket_number):
msg = get_commit_msg(ref_path)
msg = ticket_number + ' ' + msg
with open(ref_path, 'w') as commit_msg_object:
commit_msg_object.write(msg)
def bye(msg):
sys.stderr.write(msg + '\n')
sys.stderr.write('PREPARE COMMIT ABORTED' + '\n')
sys.exit(1)
def next_hook(msg):
sys.stdout.write(msg + '\n')
sys.exit(0)
def is_special_branch(branch_name):
protected_branch_names = ('master', 'develop', ) # NOTE: Change Required
if branch_name.strip() in protected_branch_names:
return True
elif 'integration' in branch_name:
return True
return False
def is_commit_contains_ticket_number(commit_msg):
matched = ticket_number.match(commit_msg)
return matched and not matched.group().startswith('PEP-8')
def is_empty_msg(msg):
return not ticket_number.sub('', msg).strip()
def main(_, commit_msg_ref, *args):
msg = get_commit_msg(commit_msg_ref)
branch_name = get_branch_name()
if is_special_branch(branch_name):
next_hook('Current branch is not a feature branch. Skipped')
elif is_empty_msg(msg):
bye('Commit message should have message body')
elif is_commit_contains_ticket_number(msg):
next_hook("Commit message already contains a Jira ticket number. Skipped")
else:
ticket_number = get_ticket_number(branch_name)
add_ticket_number(commit_msg_ref, ticket_number)
pass
if __name__ == '__main__':
main(*sys.argv)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment