find point where two branches in git FIRST diverged

102 views Asked by At

This is slightly simplified from the real story, but hopefully close enough. Suppose I initially have one branch: develop. Then I create a new branch: release. At this point, release and develop both point to commit XYZ. I do some work on the release branch, and occasionally merge it into develop. Meanwhile, I do lots of other work on the develop branch. Then one day I wake up and wonder when did my branches first diverge? That is, I want to find the commit hash of commit XYZ. The obvious temptation is to use "git merge-base" but this just finds the point when I last merged release into develop, which is WAY later than commit XYZ.

1

There are 1 answers

2
hlovdal On

Since both branches have the same root, I think it should be possible to generate a list of commits back to the root commit for each branch, and then compare those two lists reversed until there is a difference. Then the common ancestor commit is the last one before the first difference.

The following command should then print the commit id of the common ancestor commit:

diff -u <(git log --reverse --oneline develop) <(git log --reverse --oneline release) \
   | sed '1,3d; /^[+-]/,$d' | tail -1 | awk '{print $1}'

Edit: The sed argument is two delete (d) commands, separated with semicolon. The first delete is removing lines 1 to 3 (inclusive). The second delete is removing from the first line that starts with either plus or minus, until the last line ($).