is there a way to verify if a git sha belongs to a git branch with go-github client?

131 Views Asked by At

would like to use go GitHub client to get result like git branch -r origin/<branch> --contains <sha>

1

There are 1 best solutions below

1
On

is there a way to verify if a git sha belongs to a git branch with go-github client?

I don't seem to be able to find an API endpoint that would specifically answer whether the SHA belongs to the branch or not, so you would have to iterate over commit within the branch. Something like:

func main() {
    ctx := context.Background()
    sts := oauth2.StaticTokenSource(
        &oauth2.Token{AccessToken: "<token>"},
    )
    tc := oauth2.NewClient(ctx, sts)
    client := github.NewClient(tc)

    repoOwner := "<owner>"
    repoName := "<repo>"
    branchToSearch := "<branch>"
    shaToFind := "<sha>"
    resultsPerPage := 25

    listOptions := github.ListOptions{PerPage: resultsPerPage}

    for {
        rc, resp, err := client.Repositories.ListCommits(ctx,
            repoOwner,
            repoName,
            &github.CommitsListOptions{
                SHA:         branchToSearch,
                ListOptions: listOptions,
            },
        )
        if err != nil {
            log.Panic(err)
        }

        for _, c := range rc {
            if *c.SHA == shaToFind {
                log.Printf("FOUND commit \"%s\" in the branch \"%s\"\n", shaToFind, branchToSearch)
                return
            }
        }

        if resp.NextPage == 0 {
            break
        }
        listOptions.Page = resp.NextPage
    }

    log.Printf("NOT FOUND commit \"%s\" in the branch \"%s\"\n", shaToFind, branchToSearch)
}