Danilo Bargen
Danilo Bargen

Reputation: 19482

Determine whether two Git branches have diverged

I'd like to determine whether two Git branches have diverged or whether one of the branches could simply be fast forwarded to the other branch.

In other words, I want to check whether the current HEAD of one of the branches has been merged into the other branch at some point or if it contains commits that are not in the other branch.

Is there a way to do this without actually merging the two branches? A simple git diff does not help in this case.

Upvotes: 5

Views: 4199

Answers (4)

ebaxt
ebaxt

Reputation: 8417

You can use git merge-base:

git merge-base branch1 branch2

A description can be found here.

Upvotes: 7

sschuberth
sschuberth

Reputation: 29866

I'm using this shell script snippet for that purpose:

git_is_merged () {
    local revlist
    if revlist=$(git rev-list -1 "$1" --not "$2"); then
        if [ "$revlist" = "" ]; then
            echo "'$1' IS merged into '$2'."
        else
            echo "'$1' is NOT merged into '$2'."
        fi
    fi
}

alias gim='git_is_merged'

Use it like gim origin/devel origin/master to determine whether origin/devel is merged into origin/master.

Edit: For the sake of completeness, if you are working with named branches only, you could also use

git branch --contains origin/devel | grep -q origin/master && echo "Merged" || echo "Not merged"

or

git branch --merged origin/master | grep -q origin/devel && echo "Merged" || echo "Not merged"

for the same purpose.

Upvotes: 4

jørgensen
jørgensen

Reputation: 10579

If it can simply be fast-forwarded, git merge --ff-only otherbranch will succeed. (And if it can't, it will be rejected rather than a merge commit being made.)

Upvotes: 4

François
François

Reputation: 8138

If you want a graphical tool, you can use gitk branch1 branch2. This also allows you to inspect the diverging commits, if needed.

Upvotes: 0

Related Questions