How do I push new files to GitHub?

后端 未结 6 880
独厮守ぢ
独厮守ぢ 2020-12-08 22:31

I created a new repository on github.com and then cloned it to my local machine with

git clone https://github.com/usrname/mathematics.git

I

6条回答
  •  时光取名叫无心
    2020-12-08 22:55

    Note: This version of the script was called from inside the GIT repository because I removed the repository name from the file paths.

    I finally figured out how to use PyGithub to commit multiple files:

    import base64
    from github import Github
    from github import InputGitTreeElement
    
    token = '5bf1fd927dfb8679496a2e6cf00cbe50c1c87145'
    g = Github(token)
    repo = g.get_user().get_repo('mathematics')
    file_list = [
        'numerical_analysis/regression_analysis/simple_regression_analysis.png',
        'numerical_analysis/regression_analysis/simple_regression_analysis.py'
    ]
    commit_message = 'Add simple regression analysis'
    master_ref = repo.get_git_ref('heads/master')
    master_sha = master_ref.object.sha
    base_tree = repo.get_git_tree(master_sha)
    element_list = list()
    for entry in file_list:
        with open(entry, 'rb') as input_file:
            data = input_file.read()
        if entry.endswith('.png'):
            data = base64.b64encode(data)
        element = InputGitTreeElement(entry, '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)
    """ An egregious hack to change the PNG contents after the commit """
    for entry in file_list:
        with open(entry, 'rb') as input_file:
            data = input_file.read()
        if entry.endswith('.png'):
            old_file = repo.get_contents(entry)
            commit = repo.update_file('/' + entry, 'Update PNG content', data, old_file.sha)
    

    If I try to add the raw data from a PNG file, the call to create_git_tree eventually calls json.dumps in Requester.py, which causes the following exception to be raised:

    UnicodeDecodeError: 'utf8' codec can't decode byte 0x89 in position 0: invalid start byte

    I work around this problem by base64 encoding the PNG data and committing that. Later, I use the update_file method to change the PNG data. This results in two separate commits to the repository which is probably not what you want.

提交回复
热议问题