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

Create, Clone, and Push to GitHub repo using PyGitHub and PyGit2

如何创建一个新的 GitHub 存储库、克隆它、更改文件,然后使用 python 和 pyGitHub 将其推回 github 和pyGit2 库?

这两个库的文档都非常稀疏,几乎没有示例。

以下是我如何让它发挥作用的。我并不是说这是实现它的绝对最佳方式,但我希望它能成为未来某人的好榜样。

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)

我花了两天时间尝试解决缺少示例的问题来回答这个问题,所以我希望这对以后的人有所帮助。