如何使用pygit2检出一个分支?

6

我想使用pygit2来检出分支名称。

例如,如果我有两个分支:masternew,并且HEADmaster上,我希望能够执行以下操作:

import pygit2
repository = pygit2.Repository('.git')
repository.checkout('new')

甚至更多
import pygit2
repository = pygit2.Repository('.git')
repository.lookup_branch('new').checkout()

但两者均无效,并且pygit2文档没有提到如何检出分支。

2个回答

9

看起来你可以做到:

import pygit2
repo = pygit2.Repository('.git')
branch = repo.lookup_branch('new')
ref = repo.lookup_reference(branch.name)
repo.checkout(ref)

可以使用pygit2检出一个标签吗? - Khaled

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)

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