Search code examples
pythongitpygit2

How to get the current checked out Git branch name through pygit2?


This question should be related to:

But I am wondering how to do that through pygit2?


Solution

  • From PyGit Documentation

    Either of these should work

    #!/usr/bin/python
    from pygit2 import Repository
    
    repo = Repository('/path/to/your/git/repo')
    
    # option 1
    head = repo.head
    print("Head is " + head.name)
    
    # option 2
    head = repo.lookup_reference('HEAD').resolve()
    print("Head is " + head.name)
    

    You'll get the full name including /refs/heads/. If you don't want that strip it out or use shorthand instead of name.

    ./pygit_test.py  
    Head is refs/heads/master 
    Head is refs/heads/master