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.
Asked
Active
Viewed 378 times
2 Answers
1
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.

jelmer
- 2,405
- 14
- 27
-
Thanks. I chose to do `(_, ref), _ = x.refs.follow(b'HEAD')` – Dull Bananas Nov 09 '19 at 17:00
-
I have another question about Dulwich: https://stackoverflow.com/q/58781823/11041613 – Dull Bananas Nov 09 '19 at 17:35
0
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'

Dull Bananas
- 892
- 7
- 29
-
1Note that in theory, the length of the refchain can be something other than 2. If you have a detached HEAD, the refchain will be [b"HEAD"]. If the master branch is a symref to another branch (not common, but possible) then the refchain may be longer than 2 entries. – jelmer Nov 09 '19 at 19:40
-
So do I just put a star in front of the 2nd underscore (`(_, ref), *_ = `) to avoid this issue? – Dull Bananas Nov 09 '19 at 21:30
-
1The returned tuple always has two elements: a refchain and the commit SHA. The refchain is a list that can have between 1 and many elements, not necessarily two. This is why my example above used ref_chain[1]. – jelmer Nov 09 '19 at 21:56
-
1oh. so i will just use your example and replace `commit_sha` with `_` – Dull Bananas Nov 09 '19 at 22:06