Skip to content

Instantly share code, notes, and snippets.

@alfredodeza
Last active October 19, 2015 20:06
Show Gist options
  • Save alfredodeza/6d62d99a95c9a7975fbe to your computer and use it in GitHub Desktop.
Save alfredodeza/6d62d99a95c9a7975fbe to your computer and use it in GitHub Desktop.
prefix commit messages with branch names
#!/usr/bin/python
"""
This is a prepare-commit-msg hook that fill prefix commit messages with
[BRANCH]
Copy this file to $GITREPOSITORY/.git/hooks/prepare-commit-msg
and mark it executable.
Assumes your branch is based off of a tracker ID
"""
import subprocess
import sys
import os
def which(executable):
locations = (
'/usr/local/bin',
'/bin',
'/usr/bin',
'/usr/local/sbin',
'/usr/sbin',
'/sbin',
)
for location in locations:
executable_path = os.path.join(location, executable)
if os.path.exists(executable_path):
return executable_path
GIT = which('git')
def branch_name():
try:
name = subprocess.check_output(
[GIT, "symbolic-ref", "HEAD"],
stderr=subprocess.STDOUT)
except Exception as err:
if 'fatal: ref HEAD is not a symbolic ref' in err.output:
# we are in a rebase or detached head state
return ''
# This looks like: refs/heads/12345678/my-cool-feature
# if we ever get a branch that has '/' in it we are going to have
# some issues.
return name.split('/')[-1]
parts = name.split('/')
if len(parts) != 4:
raise ValueError("Branch name has '/' in it which is not allowed")
branch = parts[-1]
return branch
def prepend_commit_msg(branch):
"""Prepend the commit message with `text`"""
msgfile = sys.argv[1]
header = "[%s] " % branch
with open(msgfile) as f:
contents = f.read()
if not branch:
return contents
with open(msgfile, 'w') as f:
# Don't append if it's already there
if not contents.startswith(header):
f.write(header)
f.write(contents)
def main():
branch = branch_name().strip().strip('\n')
prepend_commit_msg(branch)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment