Answer a question

This question should be related to:

  • How to get the current branch name in Git?
  • Get git current branch/tag name
  • How to get the name of the current git branch into a variable in a shell script?
  • How to programmatically determine the current checked out Git branch

But I am wondering how to do that through pygit2?

Answers

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
Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐