Skip to content

Instantly share code, notes, and snippets.

@igniteflow
Last active December 29, 2015 16:09
Show Gist options
  • Save igniteflow/7695909 to your computer and use it in GitHub Desktop.
Save igniteflow/7695909 to your computer and use it in GitHub Desktop.
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