如何用pygit2切换分支?
我想用 pygit2
来切换到一个分支。
比如说,我有两个分支:master
和 new
,而现在的状态在 master
上。我希望能这样做:
import pygit2
repository = pygit2.Repository('.git')
repository.checkout('new')
或者甚至这样:
import pygit2
repository = pygit2.Repository('.git')
repository.lookup_branch('new').checkout()
但是这两种方法都不行,而且 pygit2 的文档 里也没有提到怎么切换分支。
2 个回答
1
我在这方面遇到了很多麻烦,而这是关于这个问题在StackOverflow上为数不多的相关帖子之一。所以我想分享一个完整的示例,教大家如何从Github上克隆一个代码库,并切换到指定的分支。
def clone_repo(clone_url, clone_path, branch, auth_token):
# Use pygit2 to clone the repo to disk
# if using github app pem key token, use x-access-token like below
# if you were using a personal access token, use auth_method = 'x-oauth-basic' AND reverse the auth_method and token parameters
auth_method = 'x-access-token'
callbacks = pygit2.RemoteCallbacks(pygit2.UserPass(auth_method, auth_token))
pygit2_repo = pygit2.clone_repository(clone_url, clone_path, callbacks=callbacks)
pygit2_branch = pygit2_repo.branches['origin/' + branch]
pygit2_ref = pygit2_repo.lookup_reference(pygit2_branch.name)
pygit2_repo.checkout(pygit2_ref)
9
看起来你可以这样做:
import pygit2
repo = pygit2.Repository('.git')
branch = repo.lookup_branch('new')
ref = repo.lookup_reference(branch.name)
repo.checkout(ref)