繁体   English   中英

如何将新文件推送到 GitHub?

[英]How do I push new files to GitHub?

我在 github.com 上创建了一个新的存储库,然后将它克隆到我的本地机器上

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

我在文件夹mathematics下添加了3个新文件

$ tree 
.
├── LICENSE
├── numerical_analysis
│   └── regression_analysis
│       ├── simple_regression_analysis.md
│       ├── simple_regression_analysis.png
│       └── simple_regression_analysis.py

现在,我想使用 Python 将 3 个新文件上传到我的 GitHub,更具体地说,是PyGithub 这是我尝试过的:

#!/usr/bin/env python
# *-* coding: utf-8 *-*
from github import Github

def main():
    # Step 1: Create a Github instance:
    g = Github("usrname", "passwd")
    repo = g.get_user().get_repo('mathematics')

    # Step 2: Prepare files to upload to GitHub
    files = ['mathematics/numerical_analysis/regression_analysis/simple_regression_analysis.py', 'mathematics/numerical_analysis/regression_analysis/simple_regression_analysis.png']

    # Step 3: Make a commit and push
    commit_message = 'Add simple regression analysis'

    tree = repo.get_git_tree(sha)
    repo.create_git_commit(commit_message, tree, [])
    repo.push()

if __name__ == '__main__':
    main()

我不知道

  • 如何获取repo.get_git_tree的字符串sha
  • 如何在第 2 步和第 3 步之间建立连接,即推送特定文件

就个人而言, PyGithub 文档不可读。 找了好久都没找到合适的api。

我尝试使用GitHub API提交多个文件。 Git Data API 的这个页面说它应该“非常简单”。 有关该调查的结果,请参阅此答案

我建议使用类似GitPython 的东西:

from git import Repo

repo_dir = 'mathematics'
repo = Repo(repo_dir)
file_list = [
    'numerical_analysis/regression_analysis/simple_regression_analysis.py',
    'numerical_analysis/regression_analysis/simple_regression_analysis.png'
]
commit_message = 'Add simple regression analysis'
repo.index.add(file_list)
repo.index.commit(commit_message)
origin = repo.remote('origin')
origin.push()

注意:此版本的脚本在存储库的父目录中运行。

注意:此版本的脚本是从 GIT 存储库内部调用的,因为我从文件路径中删除了存储库名称。

我终于想出了如何使用PyGithub提交多个文件:

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)

如果我尝试从一个PNG文件添加的原始数据,调用create_git_tree最终调用json.dumpsRequester.py ,这将导致以下异常升高:

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

我通过对 PNG 数据进行base64编码并提交来解决这个问题。 后来,我使用update_file方法来更改 PNG 数据。 这会导致对存储库的两次单独提交,这可能不是您想要的。

我可以给你一些信息支持,但也有一个具体的解决方案。

在这里您可以找到将新文件添加到存储库的示例, 这里有一个视频教程。

您可以在下面看到在 GitHub 的开发人员页面上找到的与 GitHub 一起使用的 Python 包列表:

但是,如果需要,您也可以使用 IPython 中的命令推送文件:

In [1]: import subprocess
In [2]: print subprocess.check_output('git init', shell=True)
Initialized empty Git repository in /home/code/.git/
In [3]: print subprocess.check_output('git add .', shell=True)
In [4]: print subprocess.check_output('git commit -m "a commit"', shell=True)

使用子流程,这将完成相同的工作-

import subprocess
subprocess.call(['git', 'add', '-A'])
subprocess.call(['git', 'commit', '-m', '{}'.format(commit_message)])
subprocess.call(['git', 'push', 'https://{}@github.com/user-name/repo.git'.format(token)])

确保使用 -A 或 -all 来跟踪项目/甚至父目录中的所有文件。 使用 'git add .' 将仅跟踪写入此代码的 cwd 内的文件。

import subprocess
p = subprocess.Popen("git rev-parse HEAD".split(), stdout=subprocess.PIPE)
out, err = p.communicate()
sha = out.strip()

使用 PyGithub 可能有一种方法可以做到这一点,但这应该适用于快速破解。

如果您不需要 pygithub,dulwich git-library 提供了高级 git 命令 有关命令,查看https://www.dulwich.io/apidocs/dulwich.porcelain.html

如果 PyGithub 的文档不可用(而且看起来不像),而您只想推送提交(不对问题、存储库配置等做任何花哨的事情),您可能最好直接与 git 交互,要么调用git可执行文件,要么使用包装库,例如GitPython

直接将git与诸如subprocess.Popen东西一起使用在倾斜曲线上可能会更容易,但从长远来看,错误处理等也会更困难,因为您实际上没有很好的抽象可以传递,并且将不得不自己进行解析。

摆脱 PyGithub 还可以让您摆脱与 GitHub 及其 API 的绑定,允许您推送到任何存储库,甚至是计算机上的另一个文件夹。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM