Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Python prepare-commit-msg to insert [touch:ticket number] to every commit message. Note it adds it commented in order to abort gracefully, otherwise exiting the EDITOR would cause the commit to be actioned as [touch:ticket number] would be recognised as the message. Note that get_ticket_number() logic is custom. Change to extract the ticket numb…
#!/usr/bin/env python
"""
To enable save as /yourproject/.git/hooks/prepare-commit-msg
and make executable: chmod +rx prepare-commit-msg
"""
import sys
from subprocess import check_output
def get_ticket_number():
branch_name = check_output(['git', 'rev-parse', '--abbrev-ref', 'HEAD'])
return branch_name.split('-')[1]
def prepend_to_file(marker):
with open(sys.argv[1], 'r') as message_file:
lines = message_file.readlines()
lines[0] = marker + lines[0]
with open(sys.argv[1], 'w') as message_file:
message_file.write(''.join(lines))
if __name__ == '__main__':
try:
marker = '\n\n#[touch:%s]' % get_ticket_number()
prepend_to_file(marker)
except:
# if we can't find a ticket number, carry on as normal
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.