问题
In order to find the common ancestor of 2 git branches, one needs to do:
git merge-base branch another_branch
Okay. But... what if both branches have already been merged? When I use merge-base
in that case, the commit I get is the latest one before the merge, and I would like to know the common ancestor from which both branches came out "before the merge".
In other words:
Z - A - B - C - D - E - F
\ /
G - H - I
HEAD
is at F. If I do a git merge-base
here, the commit I get is I
, and the one I am looking for is A, or perhaps Z. Is there any git instruction to find it?
回答1:
If you do
git merge-base C I
you get the commit A you want. What are C and I? They are the parent commits of your merge commit D.
Hoy do you get them?
git log --pretty=%P -n 1 D
gives you two strings. This two strings are the commit C and I you need.
If you want to do it all together you can write
git merge-base $(git log --pretty=%P -n 1 MERGE_COMMIT)
where you have to replace MERGE_COMMIT with the hash of your merge commit D
Edit: As @poke stated it is simpler with
git merge-base MERGE_COMMIT^ MERGE_COMMIT^2
回答2:
I usually need to find the ancestor between the tip of my branch, HEAD
and the remote main development branch, say origin/dev
. Here is what I use :
git log --reverse --boundary --format=%h HEAD ^origin/dev | head -1
It essentially says:
- Take all the ancestors except the ones common with
origin/dev
- Include the boundary (the forking point)
- Reverse the order so the forking point is the first in the list
- Log to a format where only the
SHA
appears - Take the first one in this list
来源:https://stackoverflow.com/questions/43712418/git-how-do-i-find-the-common-ancestor-of-two-branches-that-have-already-been