在GitPython中检出或列出远程分支
我在这个模块里找不到查看或列出远程/本地分支的选项:https://gitpython.readthedocs.io/en/stable/
7 个回答
17
要列出分支,你可以使用:
from git import Repo
r = Repo(your_repo_path)
repo_heads = r.heads # or it's alias: r.branches
r.heads
会返回一个 git.util.IterableList
(它是 list
的一个子类),里面包含了多个 git.Head
对象,所以你可以:
repo_heads_names = [h.name for h in repo_heads]
如果你想切换到比如说 master
分支,可以这样做:
repo_heads['master'].checkout()
# you can get elements of IterableList through it_list['branch_name']
# or it_list.branch_name
问题中提到的模块是 GitPython
,它已经从 gitorious
转移到了 Github。
19
对于那些只想打印远程分支的人:
# Execute from the repository root directory
repo = git.Repo('.')
remote_refs = repo.remote().refs
for refs in remote_refs:
print(refs.name)
9
在你完成了
from git import Git
g = Git()
(可能还需要执行其他命令来初始化g
,使其指向你关心的仓库)后,所有对g
的属性请求基本上都会变成对git attr *args
的调用。
所以:
g.checkout("mybranch")
应该能实现你想要的效果。
g.branch()
这个命令会列出所有的分支。不过要注意,这些都是比较底层的命令,它们返回的结果和git程序返回的结果是完全一样的。所以,不要期待会有一个漂亮的列表。结果只会是一串多行文本,其中一行的开头会有一个星号。
在这个库里可能还有更好的方法来实现这个功能。例如,在repo.py
里有一个特别的active_branch
命令。你需要稍微看看源代码,自己找找看。