Skip to content

Instantly share code, notes, and snippets.

@lorin
Created August 29, 2013 03:08
Show Gist options
  • Select an option

  • Save lorin/6373849 to your computer and use it in GitHub Desktop.

Select an option

Save lorin/6373849 to your computer and use it in GitHub Desktop.
A git hook for annotating a git commit message with info about an associated Trello card.
#!/usr/bin/python
"""
This is a prepare-commit-msg hook for use with git-flow and Trello
Copy this file to $GITREPOSITORY/.git/hooks/prepare-commit-msg
It will prepend [<card id>] to your commit message, and append a
link to the Trello card at the end of the commit message
Assumes you name your feature branches card-id/name.
For example: A1b2C56xQ/my-cool-feature
This would start the commit message with:
[A1b2C56xQ]
And end the commit message with:
https://trello.com/c/A1b2C56xQ
"""
import subprocess
import sys
def get_card_id():
"""Return the card id number associated with the current feature branch"""
branchname = subprocess.check_output(["/usr/bin/git", "symbolic-ref",
"HEAD"])
# This looks like: refs/heads/feature/A1b2C56xQ/my-cool-feature
args = branchname.split('/')
if len(args) != 5:
raise ValueError("Not in feature branch format")
if args[2] != 'feature':
raise ValueError("Not a feature branch")
story = branchname.split('/')[3]
return story
def prepend_commit_msg(text):
"""Prepend the commit message with `text`"""
msgfile = sys.argv[1]
with open(msgfile) as f:
contents = f.read()
with open(msgfile, 'w') as f:
# Don't append if it's already there
if not contents.startswith(text):
f.write(text)
f.write(contents)
def append_commit_msg(text):
"""Prepend the commit message with `text`"""
msgfile = sys.argv[1]
with open(msgfile) as f:
contents = f.read()
# Strip out all lines that start with "#"
message = '\n'.join(x for x in contents.split('\n')
if not x.startswith('#'))
with open(msgfile, 'a') as f:
# Don't append if the text is already in the commit message
if text not in message:
f.write(text)
def get_trello_link(card_id):
return "https://trello.com/c/%s" % card_id
def main():
# Fail silently
try:
card_id = get_card_id()
header = "[{}] ".format(card_id)
link = get_trello_link(card_id)
prepend_commit_msg(header)
footer = "\n{}".format(link)
append_commit_msg(footer)
except Exception as e:
# Fail silently
pass
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment