Create, Clone, and Push to GitHub repo using PyGitHub and PyGit2
Asked Answered
P

1

13

How can I create a new GitHub repository, clone it, change files, and then push it back to github using python and the pyGitHub and pyGit2 libraries?

The documentation for both libraries is very sparse and there are almost no examples.

Petronilapetronilla answered 23/3, 2018 at 21:9 Comment(1)
For those that need to create an initial commit please see #70843146Contumacious
P
38

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.

Petronilapetronilla answered 23/3, 2018 at 21:18 Comment(5)
Thank you for adding this its exactly what I needed!Sochi
Thank you! Great example of how to use both libs!Cavefish
By the way, it would be great to see if the authors of the libs would be up to include your example in their code. Did you try to commit your example to the docs ?Cavefish
This is a really good example. It saved me a bunch of time writing a specialized AWS Lambda to move code from GitHub to S3.Cursorial
For newer versions of pygit2, you need to change the last argument of create_commit to [repoClone.head.target] as get_object() is deprecated.Ragged

© 2022 - 2024 — McMap. All rights reserved.