4

Based on this question I made a git hook prepare-commit-msg

#!/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 

It works pretty well on simple commits. Example - [issue14020]: some text message if commit was made in issue14020 branch.

But then I make a rebase I have got message like this [(no branch)]: [issue14020]: some text message. Is there any way to skip this "no branch" part?

Community
  • 1
  • 1
Alexey B.
  • 11,965
  • 2
  • 49
  • 73

1 Answers1

6

You get the '(no branch)' on rebase commits if you've ended up in a headless state.

Rather than using git branch to get the current branch name, use NAME=$(git rev-parse --abbrev-ref HEAD) which will return the current branch or 'HEAD' if you're in headless mode.

Re-working your script, this then becomes:

NAME=$(git rev-parse --abbrev-ref HEAD);
if [ "$NAME" != 'HEAD' ] ; then
    DESCRIPTION=$(git config branch."$NAME".description);
    echo "[$NAME]"': '$(cat "$1") > "$1";
    if [ -n "$DESCRIPTION" ] ; then
        echo "" >> "$1";
        echo $DESCRIPTION >> "$1";
    fi
fi
mproffitt
  • 2,409
  • 18
  • 24
  • What if I want to determine the name of the branch that is currently being rebased, as in, rather than HEAD, it would be the name of the actual branch. Is there a way to do this? I imagine not because detached HEAD has no reference to its branch, but I could be wrong. – finiteloop May 03 '14 at 02:02