Home >Backend Development >Golang >Tree SHA is not a tree object error in go-github library
When using the go-github library, you may encounter an error called "Tree SHA is not a tree object". This error occurs because the SHA value you supplied is not a valid tree object. Typically, this error can be caused by a file or directory that doesn't exist, a wrong SHA value, or some other issue. To resolve this issue, you can check that the SHA value you provided is correct and ensure that the relevant file or directory exists. If the problem persists, you can check the go-github repository's documentation or ask for help for further solutions. PHP editor Yuzi hopes this short guide will be helpful to you!
I'm 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: ¤ttime, }, committer: &github.commitauthor{ name: github.string(prcommitterauthorname), email: github.string(prcommitterauthorname), date: ¤ttime, }, 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 }
fail
newcommitresponse, _, err := client.git.createcommit(ctx, owner, repo, newcommit)
and
422 Tree SHA is not a tree object []
I can't find any relevant information about this error anywhere.
Any ideas?
When you use git cli, git itself will run a "meaningful" translation - for example: replace the commit with the sha of the relevant tree.
Using this lower-level API, you must do this conversion explicitly.
Using go-github
, you can do this with an additional query:
commit, _, err := client.Git.GetCommit(ctx, owner, repo, latestCommitSHA) if err != nil { return "", err } treeSHA := commit.GetTree().GetSHA()
The above is the detailed content of Tree SHA is not a tree object error in go-github library. For more information, please follow other related articles on the PHP Chinese website!