Monday, June 3, 2013

prepare-commit-msg hook for git that inserts name of the current branch

A hook for git that inserts at the beginning of the commit message name of the current branch, if the message is empty (contains empty or comment lines).

Put this your_project_folder/.git/hooks/prepare-commit-msg
#!/usr/bin/env python3

import sys
import subprocess


with open(sys.argv[1], 'r+') as commit_message_file:
    commit_message = list(commit_message_file)

    for line in commit_message:
        line = line.strip()
        if line and not line.startswith('#'):  # comment line
            break  # a non-empty line
    else:  # empty message
        branch_name = subprocess.check_output('git symbolic-ref --short HEAD', shell=True).strip().decode('utf-8')
        commit_message.insert(0, branch_name + ' ')

    commit_message_file.seek(0)
    for line in commit_message:
        commit_message_file.write(line)

Don't forget to make the script executable:
chmod +x prepare-commit-msg

No comments:

Post a Comment