使用GitPython模块获取远程HEAD分支

9

我正在尝试使用GitPython编写一些Python脚本来简化我的日常任务,因为我管理着许多分支。

当涉及到编写复杂的脚本时,我对Python也很陌生。

这是我使用的API:GitPython API文档

我想用GitPython编写一个简单的程序,解析出显示HEAD远程分支指向的部分。换句话说,我基本上想获取remotes/origin/HEAD

$ git branch -a
  master
* branch_to_remove
  remotes/origin/HEAD -> origin/master
  remotes/origin/master
  remotes/origin/testing

我浏览了API文档很多次,起初我很难理解这些API文档的Python格式,除了在class git.refs.reference.Reference(repo, path, check_path=True)中使用remote_head之外,我找不到其他有用的东西来做这件事。

但是我甚至不知道如何调用/初始化它。

这是我目前所拥有的,你可以看出我正在尝试什么,只需将其重置为“无分支”状态并删除我所在的当前分支:

import git
from git import *
repo = git.Repo("/some/path/testing")
repo.git.branch()
[some code to get the remotes/origin/HEAD, set it to remoteHeadBranch ]
repo.git.checkout(remoteHeadBranch)  # this should reset the Git back to 'no branch' state
repo.git.checkout(D="branch_to_remove")

任何帮助都非常感激!谢谢。
3个回答

4
我刚看到你的问题,我对gitPython很感兴趣,看起来是一个非常好的工具。我在GitPython文档中寻找这个特定的问题,但没有找到,但是如果你在github上搜索,你会发现有很多测试,并且有一个关于删除新分支的测试。
当你搜索“remove new branch”时,你会看到如下内容:
# remove new branch
Head.delete(new_remote_branch.repo, new_remote_branch)

GitPython参考文档


谢谢您的评论!我会尝试一下!有人能帮我一下吗,当我阅读这些Python API文档时?我是一个Java程序员,这些文档对我来说非常不同和难以理解 :-(谢谢! - samxiao
这样做是*不行的,因为你不能删除当前所在的分支,所以第一步总是返回到“无分支”状态,这就是我正在尝试做的事情。切换到“无”分支状态时出错。 'git branch -d newMaster' 返回退出状态1:错误:无法删除当前所在的分支“newMaster”。 - samxiao

3

打印当前分支:

print(repo.head.ref)

列出分支
print [str(b) for b in repo.heads]

检出一个分支

repo.heads[branch].checkout()

或者 repo.git.checkout(分支)

如果你想删除一个分支,你需要在一个不同的本地分支中,你可以通过几种方式来实现

repo.heads['master'].checkout()

或者 repo.git.checkout('master') 或者 repo.git.checkout('remotes/origin/master')

希望这可以帮助到您


不,这与问题无关。提问者特别询问的是远程 HEAD。 - flying sheep

1

next(ref.ref.name for ref in repo.remotes.origin.refs if ref.name == "origin/HEAD")

repo.remotes.origin.refs将会给你一个远程分支列表。筛选出指向HEAD的分支,并检查它所指向的位置(ref<.name>)。

现在你得到的是类似于"origin/master"或者"origin/main"的东西。


对我来说,[ref for ref in repo.remotes.origin.refs if ref.name == "origin/HEAD"] 返回一个空列表。我使用的是 git version 2.36.2 - akaihola

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接