Skip to content

Instantly share code, notes, and snippets.

@ohaval
Created December 12, 2022 06:30
Show Gist options
  • Save ohaval/3c183c83ec91cb528fdc4628efe2fa01 to your computer and use it in GitHub Desktop.
Save ohaval/3c183c83ec91cb528fdc4628efe2fa01 to your computer and use it in GitHub Desktop.
An example shows how to push a single commit with multiple files to an existing branch using PyGithub
"""
Main Steps:
1. Create blob for each file
2. Create tree with the blobs on top of the specific branch
3. Commit the tree
4. Update the branch to point to the new commit
"""
import os
from github import Github, InputGitTreeElement # tested with PyGithub==1.54.1
g = Github(os.environ['GITHUB_TOKEN'])
print(f"Authenticated as {g.get_user().login}")
org = g.get_organization('some-org')
print(f"org: {org}")
repo = org.get_repo('some-repo')
print(f"repo: {repo}")
# Create blobs for each file
blob1, blob2, blob3 = [
repo.create_git_blob(
content="print('Hello World - 1')",
encoding='utf-8',
),
repo.create_git_blob(
content="print('Hello World - 2')",
encoding='utf-8',
),
repo.create_git_blob(
content="print('Hello World - 3')",
encoding='utf-8',
),
]
print(f"blob1: {blob1}")
print(f"blob2: {blob2}")
print(f"blob3: {blob3}")
# Create a new tree with our blobs
new_tree = repo.create_git_tree(
tree=[
InputGitTreeElement(
path="hello-world-1.py",
mode="100644",
type="blob",
sha=blob1.sha,
),
InputGitTreeElement(
path="hello-world-2.py",
mode="100644",
type="blob",
sha=blob2.sha,
),
InputGitTreeElement(
path="hello-world-3.py",
mode="100644",
type="blob",
sha=blob3.sha,
),
],
base_tree=repo.get_git_tree(sha='hello-world')
)
print(f"new_tree: {new_tree}")
# Create a new commit with that tree on top of the current hello-world branch head
commit = repo.create_git_commit(
message="Add multiple files",
tree=repo.get_git_tree(sha=new_tree.sha),
parents=[repo.get_git_commit(repo.get_branch('hello-world').commit.sha)],
)
# Push that commit to the hello-world branch by editing the reference
hello_world_ref = repo.get_git_ref(ref='heads/hello-world')
print(f"hello_world_ref: {hello_world_ref}")
hello_world_ref.edit(sha=commit.sha)
print("DONE")
@aronweiler
Copy link

Awesome. Saved me a lot of work with this example. Thanks @ohaval

@wlennonCMS
Copy link

yes, thanks @ohaval for the time savings!!
a twist on this code for multiple files, I created a tree_list variable and append the new blob and tree elements in a loop.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment