在GitPython中签出或列出远程分支

时间:2010-03-18 20:09:24

标签: python git gitpython

我没有看到在此模块中签出或列出远程/本地分支的选项:https://gitpython.readthedocs.io/en/stable/

6 个答案:

答案 0 :(得分:7)

完成后

from git import Git
g = Git()

(可能还有一些其他命令用于初始化g到您关注的存储库)g上的所有属性请求或多或少地转换为git attr *args的调用。

因此:

g.checkout("mybranch")

应该做你想做的事。

g.branch()

将列出分支。但请注意,这些是非常低级别的命令,它们将返回git可执行文件将返回的确切代码。因此,不要指望一个好的清单。我只是一串几行,一行有一个星号作为第一个字符。

在库中可能有更好的方法可以做到这一点。例如,在repo.py中是一个特殊的active_branch命令。你必须稍微浏览一下这个来源并自己寻找。

答案 1 :(得分:6)

要列出当前可以使用的分支:

from git import Repo
r = Repo(your_repo_path)
repo_heads = r.heads # or it's alias: r.branches

r.heads会返回git.util.IterableListlist对象的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 {{1}}从{{1}}到moved

答案 2 :(得分:4)

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

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

for refs in remote_refs:
    print(refs.name)

答案 3 :(得分:1)

我有类似的问题。在我的情况下,我只想列出本地跟踪的远程分支。这对我有用:

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

答案 4 :(得分:0)

只是为了明白 - 从当前的repo目录中获取远程分支列表:

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)

答案 5 :(得分:0)

基本上,对于GitPython,如果您知道如何在命令行中执行此操作,而不是在API中,请使用repo.git.action(“您的命令不带'git'和'action'”的示例),例如: git log --reverse => repo.git.log('-reverse')

在这种情况下为https://stackoverflow.com/a/47872315/12550269

所以我尝试以下命令:

repo = git.Repo()

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

此命令可以创建一个新的本地分支名称local_branch(如果已经拥有,rasie错误)并设置为跟踪远程分支remote_branch

效果很好!