登录
首页 >  Golang >  Go问答

无法使用 go-github 和 422 创建提交 - 更新不是快进

来源:stackoverflow

时间:2024-03-16 13:03:28 121浏览 收藏

在使用 go-github 库创建提交时,遇到了 422 错误,原因是提交不是快速推进。快速推进意味着新提交是现有分支的直接后继,而当前情况并非如此。为了使提交快速推进,新提交的父提交应指向现有分支的当前提交。

问题内容

我使用以下函数简单地使用 go-github 库在分支中创建一个新提交

func ghapicreatecommit(ctx context.context, client *github.client, commitopts *commitoptions) error {
    // get the reference of the branch
    ref, _, err := client.git.getref(ctx, repoowner, commitopts.repo, "refs/heads/"+commitopts.branch)
    if err != nil {
        return err
    }
    commit, _, err := client.git.getcommit(ctx, repoowner, commitopts.repo, *ref.object.sha)
    if err != nil {
        return err
    }

    commit.message = github.string(commitopts.commitmessage)

    // create a new commit with the updated commit message
    newcommit, _, err := client.git.createcommit(ctx, repoowner, commitopts.repo, commit)
    if err != nil {
        return err
    }
    // attach the new commit to the reference
    ref.object.sha = newcommit.sha

    // update the branch reference to point to the new commit
    _, _, err = client.git.updateref(ctx, repoowner, commitopts.repo, ref, false)
    if err != nil {
        return err
    }

    return nil
}

此操作失败:

PATCH https://api.github.com/repos/MyOrg/myrepo/git/refs/heads/the-branch-I-am-creating-the-new-commit-to: 422 Update is not a fast forward []

为什么不快进?它只是从现有分支/提交创建的新提交。

ps:我明确不想想要在提交时创建新文件。


正确答案


func (s *gitservice) createcommit(ctx context.context, owner string, repo string, commit *commit) (*commit, *response, error)

参数commit用于指定新commit的一些信息,包括新commit的parents(参见实现)。

在您的代码中,新提交和旧提交具有相同的 parents,因此这不是快进推送到分支。为了使其快速推送到分支,新提交的 parents 应指向旧提交。

我想以下更改会使其快进:

+ commit.Parents = []*github.Commit{commit}
  newCommit, _, err := client.Git.CreateCommit(ctx, repoOwner, commitOpts.Repo, commit)

到这里,我们也就讲完了《无法使用 go-github 和 422 创建提交 - 更新不是快进》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>