0

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

shakalaka
  • 151
  • 1
  • 7

1 Answers1

0

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)
}

jabbson
  • 4,390
  • 1
  • 13
  • 23
  • This is the right answer; there is no such endpoint. However, this is inefficient and will likely lead to hitting the rate limit. A partial clone would be the most lightweight way to answer this question. – bk2204 Oct 27 '21 at 22:44