4

I need to check if branch I'm interested is merged to another branch.

With gitpython, I can use its git command object like:

import git
g = git.Git('/path/to/git/repo')
g.branch("--no-merged", "master")
Out[273]: u'* new\n  test'

So it outputs correct branches, but format it returns is kind of not really good. Now I need to parse string and find the branch I'm interested.

I was thinking if the same can be accomplished using:

repo = git.Repo('/path/to/git/repo')
# Check branches using `repo` object as starting point?

With repo object, there are many useful methods that can retrieve useful information which is already parsed into objects, but I did not find how to do same thing with repo object (if it is possible at all?).

2 Answers 2

0

I guess a merged branch is 0 commits ahead on the other (master) branch.

from git import Repo
branch_name = 'is-this-branch-merged'    
repo = Repo('.')
commits_ahead = repo.iter_commits('origin/master..%s' % branch_name)
commits_ahead_count = sum(1 for c in commits_ahead)
is_merged = (commits_ahead_count == 0)

Would love to know of a better version where you can find all 'already merged' branches easily.

1
  • 1
    I used repo.git.branch('--merged') and parsed the out string. Commented May 14, 2018 at 14:12
0

I was tasked recently with identifying stale branches in a repo with 300+ branches.

This worked for me (for finding all branches merged into a branch named feature/F12345-example-feature, for instance):

repo.git.branch('-r', '--merged', 'origin/feature/F12345-example-feature')

Note that '-r' and the remote prefix ('origin', in this case) are required in order to resolve remote branches.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.