How to add Git's branch name to the commit message?

Tomer Lichtash picture Tomer Lichtash · May 5, 2011 · Viewed 54.8k times · Source

I need some help with a Bash script that will automatically add the git's branch name as a hash in commit messages.

Answer

shytikov picture shytikov · Jul 17, 2012

Here is my commit-msg script as an example:

#!/bin/sh
#
# Automatically adds branch name and branch description to every commit message.
#
NAME=$(git branch | grep '*' | sed 's/* //') 
DESCRIPTION=$(git config branch."$NAME".description)

echo "$NAME"': '$(cat "$1") > "$1"
if [ -n "$DESCRIPTION" ] 
then
   echo "" >> "$1"
   echo $DESCRIPTION >> "$1"
fi 

Creates following commit message:

[branch_name]: [original_message]

[branch_description]

I'm using issue number as branch_name, issue description is placed to the branch_description using git branch --edit-description [branch_name] command.

More about branch descriptions you can find on this Q&A.

The code example is stored in following Gist.