gitgogithubgo-github

Tree SHA is not a tree object error in go-github library


I am trying to create an empty commit in GitHub using go-github.

The following code:

func createHeadBranchForPR(ctx context.Context, baseBranch, repo, owner string,
    client *github.Client) (newBranch string, err error) {
    newBranch = createRandomBranchName()
    baseBranchRef, _, err := client.Git.GetRef(ctx, owner, repo, "heads/"+baseBranch)
    if err != nil {
        return "", err
    }
    latestCommitSHA := baseBranchRef.Object.GetSHA()
    // Create a new tree with no changes from the latest commit on the base branch
    newTree := &github.Tree{
        SHA: &latestCommitSHA,
    }
    currentTime := time.Now()
    newCommit := &github.Commit{
        Message: github.String("Test commit"),
        Tree:    newTree,
        Parents: []github.Commit{
            {
                SHA: github.String(latestCommitSHA),
            },
        },
        Author: &github.CommitAuthor{
            Name:  github.String(prCommitterAuthorName),
            Email: github.String(prCommitterAuthorEmail),
            Date:  &currentTime,
        },
        Committer: &github.CommitAuthor{
            Name:  github.String(prCommitterAuthorName),
            Email: github.String(prCommitterAuthorName),
            Date:  &currentTime,
        },
        SHA: &latestCommitSHA,
    }
    newCommitResponse, _, err := client.Git.CreateCommit(ctx, owner, repo, newCommit)
    if err != nil {
        return "", err
    }
    // Create a new branch based on the new commit
    newBranchRef := &github.Reference{
        Ref:    github.String("refs/heads/" + newBranch),
        Object: &github.GitObject{SHA: newCommitResponse.SHA},
    }
    _, _, err = client.Git.CreateRef(ctx, owner, repo, newBranchRef)
    if err != nil {
        return "", err
    }
    return newBranch, nil
}

Fails in

newCommitResponse, _, err := client.Git.CreateCommit(ctx, owner, repo, newCommit)

with

422 Tree SHA is not a tree object []

I cannot find any relevant info anywhere about this error.

Any ideas?


Solution

  • When you go through git cli, git itself runs the translations that "makes sense" -- e.g: replace a commit with the sha of its tree where relevant.


    Using this lower level API, you have to do this translation explicitly.

    Using go-github, you can do this with one extra query:

    commit, _, err := client.Git.GetCommit(ctx, owner, repo, latestCommitSHA)
    if err != nil {
       return "", err
    }
    
    treeSHA := commit.GetTree().GetSHA()