8

我正在尝试使用 GitPython 编写一些 Python 脚本,当我管理许多分支时,我可以使用它来简化我的日常任务。

在编写复杂的脚本时,我对 Python 也很陌生。

这是我使用的 API:GitPython API doc

我想用 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 格式,除了remote_headclass git.refs.reference.Reference(repo, path, check_path=True)

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

这是我到目前为止所做的,你可以告诉我我正在尝试做什么,只需重置为“无分支”状态并删除我所在的当前分支:

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")

任何帮助深表感谢!

谢谢。

4

3 回答 3

4

我刚刚看到你的问题,我想知道这个 gitPython,看起来非常不错的工具,我一直在 GitPython 文档中寻找这个特定的问题,但没有幸运,但如果你在 github 上搜索,你会在那里看到很多测试,并且有一个对此进行测试。

当您搜索“删除新分支”时,您会看到如下内容:

# remove new branch
Head.delete(new_remote_branch.repo, new_remote_branch)

GitPython 参考

于 2012-06-12T07:24:24.333 回答
3

要打印当前分支:

print(repo.head.ref)

列出分支

print [str(b) for b in repo.heads]

结帐分支

repo.heads[branch].checkout()

或者repo.git.checkout(branch)

如果您尝试删除一个分支,您需要位于不同的 LOCAL 分支中,您可以通过多种方式执行此操作

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

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

希望这可以帮助

于 2015-04-17T03:29:45.870 回答
1

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

repo.remotes.origin.refs会给你一个远程分支的列表。过滤HEAD并检查它指向的内容(ref<.name>)。

你现在剩下类似"origin/master"or的东西"origin/main"

于 2021-09-30T07:42:54.673 回答