git 如何将新文件推送到 GitHub?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38594717/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I push new files to GitHub?
提问by SparkAndShine
I created a new repository on github.com and then cloned it to my local machine with
我在 github.com 上创建了一个新的存储库,然后将它克隆到我的本地机器上
git clone https://github.com/usrname/mathematics.git
I added 3 new files under the folder mathematics
我在文件夹下添加了 3 个新文件 mathematics
$ tree
.
├── LICENSE
├── numerical_analysis
│?? └── regression_analysis
│?? ├── simple_regression_analysis.md
│?? ├── simple_regression_analysis.png
│?? └── simple_regression_analysis.py
Now, I'd like to upload 3 new files to my GitHub using Python, more specifically, PyGithub. Here is what I have tried:
现在,我想使用 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()
I don't know
我不知道
- how to get the string
sha
forrepo.get_git_tree
- how do I make a connection between step 2 and 3, i.e. pushing specific files
- 如何获得字符串
sha
的repo.get_git_tree
- 如何在第 2 步和第 3 步之间建立连接,即推送特定文件
Personally, PyGithub documentationis not readable. I am unable to find the right api after searching for long time.
就个人而言,PyGithub 文档不可读。找了好久都没找到合适的api。
采纳答案by David Cullen
I tried to use the GitHub APIto commit multiple files. This page for the Git Data APIsays that it should be "pretty simple". For the results of that investigation, see this answer.
我尝试使用GitHub API来提交多个文件。Git Data API 的这个页面说它应该“非常简单”。有关该调查的结果,请参阅此答案。
I recommend using something like GitPython:
我建议使用类似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()
Note:This version of the script was run in the parent directory of the repository.
注意:此版本的脚本在存储库的父目录中运行。
回答by David Cullen
Note:This version of the script was called from inside the GIT repository because I removed the repository name from the file paths.
注意:此版本的脚本是从 GIT 存储库内部调用的,因为我从文件路径中删除了存储库名称。
I finally figured out how to use PyGithubto commit multiple files:
我终于想出了如何使用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)
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:
如果我尝试从 PNG 文件添加原始数据,则调用create_git_tree
最终会调用json.dumps
in Requester.py
,这会导致引发以下异常:
UnicodeDecodeError: 'utf8' codec can't decode byte 0x89 in position 0: invalid start byte
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.
我通过base64
编码 PNG 数据并提交来解决这个问题。后来,我使用该update_file
方法更改PNG数据。这会导致对存储库的两次单独提交,这可能不是您想要的。
回答by vlad.rad
I can give you some information support, but also one concrete solution.
我可以给你一些信息支持,但也有一个具体的解决方案。
Hereyou can find examples of adding new files to your repository, and hereis a video tutorial for this.
在这里您可以找到将新文件添加到存储库的示例,这里有一个视频教程。
Below you can see a list of python packages that work with GitHub found on the developer page of GitHub:
您可以在下面看到在 GitHub 的开发人员页面上找到的与 GitHub 一起使用的 Python 包列表:
But also you can push your files with commands in IPython if you need:
但是,如果需要,您也可以使用 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)
回答by MayeulC
If PyGithub's documentation is not usable (and it doesn't look so), and you just want to push a commit (not doing anything fancy with issues, repo configuration, etc.), you would probably be better off directly interfacing with git, either calling the git
executable or using a wrapper library such as GitPython.
如果 PyGithub 的文档不可用(而且看起来不像),而您只想推送提交(不对问题、repo 配置等做任何花哨的事情),您可能最好直接与 git 交互,要么调用git
可执行文件,要么使用包装库,例如GitPython。
Using git
directly with something such as subprocess.Popen
that you mentioned would probably be easier on the leaning curve, but also more difficult in the long term for error handling, etc. since you don't really have nice abstractions to pass around, and would have to do the parsing yourself.
使用git
直接的东西比如subprocess.Popen
你提到的很可能是偏曲线上更容易,但在长期的错误处理等方面也更困难,因为你真的没有很好的抽象来绕过,并且必须做自己解析。
Getting rid of PyGithub also frees you from being tied to GitHub and its API, allowing you to push to any repo, even another folder on your computer.
摆脱 PyGithub 还可以让您摆脱与 GitHub 及其 API 的绑定,允许您推送到任何存储库,甚至是计算机上的另一个文件夹。
回答by Brian Malehorn
import subprocess
p = subprocess.Popen("git rev-parse HEAD".split(), stdout=subprocess.PIPE)
out, err = p.communicate()
sha = out.strip()
There's probably a way to do this with PyGithub, but this should work for a quick hack.
使用 PyGithub 可能有一种方法可以做到这一点,但这应该适用于快速破解。
回答by janbrohl
If you do not need pygithub specifically, the dulwich git-library offers high level git commands. For the commands have a look at https://www.dulwich.io/apidocs/dulwich.porcelain.html
如果您不需要 pygithub,dulwich git-library 提供了高级 git 命令。有关命令,请查看https://www.dulwich.io/apidocs/dulwich.porcelain.html