Last active
May 13, 2017 11:22
-
-
Save kirberich/f2f5db1d74834105d135b8efa47749ff to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import github3 | |
# example code: | |
github = Github( | |
token='token', | |
repo_name='some_repo', | |
) | |
github.stage('articles/some_article.md', 'This is some new content') | |
github.publish('commit message') | |
class Github: | |
"""Super basic github API wrapper to allow updating multiple files.""" | |
def __init__(self, token, repo_name, branch_name=None, | |
author_email=None, author_name=None): | |
"""Instantiate github wrapper. | |
Requires a personal access token, which you can get from the github account settings. | |
Provide branch_name if you don't want to use the default branch. | |
""" | |
self.staging_data = {} | |
self.github = github3.login(token=token) | |
user = self.github.me() | |
self.username = user.login | |
self.repo = self.github.repository(self.username, repo_name) | |
self.branch_name = branch_name or self.repo.default_branch | |
self.branch = self.repo.branch(self.branch_name) | |
author_email = author_email or user.email | |
if not author_email: | |
raise Exception("Please supply author_email or make sure you have a public email set up in github!") | |
author_name = author_name or user.name | |
if not author_name: | |
raise Exception("Please supply author_name or make sure you have a public name set up in github!") | |
self.author_info = { | |
'name': author_name, | |
'email': author_email | |
} | |
def _generate_tree(self): | |
tree_sha = self.branch.commit.commit.tree.sha | |
tree_data = [] | |
for path, content in self.staging_data.items(): | |
blob = self.repo.create_blob(content, encoding='utf-8') | |
tree_data.append( | |
{'path': path, 'mode': '100644', 'type': 'blob', 'sha': blob} | |
) | |
tree = self.repo.create_tree(tree_data, tree_sha) | |
return tree | |
def _head(self): | |
"""Return the reference to the branch's HEAD.""" | |
return self.repo.ref('heads/{}'.format(self.branch_name)) | |
def stage(self, filename, content): | |
"""Stage changes to a file.""" | |
self.staging_data[filename] = content | |
def publish(self, message): | |
"""Commit and push staged changes. | |
Requires a commit message, author email and name. | |
""" | |
tree = self._generate_tree() | |
commit = self.repo.create_commit( | |
message, | |
tree.sha, | |
[self.branch.commit.sha], | |
author=self.author_info, | |
committer=self.author_info | |
) | |
self._head().update(commit.sha) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment