This question should be related to:
But I am wondering how to do that through pygit2?
In order to add branch name to bash prompt we have to edit the PS1 variable(set value of PS1 in ~/. bash_profile). This git_branch function will find the branch name we are on. Once we are done with this changes we can nevigate to the git repo on the terminal and will be able to see the branch name.
Naming rules for refname: Git imposes the following rules on how references are named: They can include slash / for hierarchical (directory) grouping, but no slash-separated component can begin with a dot . or end with the sequence . lock .
To get the conventional "shorthand" name:
from pygit2 import Repository
Repository('.').head.shorthand # 'master'
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With