Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/357.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用pygit2签出分支?_Python_Git_Pygit2 - Fatal编程技术网

Python 如何使用pygit2签出分支?

Python 如何使用pygit2签出分支?,python,git,pygit2,Python,Git,Pygit2,我想使用pygit2签出分支名称 例如,如果我有两个分支:master和new,并且HEAD位于master,我希望能够做到: import pygit2 repository = pygit2.Repository('.git') repository.checkout('new') 甚至 import pygit2 repository = pygit2.Repository('.git') repository.lookup_branch('new').checkout() 但是这两种

我想使用
pygit2
签出分支名称

例如,如果我有两个分支:
master
new
,并且
HEAD
位于
master
,我希望能够做到:

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

import pygit2
repository = pygit2.Repository('.git')
repository.lookup_branch('new').checkout()
但是这两种方法都不起作用,而且也没有提到如何结帐分支机构。

您似乎可以做到:

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

我在这方面遇到了很多麻烦,这是唯一与此相关的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)