【问题标题】:Create, Clone, and Push to GitHub repo using PyGitHub and PyGit2使用 PyGitHub 和 PyGit2 创建、克隆和推送到 GitHub 存储库
【发布时间】:2018-03-23 21:09:19
【问题描述】:

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

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

【问题讨论】:

标签: python pygit2 pygithub


【解决方案1】:

这是我如何使它工作的。我并不是说这是实现这一点的绝对最佳方式,但我希望它可以为将来的某人提供一个很好的例子。

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)

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

【讨论】:

  • 感谢您添加这正是我所需要的!
  • 谢谢!如何使用这两个库的好例子!
  • 顺便说一句,很高兴看看这些库的作者是否愿意在他们的代码中包含您的示例。您是否尝试将您的示例提交给文档?
  • 这是一个非常好的例子。它为我节省了大量时间编写专门的 AWS Lambda 来将代码从 GitHub 移动到 S3。
  • 对于较新版本的 pygit2,您需要将 create_commit 的最后一个参数更改为 [repoClone.head.target],因为不推荐使用 get_object()。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-21
  • 2018-04-29
  • 1970-01-01
  • 1970-01-01
  • 2021-12-31
  • 1970-01-01
  • 2021-11-18
相关资源
最近更新 更多