github.com/decred/politeia@v1.4.0/politeiawww/legacy/codetracker/github/api/commit.go (about) 1 // Copyright (c) 2020 The Decred developers 2 // Use of this source code is governed by an ISC 3 // license that can be found in the LICENSE file. 4 5 package api 6 7 import ( 8 "encoding/json" 9 "fmt" 10 "net/http" 11 ) 12 13 const ( 14 apiCommitURL = `https://api.github.com/repos/%s/%s/commits/%s` 15 apiPullRequestCommitsURL = `https://api.github.com/repos/%s/%s/pulls/%d/commits?per_page=250&page=%d&sort=updated&direction=desc` 16 ) 17 18 // FetchCommit requests a given commit based on organization, repo and hash 19 func (a *Client) FetchCommit(org, repo string, sha string) (*PullRequestCommit, error) { 20 url := fmt.Sprintf(apiCommitURL, org, repo, sha) 21 req, err := http.NewRequest("GET", url, nil) 22 if err != nil { 23 return nil, err 24 } 25 body, err := a.sendGithubRequest(req) 26 if err != nil { 27 return nil, err 28 } 29 30 var commit PullRequestCommit 31 err = json.Unmarshal(body, &commit) 32 if err != nil { 33 return nil, err 34 } 35 36 return &commit, nil 37 } 38 39 // FetchPullRequestCommits requests all of the commit hashes under a given pull 40 // request based on the organization, repo, and pull request number. 41 func (a *Client) FetchPullRequestCommitSHAs(org, repo string, prNum int) ([]string, error) { 42 totalPullRequestSHAs := make([]string, 0, 1048) 43 page := 1 44 for { 45 url := fmt.Sprintf(apiPullRequestCommitsURL, org, repo, prNum, page) 46 req, err := http.NewRequest("GET", url, nil) 47 if err != nil { 48 return nil, err 49 } 50 body, err := a.sendGithubRequest(req) 51 if err != nil { 52 return nil, err 53 } 54 55 var pullRequestCommits []PullRequestCommit 56 err = json.Unmarshal(body, &pullRequestCommits) 57 if err != nil { 58 return nil, err 59 } 60 61 // no more left 62 if len(pullRequestCommits) == 0 { 63 break 64 } 65 prSHAs := make([]string, 0, len(pullRequestCommits)) 66 for _, commit := range pullRequestCommits { 67 prSHAs = append(prSHAs, commit.SHA) 68 } 69 totalPullRequestSHAs = append(totalPullRequestSHAs, prSHAs...) 70 page++ 71 } 72 return totalPullRequestSHAs, nil 73 } 74 75 // FetchPullRequestCommits returns a list of parsed commits based on org, 76 // repo and a list of hashes provided in the arguments. 77 func (a *Client) FetchPullRequestCommits(org, repo string, hashes []string) ([]*PullRequestCommit, error) { 78 var totalCommits []*PullRequestCommit 79 for _, sha := range hashes { 80 commit, err := a.FetchCommit(org, repo, sha) 81 if err != nil { 82 log.Errorf("unable to fetch commit %v %v %v", org, repo, sha) 83 continue 84 } 85 totalCommits = append(totalCommits, commit) 86 } 87 return totalCommits, nil 88 }