Created
September 8, 2013 11:07
-
-
Save peterdemin/6483893 to your computer and use it in GitHub Desktop.
git commit message hook, that automatically adds ticket number to commit message
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
#-*- coding: utf-8 -*- | |
import os | |
import re | |
import sys | |
import shutil | |
import subprocess | |
re_ticket = re.compile(ur'(?u)^([0-9]+)-.+') | |
def git(*args): | |
p = subprocess.Popen( | |
('git',) + args, | |
shell=True, | |
stdout=subprocess.PIPE, | |
stderr=subprocess.STDOUT, | |
) | |
p.wait() | |
return p.stdout.read() | |
def current_branch(): | |
return git('symbolic-ref', '--short', '-q', 'HEAD').strip() | |
def ensure_message_file_refs(filename): | |
if os.path.exists(filename): | |
m = re_ticket.match(current_branch()) | |
if m: | |
ticket_nbr = '#' + m.group(1) | |
with open(filename, 'rt') as fp: | |
content = fp.read() | |
if ticket_nbr not in content: | |
content = content.rstrip() + u'\nRefs ' + ticket_nbr | |
with open(filename, 'wt') as fp: | |
fp.write(content) | |
print 'Succesfully appended "Refs ' + ticket_nbr + '"' | |
return 0 | |
else: | |
print 'message file not found at %r' % (filename) | |
return 1 | |
if __name__ == '__main__': | |
if len(sys.argv) > 1: | |
sys.exit(ensure_message_file_refs(sys.argv[1])) | |
else: | |
here = os.path.dirname(os.path.abspath(__file__)) | |
hook = os.path.join(here, '.git', 'hooks', 'commit-msg') | |
shutil.copy(__file__, hook) | |
print 'Succesfully installed commit-msg hook' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment