【问题标题】:Creating a repository and commiting a file with PyGithub使用 PyGithub 创建存储库并提交文件
【发布时间】:2020-08-28 04:52:15
【问题描述】:

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

我只想将文件从我的计算机提交到我创建的测试 github 存储库。到目前为止,我正在使用 Google Collab 笔记本进行测试。

这是我的代码,问题和问题在 cmets 中:

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)

【问题讨论】:

    标签: python git google-colaboratory pygithub


    【解决方案1】:

    sha 是一个 40 个字符的校验和哈希,用作您要获取的提交 ID 的唯一标识符(sha 也用于识别其他 Git 对象)。

    来自文档:

    每个对象都由二进制 SHA1 哈希唯一标识,大小为 20 个字节,或十六进制表示法为 40 个字节。 Git 只知道 4 种不同的对象类型,即 Blob、树、提交和标签。

    头部提交 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)
    

    【讨论】:

    • 嗨!如何使用 PyGithub 获取 sha?
    • 嗨@EduardoValentindosSantos,添加了更多解释
    • 你好,headcommit部分有问题,我的程序指责'Repository'对象没有属性'head'
    • @EduardoValentindosSantos 也许他们称之为master,添加了更多解释。
    • 很遗憾,还是没有得到我想要的结果
    猜你喜欢
    • 1970-01-01
    • 2015-04-24
    • 2018-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-29
    相关资源
    最近更新 更多