Skip to content
Advertisement

Create/Update .json file to GitHub Private Repository without making local working directory or cloning repo using Python

I am having a GitHub Private Repository which has 3 .json files on its parent directory. Suppose the three json files are:

1.json
2.json
3.json

I am trying to write a function through which I can just push any one of the .json file through the python function with contents and it makes a commit and push the changes.

I tried using solution from this but it seems outdated or unsupported: Python update files on Github remote repo without local working directory

Function should be liked this:

def update_file_to_repo(file_name,file_content):
    # Do the push..

file_name has the 1.json or any other file name as string and file_content has contents as string imported through json.dumps() by me in main function..

Advertisement

Answer

Though I didn’t found any ways to do it without cloning the repo in local directory

However, here’s the way if you wanted to do while using a local directory:

Function for cloning the private repo to local directory. You will also need to create a Personal Access Token(you can create here) and make sure to give repo permissions for cloning and making changes to the private repo.

def initialize_repo():
    os.system("git config --global user.name "your.username"")
    os.system("git config --global user.email "your_github_email_here"")
    os.system(r"git clone https://username:token@github.com/username/repo.git folder-name")

Function for pulling the repo:

def pull_repo():
    os.system(r"cd /app/folder-name/ && git pull origin master")
    return

Function for pushing the repo:

def push(pull="no"):
    PATH_OF_GIT_REPO = r'/app/folder-name/.git'  # make sure .git folder is properly configured
    COMMIT_MESSAGE = 'commit done by python script'
    # try:
    repo = Repo(PATH_OF_GIT_REPO)
    if pull=="yes":
        pull_repo()
    repo.git.add(update=True)
    repo.index.commit(COMMIT_MESSAGE)
    origin = repo.remote(name='origin')
    origin.push()
    # except:
    #     print('Some error occured while pushing the code')    
    return

Now using these functions, just make a pull, then make the changes to the json or any other file you want and then do the push :)

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement