使用 PyGithub 创建存储库并提交文件

Creating a repository and commiting a file with PyGithub

我在这里的许多其他问题中看到了使用 PyGithub 进行提交的主题,但是其中 none 帮助了我,我不明白解决方案,我想我太新手了。

我只想将文件从我的计算机提交到我创建的测试 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对象也是如此)。

来自文档:

Each object is uniquely identified by a binary SHA1 hash, being 20 bytes in size, or 40 bytes in hexadecimal notation. Git only knows 4 distinct object types being Blobs, Trees, Commits and Tags.

head 提交 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 标识符和 returns 一个 github.GitTree.GitTree

Git tree object creates the hierarchy between files in a Git repository

您会在 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)