Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

git

git-merge

I'm writing a custom merge driver that needs to be aware of the names of the branches it is merging. I managed to retrieve the name of the branch being merged into (destination) with git symbolic-ref HEAD and the name of the branch being merged in (source) from the GITHEAD_<SHA> environment variable.

# 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"

Is this the right way of doing this? Particularly, retrieving the source name from an environment variable seems flaky. Note that MERGE_HEAD is not present at this point, so I cannot use the same approach as with HEAD.

like image 796
vanjan Avatar asked Jun 19 '14 08:06

vanjan


1 Answers

Yes, this is as close as you can get in a merge driver.

A merge strategy gets the correct name by looking up each GITHEAD_%s where each %s argument is filled in from the argument(s) given to the merge strategy, one per "remote head". See my answer to a related question for details. This is not documented anywhere, it's just from the source. Unfortunately, by the time you get down to a merge driver, this information is lost: there are no % directives that retrieve those names, even though there could be. (Adding some % directives should be easy: just increase the size of the dictionary and add appropriate directives and strbuf objects.)

If you're handling a normal two-heads-and-a-base merge, there's only one GITHEAD_* variable and it's the other head, but if you are handling an octopus merge, you are out of luck.

like image 54
torek Avatar answered Oct 01 '22 21:10

torek