0

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.

Dull Bananas
  • 892
  • 7
  • 29

2 Answers2

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
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
  • 1
    Note 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
  • 1
    The 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
  • 1
    oh. so i will just use your example and replace `commit_sha` with `_` – Dull Bananas Nov 09 '19 at 22:06