StasM
StasM

Reputation: 11082

git: finding which merge brough commit into the current branch

I have a number of branches, which are periodically merged, i.e. we can have A, which is merged into B, then B into C, then A into D and D into C, etc. Suppose I have a commit X, which I know was originally introduces in A, and then merged into C somehow (I can see it when I do git log C). Is there a way to find out which merge (which merge commit) brought the commit X into the branch C?

Upvotes: 2

Views: 692

Answers (1)

Richard Hansen
Richard Hansen

Reputation: 54273

Usually I do something like the following:

git log --oneline --ancestry-path --merges <commit-of-interest>..C

The --ancestry-path argument is the key here: it causes git to only show commits that are both a descendant of <commit-of-interest> AND an ancestor of C. The --merges option filters the resulting list further to only show merge commits.

Each of the printed merges falls into one of the following categories:

  • the merge brought <commit-of-interest> into a branch
  • the merge brought a different branch into a branch that already has <commit-of-interest>
  • both parent branches already had <commit-of-interest>

The first category is the one you're interested in. You can usually tell which category the merge is in by looking at the commit subject line. Start at the bottom of the list; the oldest merges are the most likely to be in the first category.

It's technically possible to write a script to filter out merges in the second and third categories (just test to see if <commit-of-interest> is reachable by the merge's first parent), but I've never found it to be necessary.

If you need to do a more in-depth study of the commit history then I recommend looking at the history graph:

git log --oneline --graph --color --decorate \
    --ancestry-path <commit-of-interest>..C

You may want to toss in --boundary too, although sometimes that adds too much noise. You could use gitk, but unfortunately the graph it draws doesn't show parentage in the correct order (gitk might draw the edge between a merge and its second parent on the left; git log --graph always draws the second parent edge on the right).

Upvotes: 5

Related Questions