pondělí 1. listopadu 2021

Git How to add Branch name into commit message

Git - add Branch name into commit message.

Git - How to add Branch name into commit message.

Why

Because search something in git history can be very frustrating, because git branches are just “floating labels, which will simply move elsewhere or dissapear”.

How

Using git hook

Into file .git\hooks\prepare-commit-msg add this:

#!/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)  
TEXT=$(cat "$1" | sed '/^#.*/d')  
  
if [ -n "$TEXT" ]  
then  
  printf "$(cat "$1" | sed '/^#.*/d')\nBranch: $NAME" > "$1"  
  if [ -n "$DESCRIPTION" ]  
    then  
  echo "" >> "$1"  
  echo $DESCRIPTION >> "$1"  
  fi  
else  
  echo "Aborting commit due to empty commit message."  
  exit 1  
fi

And that’s it. Your commits will contain a branch name.

Sharing git hooks with others

Sharing git hooks inside a project is not supported by git. There are a few workarounds, but none of them is perfect.

e.g.

  • add directory <your repo>/.githooks/ create file prepare-commit-msg there and commit it.
  • set property git config --local core.hooksPath=.githooks
  • somehow ensure, that everyone will execute git config --local core.hooksPath=.githooks on every clone of your repo :(

https://stackoverflow.com/questions/5894946/how-to-add-gits-branch-name-to-the-commit-message

https://www.viget.com/articles/two-ways-to-share-git-hooks-with-your-team/