GitPython中如何检出或列出远程分支

22
7个回答

19

对于那些只想打印远程分支的人:

# Execute from the repository root directory
repo = git.Repo('.')
remote_refs = repo.remote().refs

for refs in remote_refs:
    print(refs.name)

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此处有存档。


2
看起来这里有文档:https://gitpython.readthedocs.io/en/stable/reference.html?highlight=branch#git.repo.base.Repo.branches - scorpiodawg

9

完成以下步骤后

from git import Git
g = Git()

(并可能使用其他命令来将g初始化到您关心的存储库)对g的所有属性请求都或多或少地转换为调用git attr *args

因此:

g.checkout("mybranch")

应该做你想要的事情。

g.branch()

将列出分支。但是请注意,这些命令非常低级,它们将返回git可执行文件返回的确切代码。因此,请不要期望得到一个漂亮的列表。它只是几行字符串,并且其中一行以星号作为第一个字符。
在库中可能有更好的方法来完成这个任务。例如,在repo.py中有一个特殊的active_branch命令。您需要查看源代码并自己找到它。

当我运行 r = Git.clone("git ...") 时,r.checkout("develop") 不起作用。AttributeError: 'str' object has no attribute 'checkout'。 - Mike
好的,看起来我需要运行 g = Git("dir") 然后我可以进行 checkout。 - Mike

5

我也遇到了类似的问题。在我的情况下,我只想列出本地跟踪的远程分支。这个方法对我有效:

import git

repo = git.Repo(repo_path)
branches = []
for r in repo.branches:
    branches.append(r)
    # check if a tracking branch exists
    tb = t.tracking_branch()
    if tb:
        branches.append(tb) 

如果需要所有远程分支,我建议直接运行git命令:
def get_all_branches(path):
    cmd = ['git', '-C', path, 'branch', '-a']
    out = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
    return out

6
如果您已经有一个Repo实例,您可以直接调用git命令,例如:repo.git.branch('-a') - dusktreader

4

为了让它更加明显 - 要从当前仓库目录获取远程分支列表:

import os, git

# Create repo for current directory
repo = git.Repo(os.getcwd())

# Run "git branch -r" and collect results into array
remote_branches = []
for ref in repo.git.branch('-r').split('\n'):
    print(ref)
    remote_branches.append(ref)

1
基本上,使用GitPython,如果你知道如何在命令行中执行它,但不知道如何在API中执行,只需使用repo.git.action("your command without leading 'git' and 'action'"),例如:git log --reverse => repo.git.log('--reverse')
在这种情况下https://dev59.com/f1YN5IYBdhLWcg3wK1bO#47872315 所以我尝试了这个命令:
repo = git.Repo()

repo.git.checkout('-b', local_branch, remote_branch)

这个命令可以创建一个新的本地分支名local_branch(如果已经存在,则会引发错误),并设置为跟踪远程分支remote_branch
它运行得非常好!

0

我在这里采用了稍微不同的方法,基于获取一个可检出分支列表的愿望:

repo = git.Repo(YOUR_REPO_HERE)
branch_list = [r.remote_head for r in repo.remote().refs]

与使用refs.name的答案不同,这个方法获取的名称不带远程前缀,以您想要用于检出存储库的形式呈现。


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