pythongitbranchdulwich

Getting current Git branch name using dulwich library


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.


Solution

  • 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'