Home  >  Article  >  Backend Development  >  Unable to create commit with go-github and 422 - update is not fast forward

Unable to create commit with go-github and 422 - update is not fast forward

PHPz
PHPzforward
2024-02-09 17:12:19692browse

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

php editor Xiaoxin encountered a problem when using go-github: when creating a submission, a 422 error occurred and it was prompted that "the update is not fast forward". What is the specific cause of this problem? How to solve it? Next, we will give you detailed answers.

Question content

I use the following function to simply create a new commit in a branch using the go-github library

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
}

This operation failed:

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 []

Why not fast forward? It's just a new commit created from an existing branch/commit.

ps: I definitely don't want a new file to be created on commit.

Solution

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

Parameterscommit are used to specify some information about the new commit, including the parents of the new commit (see Implementation).

In your code, the new commit and the old commit have the same parents, so this is not a fast-forward push to the branch. To make it push to the branch quickly, the parents of the new commit should point to the old commit.

I guess the following changes will make it fast forward:

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

The above is the detailed content of Unable to create commit with go-github and 422 - update is not fast forward. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete