I’m trying to add multiple files into a single commit using PyGithub.
I’m looping in my local directory to fetch all the files to be committed and then I’m trying to create a git blob for each.
Then I’m trying to create a new git tree and add into it.
Reference for this approach – https://gist.github.com/ohaval/3c183c83ec91cb528fdc4628efe2fa01
Getting exception –
{“message”: “tree.path contains a malformed path component”, “documentation_url”: “https://docs.github.com/rest/git/trees#create-a-tree”, “status”: “422”}
Here is my code
from github import Github, InputGitTreeElement
g = Github("XXXTokenXXX")
def get_all_file_paths(directory):
# initializing empty file paths list
file_paths = []
# crawling through directory and subdirectories
for root, directories, files in os.walk(directory):
for filename in files:
# join the two strings in order to form the full filepath.
filepath = os.path.join(root, filename)
file_paths.append(filepath)
# returning all file paths
return file_paths
file_paths = get_all_file_paths("./apiproxy")
try:
repo = g.get_repo(GITHUB_REPO)
repo.get_branch(branch="sandbox")
tree = []
for file in file_paths:
blob = repo.create_git_blob(
content=file,
encoding='utf-8',
)
tr = InputGitTreeElement(
path=file,
mode="100644",
type="blob",
sha=blob.sha,
)
tree.append(tr)
new_tree = repo.create_git_tree(
tree,
base_tree=repo.get_git_tree(sha='sandbox')
)
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('sandbox').commit.sha)],
)
print('Added into github sandbox branch.')
except Exception as e:
print(e)
print('Git failure')