Uriel Frankel
Uriel Frankel

Reputation: 14622

git - find divergences of a branch

I have a branch A that diverged into other branches. I also have more branches that didn't diverge from that A branch. How can I find which branches diverged from A?

For example:

-------------------------------- Master
 \  \
  \   -------------------------- A
   \         \
    \          ----------------- B
     \           \
      \            ------------- C
       \
        \
          ---------------------- D
                \
                  -------------- E

I want the output to be B and C.

Upvotes: 4

Views: 1129

Answers (1)

Kristján
Kristján

Reputation: 18833

git branch --contains should provide what you want.

The --contains option shows us all branches that contain a specific commit-ish. The commit we want is the first one on A after it branched from master. It'd be easier to get the merge-base of A and master, but that will also be contained by master and anything branching from master after A does.

We can find the first commit SHA on A with:

git log --format=format:%h master..A | tail -1

%h gives us the short commit SHA, so we don't have to slice up the default output afterwards. tail picks off the earliest commit on A, or you could also pass log the --reverse option and use head. If your branch is a million commits long, that will let processes die sooner, but at that point you've probably got other concerns.

Then, we use A'a first SHA in branch --contains:

git branch --contains $(git log --format=format:%h master..A | tail -1) --no-merged A

The --no-merged A option ignores branch A itself, which clearly contains the commit we picked.

If you've currently checked out one of the branches that diverged from A, git will indicate that with a * like it does when you just run git branch. I can't find a way to strip that in pure Git, but you can use any number of unix commands to remove it from the output.

Upvotes: 4

Related Questions