如何使用GitPython检出分支

Ale*_*ing 12 python git 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")
Run Code Online (Sandbox Code Playgroud)

我不知道在上述评论的位置放什么.该文件似乎给出了如何拆卸头,但不知道如何检出一个名为分支的例子.

Aro*_*unt 16

如果分支存在:

repo.git.checkout('branchename')
Run Code Online (Sandbox Code Playgroud)

如果不:

repo.git.checkout('-b', 'branchename')
Run Code Online (Sandbox Code Playgroud)

基本上,使用GitPython,如果你知道如何在命令行中执行它,但不在API中,只需使用repo.git.action("your command without leading 'git' and 'action'"),例如:git log --reverse=>repo.git.log('--reverse')

  • 我无法说得足够多,但谢谢你。你的回答的最后一部分终于让我理解了这个包。我连续两天试图理解这一点。应该是 GitPython 文档中的第一件事。 (4认同)