Skip to content

Instantly share code, notes, and snippets.

@taylor
Forked from lorin/prepare-commit-msg.py
Created September 4, 2013 01:18
Show Gist options
  • Save taylor/6431726 to your computer and use it in GitHub Desktop.
Save taylor/6431726 to your computer and use it in GitHub Desktop.
#!/usr/bin/python
"""
This is a prepare-commit-msg hook for use with git-flow and Pivotal Tracker.
Copy this file to $GITREPOSITORY/.git/hooks/prepare-commit-msg
It will prepend [#<story id>] to your commit message.
See https://www.pivotaltracker.com/help/api?version=v3#scm_post_commit
Assumes you name your feature branches story-id/name.
For example: 12345678/my-cool-feature
This script can be found at https://gist.github.com/2963131
"""
import subprocess
import sys
def get_story():
"""Return the story id number associated with the current feature branch"""
branchname = subprocess.check_output(["/usr/bin/git", "symbolic-ref", "HEAD"])
# This looks like: refs/heads/feature/12345678/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 = int(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 main():
# Fail silently
try:
story = get_story()
header = "[#%d] " % story
prepend_commit_msg(header)
except:
pass
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment