Search code examples
pythongitgoogle-colaboratorypygithub

Creating a repository and commiting a file with PyGithub


I've seen the topic of commiting using PyGithub in many other questions here, but none of them helped me, I didn't understood the solutions, I guess I'm too newbie.

I simply want to commit a file from my computer to a test github repository that I created. So far I'm testing with a Google Collab notebook.

This is my code, questions and problems are in the comments:

from github import Github

user = '***'
password = '***'

g = Github(user, password)
user = g.get_user()

# created a test repository
repo = user.create_repo('test')

# problem here, ask for an argument 'sha', what is this?
tree = repo.get_git_tree(???)

file = 'content/echo.py'

# since I didn't got the tree, this also goes wrong
repo.create_git_commit('test', tree, file)

Solution

  • The sha is a 40-character checksum hash that functions as a unique identifier to the commit ID that you want to fetch (sha is used to identify each other Git Objects as well).

    From the docs:

    Each object is uniquely identified by a binary SHA1 hash, being 20 bytes in size, or 40 bytes in hexadecimal notation. Git only knows 4 distinct object types being Blobs, Trees, Commits and Tags.

    The head commit sha is accessible via:

    headcommit      = repo.head.commit
    headcommit_sha  = headcommit.hexsha
    

    Or master branch commit is accessible via:

    branch          = repo.get_branch("master")
    master_commit   = branch.commit
    

    You can see all your existing branches via:

    for branch in user.repo.get_branches():
        print(f'{branch.name}')
    

    You can also view the sha of the branch you'd like in the repository you want to fetch.

    The get_git_tree takes the given sha identifier and returns a github.GitTree.GitTree, from the docs:

    Git tree object creates the hierarchy between files in a Git repository

    You'll find a lot of more interesting information in the docs tutorial.

    Code for repository creation and to commit a new file in it on Google CoLab:

    !pip install pygithub
    
    from github import Github
    
    user = '****'
    password = '****'
    
    g = Github(user, password)
    user = g.get_user()
    
    repo_name = 'test'
    
    # Check if repo non existant
    if repo_name not in [r.name for r in user.get_repos()]:
        # Create repository
        user.create_repo(repo_name)
    
    # Get repository
    repo = user.get_repo(repo_name)
    
    # File details
    file_name       = 'echo.py'
    file_content    = 'print("echo")'
    
    # Create file
    repo.create_file(file_name, 'commit', file_content)