Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

git

python

pygit2

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?

like image 870
Drake Guan Avatar asked Oct 01 '14 04:10

Drake Guan


People also ask

How do I find the branch name in terminal?

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.

Can a branch name have '/' in Git?

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 .


2 Answers

To get the conventional "shorthand" name:

from pygit2 import Repository

Repository('.').head.shorthand  # 'master'
like image 71
Razzi Abuissa Avatar answered Oct 03 '22 23:10

Razzi Abuissa


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
like image 30
Andrew C Avatar answered Oct 04 '22 01:10

Andrew C