如何通过github rest api将子模块更新为指定的提交?

时间:2017-08-21 05:28:56

标签: git rest github

有两个github回购:A& B. A将B作为其子模块。

https://github.com/org_name/A.git

https://github.com/org_name/B.git

A:
 B@defad9     // a submodule in A

情况就是这样,B和PR(#1)的变更提交了。现在我想用A的最新更改在A上运行构建。是否有一个github rest api可以执行更新而不是git子模块更新...?

3 个答案:

答案 0 :(得分:6)

我将Jason描述的GitHub调用整理成一个Transposit应用程序,该应用程序可用作GitHub Webhook,以便在子模块更新时自动更新父仓库中的子模块sha。

Transposit托管我的javascript函数,并具有一个JavaScript API,可用于调用GitHub的REST API。该函数在提交到子模块时由webhook调用,在这里它获取子模块存储库的最新SHA,将父存储库中的树更新为新的sha并提交。

(params) => {
     let owner = env.get('parentOwner');
     let repo = env.get('parentRepo');
     let branch = env.get('parentBranch');
     let submoduleOwner = env.get('submoduleOwner');
     let submoduleRepo = env.get('submoduleRepo');
     let submoduleBranch = env.get('submoduleBranch');  
     let submodulePath = env.get('submodulePath');

     let parentSha = api.run('github.get_branch_for_repo', {owner, repo, branch})[0].commit.sha;
     let submoduleSha = api.run('github.get_branch_for_repo', {owner: submoduleOwner, repo: submoduleRepo, branch: submoduleBranch})[0].commit.sha;

     let treeSha = api.run('github.create_git_tree', {
       owner: owner,
       repo: repo,
       $body: {
         "base_tree": parentSha,
         "tree": [
             {
                 "path": submodulePath,
                 "mode": "160000", 
                 "type": "commit",
                 "sha": submoduleSha
             }
         ]
       }
     })[0]

     let commitSha = api.run('github.create_git_commit', {
       owner: owner,
       repo: repo,
       $body: {
         "message": `Auto-update submodule ${submoduleOwner}/${submoduleRepo} to ${submoduleSha}`,
         "tree": treeSha.sha,
         "parents": [parentSha]
       }
     })[0]

     let editSha = api.run('github.edit_git_ref', {
       owner: owner,
       ref: `heads/${branch}`,
       repo: repo,
       $body: {
         "sha": commitSha.sha
       }
     })
     return editSha;
   }

有关如何使用此Webhook的更多信息,请参见:https://www.transposit.com/blog/2019.08.23-github_submodule/

答案 1 :(得分:2)

我今天花了一些时间解决这个问题。首先,获取父仓库的提交哈希值:

GET /repos/:owner/:REPO_A/branches/master

$PARENT_SHA = {commit.sha}

您还需要从子模块存储库中提交您想要更新为的提交:

GET /repos/:owner/:REPO_B/branches/master

$TARGET_SHA = {commit.sha}

接下来,您将创建一个git树来更新子模块引用:

POST /repos/:owner/:REPO_A/git/trees
{
    "base_tree": $PARENT_SHA,
    "tree": [
        {
            "path": "path/to/submodule",
            "mode": "160000", 
            "type": "commit",
            "sha": $TARGET_SHA
        }
    ]
}

$TREE_SHA = {sha}

现在您可以提交树了:

POST /repos/:owner/:REPO_A/git/commits
{
    "message": "Synchronize Handbook",
    "tree": $TREE_SHA,
    "parents": [$PARENT_SHA]
}

$COMMIT_SHA = {sha}

最后,更新master以指向您的新提交:

PATCH /repos/:owner/:REPO_A/git/refs/heads/master
{
    "sha": $COMMIT_SHA
}

答案 2 :(得分:0)

我不知道:您需要在本地执行git submodule update --remote才能更新B(假设最新更改已在master上完成)。
然后添加,提交并按A以便为B记录新的gitlink。