如何使用GitHub API v3创建提交并推送到repo?

时间:2012-08-03 19:18:19

标签: python github github-api

我想创建一个存储库并通过任何Python包向它提交一些文件。我该怎么办?

我不明白如何为提交添加文件。

6 个答案:

答案 0 :(得分:9)

您可以查看新更新GitHub CRUD API (May 2013)是否可以提供帮助

  

repository contents API允许读取文件一段时间。现在,您可以轻松地将更改提交到单个文件,就像在Web UI中一样。

     

从今天开始,您可以使用以下方法:

     

答案 1 :(得分:6)

Github提供Git database API,使您可以访问读取和写入原始对象,以及列出和更新引用(分支头和标记)。为了更好地理解该主题,我强烈建议您阅读Pro Git书的Git Internals章。

根据文档,将更改提交到存储库中的文件是一个7步骤的过程:

  
      
  1. 获取当前提交对象
  2.   
  3. 检索它指向的树
  4.   
  5. 检索树对该特定文件路径的blob对象的内容
  6.   
  7. 以某种方式更改内容并使用该新内容发布新的blob对象,然后获取blob SHA
  8.   
  9. 发布一个新的树对象,该文件路径指针替换为新的blob SHA,使树回SHA
  10.   
  11. 使用当前提交SHA作为父树和新树SHA创建一个新提交对象,获取提交SHA
  12.   
  13. 更新分支的引用以指向新提交SHA
  14.   

This blog在使用perl解释此过程方面做得很好。对于python实现,您可以使用PyGithub库。

答案 2 :(得分:6)

这是一个完整的代码段:

def push_to_github(filename, repo, branch, token):
    url="https://api.github.com/repos/"+repo+"/contents/"+filename

    base64content=base64.b64encode(open(filename,"rb").read())

    data = requests.get(url+'?ref='+branch, headers = {"Authorization": "token "+token}).json()
    sha = data['sha']

    if base64content.decode('utf-8')+"\n" != data['content']:
        message = json.dumps({"message":"update",
                            "branch": branch,
                            "content": base64content.decode("utf-8") ,
                            "sha": sha
                            })

        resp=requests.put(url, data = message, headers = {"Content-Type": "application/json", "Authorization": "token "+token})

        print(resp)
    else:
        print("nothing to update")

token = "lskdlfszezeirzoherkzjehrkzjrzerzer"
filename="foo.txt"
repo = "you/test"
branch="master"

push_to_github(filename, repo, branch, token)

答案 3 :(得分:3)

使用请求库的解决方案:

注意:我使用requests库对GitHub REST API v3进行了调用。

1。获取特定分支的最后一次提交SHA

# GET /repos/:owner/:repo/branches/:branch_name
last_commit_sha = response.json()['commit']['sha']

2。使用文件内容(编码为base64或utf-8)创建blob

# POST /repos/:owner/:repo/git/blobs
# {
#  "content": "aGVsbG8gd29ybGQK",
#  "encoding": "base64"
#}
base64_blob_sha = response.json()['sha']

# POST /repos/:owner/:repo/git/blobs
# {
#  "content": "hello world",
#  "encoding": "utf-8"
#}
utf8_blob_sha = response.json()['sha']

3。创建定义文件夹结构的树

# POST repos/:owner/:repo/git/trees/
# {
#   "base_tree": last_commit_sha,
#   "tree": [
#     {
#       "path": "myfolder/base64file.txt",
#       "mode": "100644",
#       "type": "blob",
#       "sha": base64_blob_sha
#     },
#     {
#       "path": "file-utf8.txt",
#       "mode": "100644",
#       "type": "blob",
#       "sha": utf8_blob_sha
#     }
#   ]
# }
tree_sha = response.json()['sha']

4。创建提交

# POST /repos/:owner/:repo/git/commits
# {
#   "message": "Add new files at once programatically",
#   "author": {
#     "name": "Jan-Michael Vincent",
#     "email": "JanQuadrantVincent16@rickandmorty.com"
#   },
#   "parents": [
#     last_commit_sha
#   ],
#   "tree": tree_sha
# }
new_commit_sha = response.json()['sha']

5。更新分支的引用以指向新的提交SHA(在主分支示例上)

# POST /repos/:owner/:repo/git/refs/heads/master
# {
#     "ref": "refs/heads/master",
#     "sha": new_commit_sha
# }

最后,要进行更高级的设置,请阅读docs

答案 4 :(得分:1)

根据先前的答案,这是一个完整的示例。请注意,如果将提交上载到新分支,则需要使用POST,或者如果将上载到现有分支,则需要使用PATCH


    import whatsneeded
    
    GITHUB_TOKEN = "WHATEVERWILLBEWILLBE"
    
    def github_request(method, url, headers=None, data=None, params=None):
        """Execute a request to the GitHUB API, handling redirect"""
        if not headers:
            headers = {}
        headers.update({
            "User-Agent": "Agent 007",
            "Authorization": "Bearer " + GITHUB_TOKEN,
        })
    
        url_parsed = urllib.parse.urlparse(url)
        url_path = url_parsed.path
        if params:
            url_path += "?" + urllib.parse.urlencode(params)
    
        data = data and json.dumps(data)
        conn = http.client.HTTPSConnection(url_parsed.hostname)
        conn.request(method, url_path, body=data, headers=headers)
        response = conn.getresponse()
        if response.status == 302:
            return github_request(method, response.headers["Location"])
    
        if response.status >= 400:
            headers.pop('Authorization', None)
            raise Exception(
                f"Error: {response.status} - {json.loads(response.read())} - {method} - {url} - {data} - {headers}"
            )
    
        return (response, json.loads(response.read().decode()))
      
    def upload_to_github(repository, src, dst, author_name, author_email, git_message, branch="heads/master"):
        # Get last commit SHA of a branch
        resp, jeez = github_request("GET", f"/repos/{repository}/git/ref/{branch}")
        last_commit_sha = jeez["object"]["sha"]
        print("Last commit SHA: " + last_commit_sha)
    
        base64content = base64.b64encode(open(src, "rb").read())
        resp, jeez = github_request(
            "POST",
            f"/repos/{repository}/git/blobs",
            data={
                "content": base64content.decode(),
                "encoding": "base64"
            },
        )
        blob_content_sha = jeez["sha"]
    
        resp, jeez = github_request(
            "POST",
            f"/repos/{repository}/git/trees",
            data={
                "base_tree":
                last_commit_sha,
                "tree": [{
                    "path": dst,
                    "mode": "100644",
                    "type": "blob",
                    "sha": blob_content_sha,
                }],
            },
        )
        tree_sha = jeez["sha"]
    
        resp, jeez = github_request(
            "POST",
            f"/repos/{repository}/git/commits",
            data={
                "message": git_message,
                "author": {
                    "name": author_name,
                    "email": author_email,
                },
                "parents": [last_commit_sha],
                "tree": tree_sha,
            },
        )
        new_commit_sha = jeez["sha"]
    
        resp, jeez = github_request(
            "PATCH",
            f"/repos/{repository}/git/refs/{branch}",
            data={"sha": new_commit_sha},
        )
        return (resp, jeez)

答案 5 :(得分:0)

我在 Google App Engine (GAE) ,除了python,我可以create新文件update,甚至是delete it通过提交并使用php,java和go中的GitHub API v3在GitHub中推送到我的仓库。

检查并审核一些可用的第三方libraries以创建与perl中提供的example script类似的内容,我建议使用以下内容:

如您所知,您可以在每个GitHub帐户和组织中获得一个网站,以及无限制的项目网站,其中网站直接从您的仓库托管,并由Jekyll作为默认设置。

在GAE上结合JekyllWebhooks和GitHub API脚本,以及相应的 GAE Setting ,它将为您提供像{{{{{{ 3}}并在GitHub上创建一个动态页面。

除了GAE之外,还有一个选项可以在Heroku上运行。使用位于(免费)Heroku实例上的calling external script JekyllBot为每个帖子生成JSON文件并将更改推送回GitHub。