2

I read another post that provided a somewhat working prepare-commit-msg, I modified it a little:

#!/bin/sh
#
# Automatically adds branch name and branch description to every commit message.
#
# todo:
# * breaks merge commit message
# * breaks git commit --amend

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

Taking the "happy path" that is:

git add -A
git commit -m 'Some commit message'

will work as expected, output:

some-modular-app git:test-commit-hooks ❯ log | grep 9406dfb
* 9406dfb - [test-commit-hooks] Make edit (2 hours ago) <mbigras>

How there are two cases that do not work, if you use:

1.

git commit

to enter vim then the newlines are deleted for some reason, which forces one to edit the message to put the comments on their own line, as shown below:

enter image description here

enter image description here

2.

git commit --amend

Will cause the same problem as 1. but also it prepends a second [branch-name], also shown below enter image description here

enter image description here

How could I modify the above script to address the problem use cases 1 and 2?

Thanks

Community
  • 1
  • 1
mbigras
  • 7,664
  • 11
  • 50
  • 111
  • The answer is hidden in [a comment in that same Q&A](http://stackoverflow.com/questions/5894946/how-to-add-gits-branch-name-to-the-commit-message#comment31820573_11524807). See also http://git-blame.blogspot.com/2013/06/checking-current-branch-programatically.html as noted in http://stackoverflow.com/a/1593487/1256452 – torek Aug 05 '16 at 19:40

1 Answers1

3

Please try this snippet in your hook:

NAME=$(git branch | grep '*' | sed 's/* //') 
echo -n "$NAME"': '|cat - "$1" > /tmp/out && mv /tmp/out "$1"