简体   繁体   中英

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

想使用 go GitHub 客户端来获得像git branch -r origin/<branch> --contains <sha>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM