git 如何使用 GitPython 签出分支

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47872070/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-19 13:00:22  来源:igfitidea点击:

How to check out a branch with GitPython

pythongitgitpython

提问by Alex Spurling

I have cloned a repository with GitPython, now I would like to checkout a branch and update the local repository's working tree with the contents of that branch. Ideally, I'd also be able to check if the branch exists before doing this. This is what I have so far:

我已经使用 GitPython 克隆了一个存储库,现在我想签出一个分支并使用该分支的内容更新本地存储库的工作树。理想情况下,我还可以在执行此操作之前检查分支是否存在。这是我到目前为止:

import git

repo_clone_url = "[email protected]: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")

I am not sure what to put in the place of the comments above. The documentationseems to give an example of how to detach the HEAD, but not how to checkout an named branch.

我不知道用什么来代替上面的评论。该文档似乎给出了如何分离 HEAD 的示例,但没有给出如何检出命名分支的示例。

回答by Arount

If the branch exists:

如果分支存在:

repo.git.checkout('branchename')

If not:

如果不:

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


Basically, with GitPython, if you know how to do it within command line, but not within the API, just use repo.git.action("your command without leading 'git' and 'action'"), example: git log --reverse=> repo.git.log('--reverse')

基本上,对于 GitPython,如果您知道如何在命令行中而不是在 API 中执行此操作,只需使用repo.git.action("your command without leading 'git' and 'action'"), 示例:git log --reverse=>repo.git.log('--reverse')