如何使用GitPython检出一个分支

34
我使用GitPython克隆了一个存储库,现在我想检出一个分支并更新本地存储库的工作树以包含该分支的内容。最好能够在执行此操作之前检查该分支是否存在。这是我目前的进展:
import git

repo_clone_url = "git@github.com:mygithubuser/myrepo.git"
local_repo = "mytestproject"
test_branch = "test-branch"
repo = git.Repo.clone_from(repo_clone_url, local_repo)
# Check out branch test_branch somehow
# write to file in working directory
repo.index.add(["test.txt"])
commit = repo.index.commit("Commit test")

我不确定应该在上面的注释中放什么。 文档 似乎给出了一个分离 HEAD 的示例,但没有说明如何切换到命名分支。


1
非常有用的问题。不确定作者是如何忽略这个问题的。 - NuclearPeon
2个回答

56

如果该分支存在:

repo.git.checkout('branchename')

如果没有:

repo.git.checkout('-b', 'branchename')

基本上,使用 GitPython,如果您知道如何在命令行中执行操作,但不知道如何在 API 中执行操作,请使用 repo.git.action("不包括 'git' 和 'action' 的您的命令"),例如:git log --reverse => repo.git.log('--reverse')


谢谢,你知道如何检查本地分支是否存在吗? - Alex Spurling
是的。我甚至知道其中两个!而且我肯定可以在几分钟内想象出更多!但是,它们都不是很好,因为它们都基于同一件事情。GitPython只计算并转发git命令行到操作系统并解析结果。你能做的最好的事情就是尝试一些东西并期望一个git.exc.GitCommandError。如果发生分支不存在或者你搞砸了你的代码...要检查的内容:repo.git.checkout('branchename')repo.git.rev_parse('--verify', 'branchname')。它不会执行相同的git操作,但会给你完全相同的结果。 - Arount
@Arount 我正在使用你列出的第一个命令,虽然我没有收到错误信息。但是似乎仓库并没有切换到该分支?我可能漏掉了什么吗? - Kyle Swanson
@Arount在此处记录了我的问题 -> https://stackoverflow.com/questions/55622824/how-to-query-the-log-of-a-specific-git-repo-branch-using-gitpython - Kyle Swanson
4
我再怎么说也表达不够,但还是要谢谢你。你回答的最后一部分终于让我明白了这个软件包。我已经连续两天在努力理解它了。这应该是GitPython文档中的第一件事情。 - Daniel Lavedonio de Lima

1
同一个分支的检出可以通过"高级仓库使用"(低级API)来实现,就像这样:repo.git.checkout(..)。在gitpython中,可以使用这种方式来实现。
new_branch = repo.create_head("new_branch")
assert repo.active_branch != new_branch  # It's not checked out yet

repo.head.reference = new_branch  # this makes the ckeckout
assert not repo.head.is_detached

谢谢。但是为什么你要这样做,而不是使用repo.git.checkout('new_branch')呢? - undefined
@AlexSpurling我相信有些开发者可能有理由。在这种情况下,我想这样的调用更轻量级,不会在底层调用子进程? - undefined

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