如何使用GitPython签出分支 [英] How to check out a branch with GitPython

查看:138
本文介绍了如何使用GitPython签出分支的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用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的示例. ,而不是如何检出命名分支.

解决方案

如果分支存在:

repo.git.checkout('branchename')

如果不是:

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


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

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:

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")

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

解决方案

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签出分支的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆