我在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,更具体地说是PyGithub,将3个新文件上传到我的GitHub。这是我尝试过的方法:
#!/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。
sha
,你需要使用hashlib
。 - Wayne Wernersha
是由git
计算的,如果你试图自己计算它,几乎肯定会出错。 - Brian Malehornsha1sum
计算git哈希值了吗?如果是的话,我对你准确地得到格式感到印象深刻。 - Brian Malehorngit
接口呢?或者使用像 GitPython 这样的 Python 接口,不一定是面向 GitHub 的?它的文档确实非常稀少,我不会称之为可用。 - MayeulCcreate_git_tree
,将HEAD的树作为基础,并给它一个InputGitTreeElement
列表(设置content
,但保留sha
),并进行修改。然后使用新树调用create_git_commit
。最后,您需要获取分支引用并将其更新为新的提交sha
。不过,找到一些包装此库的库可能比自己编写更容易。 - Hasturkun