Previewing a merge result
Posted on Mon 07 December 2015 in Effective git usage
Sometimes you'll want to preview what the result of a merge would be, either to see if it makes sense or to check for merge conflicts. Unfortunately there is not really a way to do this, but the following tricks come close:
git diff other
This will show you the diff between your branch and another one. The downside is that changes made on your branch will also be shown, but in reverse. So it's not very useful.
git diff ...other
This will show the changes on branch other since that branch and the one you're on started diverging. The pitfall is that if any changes were also applied to your branch (e.g. with cherry-pick), they'll still show up. Merge conflicts will also not be detected.
Fortunately, git also exposes all its innards to the user. One of these innards
is the merge-tree
It takes three arguments that should resolve to trees. To
preview the effect of merging a branch named develop into the current branch,
you could run:
git merge-tree $(git merge-base HEAD develop) HEAD develop
As it's a plumbing command, it does not guess what you mean, you have to be explicit. It also doesn't colorize the output or use your pager, so the full command would be:
git merge-tree $(git merge-base HEAD develop) HEAD develop | colordiff | $(git var GIT_PAGER)
So really, the best way to preview a merge is to simply try the merge and discard the result. Make sure your working tree is clean and simply merge:
git merge --no-commit other
git diff
This will show exactly what the change will be and will also show all merge conflicts. When you're done inspecting the result, simply discard the changes:
git reset --hard