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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-19 10:27:08  来源:igfitidea点击:

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

pythongitpygit2

采纳答案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'