8

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

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

4

1 回答 1

26

Here's how I was able to make it work. I don't mean to indicate that this is the absolute best way to implement this, but I hope it serves as a good example for someone in the future.

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)

I spent two days trying to work through the lack of examples to answer this question, so I hope this helps someone in the future.

于 2018-03-23T21:18:25.780 回答