git 如何通过pygit2获取当前签出的Git分支名称?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26134026/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the current checked out Git branch name through pygit2?
提问by Drake Guan
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?
采纳答案by Andrew C
From PyGit Documentation
来自 PyGit 文档
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.
您将获得包括 /refs/heads/ 在内的全名。如果您不想将其删除或使用速记代替名称。
./pygit_test.py
Head is refs/heads/master
Head is refs/heads/master
回答by Razzi Abuissa
To get the conventional "shorthand" name:
要获得传统的“速记”名称:
from pygit2 import Repository
Repository('.').head.shorthand # 'master'