Created
October 12, 2021 10:01
-
-
Save naimurhasan/70624517e01a755f8434ad492d78bb1c to your computer and use it in GitHub Desktop.
Using pygithub upload file | Advantage do not need to clone the repo.
This file contains hidden or 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 base64 | |
from github import Github | |
from github import InputGitTreeElement | |
g = Github("YOUR TOKEN") | |
# for org repo | |
# org = g.get_organization("NaimurDev") | |
# repo = org.get_repo('test_file') | |
# for personal repo | |
repo = g.get_user().get_repo('repo-name') | |
all_files = [] | |
contents = repo.get_contents("") | |
print('contents') | |
print(contents) | |
file_list = [ | |
'hello2.txt', | |
] | |
file_names = [ | |
'hello2.txt', | |
] | |
commit_message = 'python commit' | |
master_ref = repo.get_git_ref('heads/main') | |
master_sha = master_ref.object.sha | |
base_tree = repo.get_git_tree(master_sha) | |
element_list = list() | |
for i, entry in enumerate(file_list): | |
with open(entry) as input_file: | |
data = input_file.read() | |
if entry.endswith('.png'): # images must be encoded | |
data = base64.b64encode(data) | |
element = InputGitTreeElement(file_names[i], '100644', 'blob', data) | |
element_list.append(element) | |
tree = repo.create_git_tree(element_list, base_tree) | |
parent = repo.get_git_commit(master_sha) | |
commit = repo.create_git_commit(commit_message, tree, [parent]) | |
master_ref.edit(commit.sha) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment