使用PyGitHub和PyGit2创建、克隆和推送到GitHub存储库

12

如何使用Python和pyGitHub与pyGit2库创建一个新的GitHub存储库、克隆它、更改文件并将其推回GitHub?

这两个库的文档都非常少,几乎没有任何示例。


2
对于需要创建初始提交的人,请参见https://dev59.com/EG8NtIcB2Jgan1zniFPR#70842647。 - Connor Fuhrman
1个回答

35

以下是我是如何使其工作的。我不是要表明这是实现此目的的绝对最佳方式,但我希望这能为将来有需要的人提供一个很好的示例。

from github import Github
import pygit2

# using username and password establish connection to github
g = Github(userName, password)
org = g.get_organization('yourOrgName')

#create the new repository
repo = org.create_repo(projectName, description = projectDescription )

#create some new files in the repo
repo.create_file("/README.md", "init commit", readmeText)

#Clone the newly created repo
repoClone = pygit2.clone_repository(repo.git_url, '/path/to/clone/to')

#put the files in the repository here

#Commit it
repoClone.remotes.set_url("origin", repo.clone_url)
index = repoClone.index
index.add_all()
index.write()
author = pygit2.Signature("your name", "your email")
commiter = pygit2.Signature("your name", "your email")
tree = index.write_tree()
oid = repoClone.create_commit('refs/heads/master', author, commiter, "init commit",tree,[repoClone.head.get_object().hex])
remote = repoClone.remotes["origin"]
credentials = pygit2.UserPass(userName, password)
remote.credentials = credentials

callbacks=pygit2.RemoteCallbacks(credentials=credentials)

remote.push(['refs/heads/master'],callbacks=callbacks)

我花了两天时间试图通过缺乏示例来回答这个问题,所以我希望这可以帮助将来的某个人。


2
谢谢您添加这个,正是我所需要的! - Kyle Sponable
1
谢谢!这是一个很好的示例,展示了如何同时使用两个库! - Jordi Riera
1
顺便说一下,如果库的作者能够加入你的示例代码,那就太棒了。你有尝试将示例代码提交到文档中吗? - Jordi Riera
1
这是一个非常好的例子。它为我节省了大量时间,因为我不需要编写一个专门的AWS Lambda来将代码从GitHub移动到S3。 - Allen Fisher
4
对于更新版本的pygit2,您需要将create_commit的最后一个参数更改为[repoClone.head.target],因为get_object()已被弃用。 - Webucator

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