Figure out merged commit in prepare-commit-msg hook

git

I have tried creating a prepare-commit-msg hook that works for merge commits. The script gets passed the following arguments .git/MERGE_MSG, merge.

I need to get the hash or branch name of the merged commit (for a normal, non-octopus merge). I know I can do git rev-parse MERGE_HEAD to get the hash or name-rev --name-only MERGE_HEAD to get the branch name (if any).

However, it seems that prepare-commit-msg is called before MERGE_HEAD is created. Is there any other way of knowing which commit was merged short of parsing the auto-generated message?

I’m using git 2.4.0.

Best Answer

In a custom merge driver, the name of the branch being merged into (destination) can be retrieved with git symbolic-ref HEAD and the name of the branch being merged in (source) from the GITHEAD_<SHA> environment variable,

This is an example script fragment :

# retrieve merged branch name from an env var GITHEAD_<sha>=<branchName> 
# we cannot use a sym ref of MERGE_HEAD, as it doesn't yet exist 
gitHead=$(env | grep GITHEAD) # e.g. GITHEAD_<sha>=release/1.43 
# cut out everything up to the last "=" sign 
source="${gitHead##*=}"

# retrieve base branch name from a sym ref of HEAD 
branch=$(git symbolic-ref HEAD) # e.g. refs/heads/master 
# cut out "refs/heads"
destination="${branch#refs/heads/}"

echo "Merging from $source into $destination"

Source : How to retrieve branch names in a custom Git merge driver?.

Related Question