问题描述
我在这里的许多其他问题中都看到过使用PyGithub进行提交的主题,但是这些问题都没有帮助我,我不理解解决方案,我想我太新了。
我只是想将计算机中的文件提交到我创建的测试github存储库中。到目前为止,我正在使用Google Collab笔记本进行测试。
这是我的代码,注释中有问题和疑问:
from github import Github
user = '***'
password = '***'
g = Github(user,password)
user = g.get_user()
# created a test repository
repo = user.create_repo('test')
# problem here,ask for an argument 'sha',what is this?
tree = repo.get_git_tree(???)
file = 'content/echo.py'
# since I didn't got the tree,this also goes wrong
repo.create_git_commit('test',tree,file)
解决方法
sha
是一个40个字符的校验和哈希,用作要获取的提交ID的唯一标识符(sha
也用于标识彼此的Git对象)。 / p>
从文档中
每个对象都由二进制SHA1哈希唯一标识,哈希大小为20字节,十六进制表示法为40字节。 Git只知道4种不同的对象类型,即Blob,Trees,Commits和Tag。
可以通过以下方式访问主要提交sha
:
headcommit = repo.head.commit
headcommit_sha = headcommit.hexsha
或通过以下方式访问主分支提交:
branch = repo.get_branch("master")
master_commit = branch.commit
您可以通过以下方式查看所有现有分支机构:
for branch in user.repo.get_branches():
print(f'{branch.name}')
您还可以在要获取的存储库中查看所需分支的sha
。
get_git_tree
使用给定的sha
标识符,并从文档中返回github.GitTree.GitTree
:
Git树对象在Git存储库中的文件之间创建层次结构
您会在docs tutorial中找到更多有趣的信息。
用于创建存储库并在Google CoLab上提交新文件的代码:
!pip install pygithub
from github import Github
user = '****'
password = '****'
g = Github(user,password)
user = g.get_user()
repo_name = 'test'
# Check if repo non existant
if repo_name not in [r.name for r in user.get_repos()]:
# Create repository
user.create_repo(repo_name)
# Get repository
repo = user.get_repo(repo_name)
# File details
file_name = 'echo.py'
file_content = 'print("echo")'
# Create file
repo.create_file(file_name,'commit',file_content)