有两个 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 上运行一个包含 B 的最新更改的构建。是否有 github Rest api 可以执行更新而不是 git submodule update...?
我今天花了一些时间来解决这个问题。首先,获取父存储库的提交哈希:
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
}
我将 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/
据我所知,您需要在本地执行
git submodule update --remote
才能更新 B(假设最新更改是在 master
上完成的)。此代码片段使用 PyGithub 在 Python 中执行此操作
new_tree = repo.create_git_tree( [github.InputGitTreeElement(path=submodule_path, mode='160000', type='commit', sha=commit_sha)], base_tree)