How to find the common ancestor commit of two other commits?

Mathieu Yargeau June 3, 2015

I need to find the common ancestor (commit id) of two commits (which are not in the same branch).

 

I found the "Git merge-base" command, tried it, and it works. However, I was wondering it the Stash API was offering the same functionality. How can I do the same from the Stash API?

1 answer

1 accepted

Comments for this post are closed

Community moderators have prevented the ability to post new answers.

Post a new question

1 vote
Answer accepted
Balázs Szakmáry
Rising Star
Rising Star
Rising Stars are recognized for providing high-quality answers to other users. Rising Stars receive a certificate of achievement and are on the path to becoming Community Leaders.
June 3, 2015

You can keep recursively querying their parents with a piece of code similar to this:

private void ProcessCommitHashRecursive(final String hash,
                                        final Repository repository)
{
    final CommitRequest request = new CommitRequest.Builder(repository, hash).build();
    Commit commit = commitService.getCommit(request);
    for (MinimalCommit parent : commit.getParents())
    {
        ProcessCommitHashRecursive(parent.getId(), repository);
    }
}

and find the first matching. (Make sure you have something in the recursion to ensure that it always terminates after a while.)

That said it is probably much simpler and less resource-intensive to make a call to git merge-base by using CommandBuilder.

TAGS
AUG Leaders

Atlassian Community Events