如何使用GitHub Rest Api在GitHub中创建子模块

Hua*_*hao 3 github-api

我发现GitHub有Create TreeCreate File API,但我仍然不确定如何创建子模块项,对于Create Tree Api,如何指定Sha,对于Create File Api,似乎我们无法设置项类型.顺便说一句,我是否需要先创建.gitmodules文件?

Che*_*Hsu 7

我今天早些时候试图这样做.

这是我的工作流程:

  1. 创建一个树
  2. 创建一个提交
  3. 更新参考

让我举一个例子来说明一点.

master要添加子模块的repo分支上的最新提交是$BASE_SHA.


1.创建一棵树

假设你的repo上还没有任何子模块,你需要创建一个名为.gitmodulesfirst 的文件.然后你可以创建它的引用.

POST /repos/:owner/:repo/git/trees
{
    "base_tree": $BASE_SHA,
    "tree": [
        // create submodule config
        {
            "path": ".gitmodules",
            "mode": "100644",
            "type": "blob",
            "content": "[submodule \"rails\"]\n\tpath = rails\n\turl = https://github.com/rails/rails"
        },
        // link to submodule
        {
            "path": "rails",
            "mode": "160000", 
            "type": "commit",
            "sha": "39e087cbf5628ecc351fc86a3a1e320be193bf29"
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

然后,API服务器将向您发送响应

{
  "sha": $TREE_SHA,
  "url": "...",
  "tree": [...]
}
Run Code Online (Sandbox Code Playgroud)



2.创建提交

然后,我们使用sha新创建的树来创建提交($BASE_SHA作为其父级).

POST /repos/:owner/:repo/git/commits
{
    "message": "commit message",
    "tree": $TREE_SHA,
    "parents": [$BASE_SHA]
}
Run Code Online (Sandbox Code Playgroud)

服务器将返回

{
    "sha": $COMMIT_SHA,
    "url": "...",
    // other content omitted here ..
}
Run Code Online (Sandbox Code Playgroud)

3.更新参考

然后我们需要更新master.

PATCH /repos/:owner/:repo/git/refs/heads/master
{
    "sha": $COMMIT_SHA,
    "force": true
}
Run Code Online (Sandbox Code Playgroud)

如果没有返回错误,我们都会设置好.

刷新您的GitHub仓库页面,您会发现添加了子模块.