Getting current Git branch name using dulwich library

473 Views Asked by At

I am trying to get the name of the current branch of a Git repository using the dulwich library. I have spent lots of time looking through dulwich's documentation but could not find out how to do this.

2

There are 2 best solutions below

4
Dull Bananas On BEST ANSWER

This is my final result, which removes the initial refs/heads/ prefix:

>>> from dulwich.repo import Repo
>>> import re
>>> repo = Repo('.')
>>> (_, ref), _ = repo.refs.follow(b'HEAD')
>>> match = re.search(r'/([^/]+)$', ref.decode('utf-8')
>>> match[1]
'master'
2
jelmer On

The active branch is whatever branch "HEAD" currently points at. You can get that ref in Dulwich using something like this:

 >>> from dulwich.repo import Repo
 >>> x = Repo('.')
 >>> ref_chain, commit_sha = x.refs.follow(b'HEAD')
 >>> ref_chain[1]
 b'refs/heads/master'

There is now also a dulwich.porcelain.active_branch function in master that can do this for you.